babylon.max.js 5.6 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720117721117722117723117724117725117726117727117728117729117730117731117732117733117734117735117736117737117738117739117740117741117742117743117744117745117746117747117748117749117750117751117752117753117754117755117756117757117758117759117760117761117762117763117764117765117766117767117768117769117770117771117772117773117774117775117776117777117778117779117780117781117782117783117784117785117786117787117788117789117790117791117792117793117794117795117796117797117798117799117800117801117802117803117804117805117806117807117808117809117810117811117812117813117814117815117816117817117818117819117820117821117822117823117824117825117826117827117828117829117830117831117832117833117834117835117836117837117838117839117840117841117842117843117844117845117846117847117848117849117850117851117852117853117854117855117856117857117858117859117860117861117862117863117864117865117866117867117868117869117870117871117872117873117874117875117876117877117878117879117880117881117882117883117884117885117886117887117888117889117890117891117892117893117894117895117896117897117898117899117900117901117902117903117904117905117906117907117908117909117910117911117912117913117914117915117916117917117918117919117920117921117922117923117924117925117926117927117928117929117930117931117932117933117934117935117936117937117938117939117940117941117942117943117944117945117946117947117948117949117950117951117952117953117954117955117956117957117958117959117960117961117962117963117964117965117966117967117968117969117970117971117972117973117974117975117976117977117978117979117980117981117982117983117984117985117986117987117988117989117990117991117992117993117994117995117996117997117998117999118000118001118002118003118004118005118006118007118008118009118010118011118012118013118014118015118016118017118018118019118020118021118022118023118024118025118026118027118028118029118030118031118032118033118034118035118036118037118038118039118040118041118042118043118044118045118046118047118048118049118050118051118052118053118054118055118056118057118058118059118060118061118062118063118064118065118066118067118068118069118070118071118072118073118074118075118076118077118078118079118080118081118082118083118084118085118086118087118088118089118090118091118092118093118094118095118096118097118098118099118100118101118102118103118104118105118106118107118108118109118110118111118112118113118114118115118116
  1. (function universalModuleDefinition(root, factory) {
  2. var amdDependencies = [];
  3. var CANNON = root.CANNON || this.CANNON;
  4. var OIMO = root.OIMO || this.OIMO;
  5. var earcut = root.earcut || this.earcut;
  6. if(typeof exports === 'object' && typeof module === 'object') {
  7. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  8. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  9. try { earcut = earcut || require("earcut"); } catch(e) {}
  10. module.exports = factory(CANNON,OIMO,earcut);
  11. } else if(typeof define === 'function' && define.amd) {
  12. if(require.specified && require.specified("cannon")) amdDependencies.push("cannon");
  13. if(require.specified && require.specified("oimo")) amdDependencies.push("oimo");
  14. if(require.specified && require.specified("earcut")) amdDependencies.push("earcut");
  15. define("babylonjs", amdDependencies, factory);
  16. } else if(typeof exports === 'object') {
  17. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  18. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  19. try { earcut = earcut || require("earcut"); } catch(e) {}
  20. exports["babylonjs"] = factory(CANNON,OIMO,earcut);
  21. } else {
  22. root["BABYLON"] = factory(CANNON,OIMO,earcut);
  23. }
  24. })(this, function(CANNON,OIMO,earcut) {
  25. CANNON = CANNON || this.CANNON;
  26. OIMO = OIMO || this.OIMO;
  27. earcut = earcut || this.earcut;
  28. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  29. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  30. var BABYLON;
  31. (function (BABYLON) {
  32. /**
  33. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  34. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  35. */
  36. var EffectFallbacks = /** @class */ (function () {
  37. function EffectFallbacks() {
  38. this._defines = {};
  39. this._currentRank = 32;
  40. this._maxRank = -1;
  41. }
  42. /**
  43. * Removes the fallback from the bound mesh.
  44. */
  45. EffectFallbacks.prototype.unBindMesh = function () {
  46. this._mesh = null;
  47. };
  48. /**
  49. * Adds a fallback on the specified property.
  50. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  51. * @param define The name of the define in the shader
  52. */
  53. EffectFallbacks.prototype.addFallback = function (rank, define) {
  54. if (!this._defines[rank]) {
  55. if (rank < this._currentRank) {
  56. this._currentRank = rank;
  57. }
  58. if (rank > this._maxRank) {
  59. this._maxRank = rank;
  60. }
  61. this._defines[rank] = new Array();
  62. }
  63. this._defines[rank].push(define);
  64. };
  65. /**
  66. * Sets the mesh to use CPU skinning when needing to fallback.
  67. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  68. * @param mesh The mesh to use the fallbacks.
  69. */
  70. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  71. this._mesh = mesh;
  72. if (rank < this._currentRank) {
  73. this._currentRank = rank;
  74. }
  75. if (rank > this._maxRank) {
  76. this._maxRank = rank;
  77. }
  78. };
  79. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  80. /**
  81. * Checks to see if more fallbacks are still availible.
  82. */
  83. get: function () {
  84. return this._currentRank <= this._maxRank;
  85. },
  86. enumerable: true,
  87. configurable: true
  88. });
  89. /**
  90. * Removes the defines that shoould be removed when falling back.
  91. * @param currentDefines defines the current define statements for the shader.
  92. * @param effect defines the current effect we try to compile
  93. * @returns The resulting defines with defines of the current rank removed.
  94. */
  95. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  96. // First we try to switch to CPU skinning
  97. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  98. this._mesh.computeBonesUsingShaders = false;
  99. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  100. effect._bonesComputationForcedToCPU = true;
  101. var scene = this._mesh.getScene();
  102. for (var index = 0; index < scene.meshes.length; index++) {
  103. var otherMesh = scene.meshes[index];
  104. if (!otherMesh.material) {
  105. continue;
  106. }
  107. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  108. continue;
  109. }
  110. if (otherMesh.material.getEffect() === effect) {
  111. otherMesh.computeBonesUsingShaders = false;
  112. }
  113. else if (otherMesh.subMeshes) {
  114. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  115. var subMesh = _a[_i];
  116. var subMeshEffect = subMesh.effect;
  117. if (subMeshEffect === effect) {
  118. otherMesh.computeBonesUsingShaders = false;
  119. break;
  120. }
  121. }
  122. }
  123. }
  124. }
  125. else {
  126. var currentFallbacks = this._defines[this._currentRank];
  127. if (currentFallbacks) {
  128. for (var index = 0; index < currentFallbacks.length; index++) {
  129. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  130. }
  131. }
  132. this._currentRank++;
  133. }
  134. return currentDefines;
  135. };
  136. return EffectFallbacks;
  137. }());
  138. BABYLON.EffectFallbacks = EffectFallbacks;
  139. /**
  140. * Options to be used when creating an effect.
  141. */
  142. var EffectCreationOptions = /** @class */ (function () {
  143. function EffectCreationOptions() {
  144. }
  145. return EffectCreationOptions;
  146. }());
  147. BABYLON.EffectCreationOptions = EffectCreationOptions;
  148. /**
  149. * Effect containing vertex and fragment shader that can be executed on an object.
  150. */
  151. var Effect = /** @class */ (function () {
  152. /**
  153. * Instantiates an effect.
  154. * An effect can be used to create/manage/execute vertex and fragment shaders.
  155. * @param baseName Name of the effect.
  156. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  157. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  158. * @param samplers List of sampler variables that will be passed to the shader.
  159. * @param engine Engine to be used to render the effect
  160. * @param defines Define statements to be added to the shader.
  161. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  162. * @param onCompiled Callback that will be called when the shader is compiled.
  163. * @param onError Callback that will be called if an error occurs during shader compilation.
  164. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  165. */
  166. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  167. if (samplers === void 0) { samplers = null; }
  168. if (defines === void 0) { defines = null; }
  169. if (fallbacks === void 0) { fallbacks = null; }
  170. if (onCompiled === void 0) { onCompiled = null; }
  171. if (onError === void 0) { onError = null; }
  172. var _this = this;
  173. /**
  174. * Unique ID of the effect.
  175. */
  176. this.uniqueId = 0;
  177. /**
  178. * Observable that will be called when the shader is compiled.
  179. */
  180. this.onCompileObservable = new BABYLON.Observable();
  181. /**
  182. * Observable that will be called if an error occurs during shader compilation.
  183. */
  184. this.onErrorObservable = new BABYLON.Observable();
  185. /** @hidden */
  186. this._bonesComputationForcedToCPU = false;
  187. this._uniformBuffersNames = {};
  188. this._isReady = false;
  189. this._compilationError = "";
  190. this.name = baseName;
  191. if (attributesNamesOrOptions.attributes) {
  192. var options = attributesNamesOrOptions;
  193. this._engine = uniformsNamesOrEngine;
  194. this._attributesNames = options.attributes;
  195. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  196. this._samplers = options.samplers.slice();
  197. this.defines = options.defines;
  198. this.onError = options.onError;
  199. this.onCompiled = options.onCompiled;
  200. this._fallbacks = options.fallbacks;
  201. this._indexParameters = options.indexParameters;
  202. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  203. if (options.uniformBuffersNames) {
  204. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  205. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  206. }
  207. }
  208. }
  209. else {
  210. this._engine = engine;
  211. this.defines = defines;
  212. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  213. this._samplers = samplers ? samplers.slice() : [];
  214. this._attributesNames = attributesNamesOrOptions;
  215. this.onError = onError;
  216. this.onCompiled = onCompiled;
  217. this._indexParameters = indexParameters;
  218. this._fallbacks = fallbacks;
  219. }
  220. this.uniqueId = Effect._uniqueIdSeed++;
  221. var vertexSource;
  222. var fragmentSource;
  223. if (baseName.vertexElement) {
  224. vertexSource = document.getElementById(baseName.vertexElement);
  225. if (!vertexSource) {
  226. vertexSource = baseName.vertexElement;
  227. }
  228. }
  229. else {
  230. vertexSource = baseName.vertex || baseName;
  231. }
  232. if (baseName.fragmentElement) {
  233. fragmentSource = document.getElementById(baseName.fragmentElement);
  234. if (!fragmentSource) {
  235. fragmentSource = baseName.fragmentElement;
  236. }
  237. }
  238. else {
  239. fragmentSource = baseName.fragment || baseName;
  240. }
  241. this._loadVertexShader(vertexSource, function (vertexCode) {
  242. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  243. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  244. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  245. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  246. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  247. if (baseName) {
  248. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  249. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  250. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  251. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  252. }
  253. else {
  254. _this._vertexSourceCode = migratedVertexCode;
  255. _this._fragmentSourceCode = migratedFragmentCode;
  256. }
  257. _this._prepareEffect();
  258. });
  259. });
  260. });
  261. });
  262. });
  263. });
  264. }
  265. Object.defineProperty(Effect.prototype, "onBindObservable", {
  266. /**
  267. * Observable that will be called when effect is bound.
  268. */
  269. get: function () {
  270. if (!this._onBindObservable) {
  271. this._onBindObservable = new BABYLON.Observable();
  272. }
  273. return this._onBindObservable;
  274. },
  275. enumerable: true,
  276. configurable: true
  277. });
  278. Object.defineProperty(Effect.prototype, "key", {
  279. /**
  280. * Unique key for this effect
  281. */
  282. get: function () {
  283. return this._key;
  284. },
  285. enumerable: true,
  286. configurable: true
  287. });
  288. /**
  289. * If the effect has been compiled and prepared.
  290. * @returns if the effect is compiled and prepared.
  291. */
  292. Effect.prototype.isReady = function () {
  293. return this._isReady;
  294. };
  295. /**
  296. * The engine the effect was initialized with.
  297. * @returns the engine.
  298. */
  299. Effect.prototype.getEngine = function () {
  300. return this._engine;
  301. };
  302. /**
  303. * The compiled webGL program for the effect
  304. * @returns the webGL program.
  305. */
  306. Effect.prototype.getProgram = function () {
  307. return this._program;
  308. };
  309. /**
  310. * The set of names of attribute variables for the shader.
  311. * @returns An array of attribute names.
  312. */
  313. Effect.prototype.getAttributesNames = function () {
  314. return this._attributesNames;
  315. };
  316. /**
  317. * Returns the attribute at the given index.
  318. * @param index The index of the attribute.
  319. * @returns The location of the attribute.
  320. */
  321. Effect.prototype.getAttributeLocation = function (index) {
  322. return this._attributes[index];
  323. };
  324. /**
  325. * Returns the attribute based on the name of the variable.
  326. * @param name of the attribute to look up.
  327. * @returns the attribute location.
  328. */
  329. Effect.prototype.getAttributeLocationByName = function (name) {
  330. var index = this._attributesNames.indexOf(name);
  331. return this._attributes[index];
  332. };
  333. /**
  334. * The number of attributes.
  335. * @returns the numnber of attributes.
  336. */
  337. Effect.prototype.getAttributesCount = function () {
  338. return this._attributes.length;
  339. };
  340. /**
  341. * Gets the index of a uniform variable.
  342. * @param uniformName of the uniform to look up.
  343. * @returns the index.
  344. */
  345. Effect.prototype.getUniformIndex = function (uniformName) {
  346. return this._uniformsNames.indexOf(uniformName);
  347. };
  348. /**
  349. * Returns the attribute based on the name of the variable.
  350. * @param uniformName of the uniform to look up.
  351. * @returns the location of the uniform.
  352. */
  353. Effect.prototype.getUniform = function (uniformName) {
  354. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  355. };
  356. /**
  357. * Returns an array of sampler variable names
  358. * @returns The array of sampler variable neames.
  359. */
  360. Effect.prototype.getSamplers = function () {
  361. return this._samplers;
  362. };
  363. /**
  364. * The error from the last compilation.
  365. * @returns the error string.
  366. */
  367. Effect.prototype.getCompilationError = function () {
  368. return this._compilationError;
  369. };
  370. /**
  371. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  372. * @param func The callback to be used.
  373. */
  374. Effect.prototype.executeWhenCompiled = function (func) {
  375. if (this.isReady()) {
  376. func(this);
  377. return;
  378. }
  379. this.onCompileObservable.add(function (effect) {
  380. func(effect);
  381. });
  382. };
  383. /** @hidden */
  384. Effect.prototype._loadVertexShader = function (vertex, callback) {
  385. if (BABYLON.Tools.IsWindowObjectExist()) {
  386. // DOM element ?
  387. if (vertex instanceof HTMLElement) {
  388. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  389. callback(vertexCode);
  390. return;
  391. }
  392. }
  393. // Base64 encoded ?
  394. if (vertex.substr(0, 7) === "base64:") {
  395. var vertexBinary = window.atob(vertex.substr(7));
  396. callback(vertexBinary);
  397. return;
  398. }
  399. // Is in local store ?
  400. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  401. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  402. return;
  403. }
  404. var vertexShaderUrl;
  405. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  406. vertexShaderUrl = vertex;
  407. }
  408. else {
  409. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  410. }
  411. // Vertex shader
  412. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  413. };
  414. /** @hidden */
  415. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  416. if (BABYLON.Tools.IsWindowObjectExist()) {
  417. // DOM element ?
  418. if (fragment instanceof HTMLElement) {
  419. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  420. callback(fragmentCode);
  421. return;
  422. }
  423. }
  424. // Base64 encoded ?
  425. if (fragment.substr(0, 7) === "base64:") {
  426. var fragmentBinary = window.atob(fragment.substr(7));
  427. callback(fragmentBinary);
  428. return;
  429. }
  430. // Is in local store ?
  431. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  432. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  433. return;
  434. }
  435. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  436. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  437. return;
  438. }
  439. var fragmentShaderUrl;
  440. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  441. fragmentShaderUrl = fragment;
  442. }
  443. else {
  444. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  445. }
  446. // Fragment shader
  447. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  448. };
  449. /** @hidden */
  450. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  451. // Rebuild shaders source code
  452. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  453. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  454. vertexCode = prefix + vertexCode;
  455. fragmentCode = prefix + fragmentCode;
  456. // Number lines of shaders source code
  457. var i = 2;
  458. var regex = /\n/gm;
  459. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  460. i = 2;
  461. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  462. // Dump shaders name and formatted source code
  463. if (this.name.vertexElement) {
  464. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  465. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  466. }
  467. else if (this.name.vertex) {
  468. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  469. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  470. }
  471. else {
  472. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  473. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  474. }
  475. };
  476. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  477. var preparedSourceCode = this._processPrecision(sourceCode);
  478. if (this._engine.webGLVersion == 1) {
  479. callback(preparedSourceCode);
  480. return;
  481. }
  482. // Already converted
  483. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  484. callback(preparedSourceCode.replace("#version 300 es", ""));
  485. return;
  486. }
  487. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  488. // Remove extensions
  489. // #extension GL_OES_standard_derivatives : enable
  490. // #extension GL_EXT_shader_texture_lod : enable
  491. // #extension GL_EXT_frag_depth : enable
  492. // #extension GL_EXT_draw_buffers : require
  493. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  494. var result = preparedSourceCode.replace(regex, "");
  495. // Migrate to GLSL v300
  496. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  497. result = result.replace(/attribute[ \t]/g, "in ");
  498. result = result.replace(/[ \t]attribute/g, " in");
  499. if (isFragment) {
  500. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  501. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  502. result = result.replace(/texture2D\s*\(/g, "texture(");
  503. result = result.replace(/textureCube\s*\(/g, "texture(");
  504. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  505. result = result.replace(/gl_FragColor/g, "glFragColor");
  506. result = result.replace(/gl_FragData/g, "glFragData");
  507. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  508. }
  509. callback(result);
  510. };
  511. Effect.prototype._processIncludes = function (sourceCode, callback) {
  512. var _this = this;
  513. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  514. var match = regex.exec(sourceCode);
  515. var returnValue = new String(sourceCode);
  516. while (match != null) {
  517. var includeFile = match[1];
  518. // Uniform declaration
  519. if (includeFile.indexOf("__decl__") !== -1) {
  520. includeFile = includeFile.replace(/__decl__/, "");
  521. if (this._engine.supportsUniformBuffers) {
  522. includeFile = includeFile.replace(/Vertex/, "Ubo");
  523. includeFile = includeFile.replace(/Fragment/, "Ubo");
  524. }
  525. includeFile = includeFile + "Declaration";
  526. }
  527. if (Effect.IncludesShadersStore[includeFile]) {
  528. // Substitution
  529. var includeContent = Effect.IncludesShadersStore[includeFile];
  530. if (match[2]) {
  531. var splits = match[3].split(",");
  532. for (var index = 0; index < splits.length; index += 2) {
  533. var source = new RegExp(splits[index], "g");
  534. var dest = splits[index + 1];
  535. includeContent = includeContent.replace(source, dest);
  536. }
  537. }
  538. if (match[4]) {
  539. var indexString = match[5];
  540. if (indexString.indexOf("..") !== -1) {
  541. var indexSplits = indexString.split("..");
  542. var minIndex = parseInt(indexSplits[0]);
  543. var maxIndex = parseInt(indexSplits[1]);
  544. var sourceIncludeContent = includeContent.slice(0);
  545. includeContent = "";
  546. if (isNaN(maxIndex)) {
  547. maxIndex = this._indexParameters[indexSplits[1]];
  548. }
  549. for (var i = minIndex; i < maxIndex; i++) {
  550. if (!this._engine.supportsUniformBuffers) {
  551. // Ubo replacement
  552. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  553. return p1 + "{X}";
  554. });
  555. }
  556. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  557. }
  558. }
  559. else {
  560. if (!this._engine.supportsUniformBuffers) {
  561. // Ubo replacement
  562. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  563. return p1 + "{X}";
  564. });
  565. }
  566. includeContent = includeContent.replace(/\{X\}/g, indexString);
  567. }
  568. }
  569. // Replace
  570. returnValue = returnValue.replace(match[0], includeContent);
  571. }
  572. else {
  573. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  574. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  575. Effect.IncludesShadersStore[includeFile] = fileContent;
  576. _this._processIncludes(returnValue, callback);
  577. });
  578. return;
  579. }
  580. match = regex.exec(sourceCode);
  581. }
  582. callback(returnValue);
  583. };
  584. Effect.prototype._processPrecision = function (source) {
  585. if (source.indexOf("precision highp float") === -1) {
  586. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  587. source = "precision mediump float;\n" + source;
  588. }
  589. else {
  590. source = "precision highp float;\n" + source;
  591. }
  592. }
  593. else {
  594. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  595. source = source.replace("precision highp float", "precision mediump float");
  596. }
  597. }
  598. return source;
  599. };
  600. /**
  601. * Recompiles the webGL program
  602. * @param vertexSourceCode The source code for the vertex shader.
  603. * @param fragmentSourceCode The source code for the fragment shader.
  604. * @param onCompiled Callback called when completed.
  605. * @param onError Callback called on error.
  606. * @hidden
  607. */
  608. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  609. var _this = this;
  610. this._isReady = false;
  611. this._vertexSourceCodeOverride = vertexSourceCode;
  612. this._fragmentSourceCodeOverride = fragmentSourceCode;
  613. this.onError = function (effect, error) {
  614. if (onError) {
  615. onError(error);
  616. }
  617. };
  618. this.onCompiled = function () {
  619. var scenes = _this.getEngine().scenes;
  620. for (var i = 0; i < scenes.length; i++) {
  621. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  622. }
  623. if (onCompiled) {
  624. onCompiled(_this._program);
  625. }
  626. };
  627. this._fallbacks = null;
  628. this._prepareEffect();
  629. };
  630. /**
  631. * Gets the uniform locations of the the specified variable names
  632. * @param names THe names of the variables to lookup.
  633. * @returns Array of locations in the same order as variable names.
  634. */
  635. Effect.prototype.getSpecificUniformLocations = function (names) {
  636. var engine = this._engine;
  637. return engine.getUniforms(this._program, names);
  638. };
  639. /**
  640. * Prepares the effect
  641. * @hidden
  642. */
  643. Effect.prototype._prepareEffect = function () {
  644. var attributesNames = this._attributesNames;
  645. var defines = this.defines;
  646. var fallbacks = this._fallbacks;
  647. this._valueCache = {};
  648. var previousProgram = this._program;
  649. try {
  650. var engine = this._engine;
  651. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  652. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  653. }
  654. else {
  655. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  656. }
  657. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  658. if (engine.supportsUniformBuffers) {
  659. for (var name in this._uniformBuffersNames) {
  660. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  661. }
  662. }
  663. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  664. this._attributes = engine.getAttributes(this._program, attributesNames);
  665. var index;
  666. for (index = 0; index < this._samplers.length; index++) {
  667. var sampler = this.getUniform(this._samplers[index]);
  668. if (sampler == null) {
  669. this._samplers.splice(index, 1);
  670. index--;
  671. }
  672. }
  673. engine.bindSamplers(this);
  674. this._compilationError = "";
  675. this._isReady = true;
  676. if (this.onCompiled) {
  677. this.onCompiled(this);
  678. }
  679. this.onCompileObservable.notifyObservers(this);
  680. this.onCompileObservable.clear();
  681. // Unbind mesh reference in fallbacks
  682. if (this._fallbacks) {
  683. this._fallbacks.unBindMesh();
  684. }
  685. if (previousProgram) {
  686. this.getEngine()._deleteProgram(previousProgram);
  687. }
  688. }
  689. catch (e) {
  690. this._compilationError = e.message;
  691. // Let's go through fallbacks then
  692. BABYLON.Tools.Error("Unable to compile effect:");
  693. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  694. return " " + uniform;
  695. }));
  696. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  697. return " " + attribute;
  698. }));
  699. BABYLON.Tools.Error("Error: " + this._compilationError);
  700. if (previousProgram) {
  701. this._program = previousProgram;
  702. this._isReady = true;
  703. if (this.onError) {
  704. this.onError(this, this._compilationError);
  705. }
  706. this.onErrorObservable.notifyObservers(this);
  707. }
  708. if (fallbacks && fallbacks.isMoreFallbacks) {
  709. BABYLON.Tools.Error("Trying next fallback.");
  710. this.defines = fallbacks.reduce(this.defines, this);
  711. this._prepareEffect();
  712. }
  713. else { // Sorry we did everything we can
  714. if (this.onError) {
  715. this.onError(this, this._compilationError);
  716. }
  717. this.onErrorObservable.notifyObservers(this);
  718. this.onErrorObservable.clear();
  719. // Unbind mesh reference in fallbacks
  720. if (this._fallbacks) {
  721. this._fallbacks.unBindMesh();
  722. }
  723. }
  724. }
  725. };
  726. Object.defineProperty(Effect.prototype, "isSupported", {
  727. /**
  728. * Checks if the effect is supported. (Must be called after compilation)
  729. */
  730. get: function () {
  731. return this._compilationError === "";
  732. },
  733. enumerable: true,
  734. configurable: true
  735. });
  736. /**
  737. * Binds a texture to the engine to be used as output of the shader.
  738. * @param channel Name of the output variable.
  739. * @param texture Texture to bind.
  740. * @hidden
  741. */
  742. Effect.prototype._bindTexture = function (channel, texture) {
  743. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  744. };
  745. /**
  746. * Sets a texture on the engine to be used in the shader.
  747. * @param channel Name of the sampler variable.
  748. * @param texture Texture to set.
  749. */
  750. Effect.prototype.setTexture = function (channel, texture) {
  751. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  752. };
  753. /**
  754. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  755. * @param channel Name of the sampler variable.
  756. * @param texture Texture to set.
  757. */
  758. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  759. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  760. };
  761. /**
  762. * Sets an array of textures on the engine to be used in the shader.
  763. * @param channel Name of the variable.
  764. * @param textures Textures to set.
  765. */
  766. Effect.prototype.setTextureArray = function (channel, textures) {
  767. if (this._samplers.indexOf(channel + "Ex") === -1) {
  768. var initialPos = this._samplers.indexOf(channel);
  769. for (var index = 1; index < textures.length; index++) {
  770. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  771. }
  772. }
  773. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  774. };
  775. /**
  776. * 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)
  777. * @param channel Name of the sampler variable.
  778. * @param postProcess Post process to get the input texture from.
  779. */
  780. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  781. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  782. };
  783. /**
  784. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  785. * 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)
  786. * @param channel Name of the sampler variable.
  787. * @param postProcess Post process to get the output texture from.
  788. */
  789. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  790. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  791. };
  792. /** @hidden */
  793. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  794. var cache = this._valueCache[uniformName];
  795. var flag = matrix.updateFlag;
  796. if (cache !== undefined && cache === flag) {
  797. return false;
  798. }
  799. this._valueCache[uniformName] = flag;
  800. return true;
  801. };
  802. /** @hidden */
  803. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  804. var cache = this._valueCache[uniformName];
  805. if (!cache) {
  806. cache = [x, y];
  807. this._valueCache[uniformName] = cache;
  808. return true;
  809. }
  810. var changed = false;
  811. if (cache[0] !== x) {
  812. cache[0] = x;
  813. changed = true;
  814. }
  815. if (cache[1] !== y) {
  816. cache[1] = y;
  817. changed = true;
  818. }
  819. return changed;
  820. };
  821. /** @hidden */
  822. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  823. var cache = this._valueCache[uniformName];
  824. if (!cache) {
  825. cache = [x, y, z];
  826. this._valueCache[uniformName] = cache;
  827. return true;
  828. }
  829. var changed = false;
  830. if (cache[0] !== x) {
  831. cache[0] = x;
  832. changed = true;
  833. }
  834. if (cache[1] !== y) {
  835. cache[1] = y;
  836. changed = true;
  837. }
  838. if (cache[2] !== z) {
  839. cache[2] = z;
  840. changed = true;
  841. }
  842. return changed;
  843. };
  844. /** @hidden */
  845. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  846. var cache = this._valueCache[uniformName];
  847. if (!cache) {
  848. cache = [x, y, z, w];
  849. this._valueCache[uniformName] = cache;
  850. return true;
  851. }
  852. var changed = false;
  853. if (cache[0] !== x) {
  854. cache[0] = x;
  855. changed = true;
  856. }
  857. if (cache[1] !== y) {
  858. cache[1] = y;
  859. changed = true;
  860. }
  861. if (cache[2] !== z) {
  862. cache[2] = z;
  863. changed = true;
  864. }
  865. if (cache[3] !== w) {
  866. cache[3] = w;
  867. changed = true;
  868. }
  869. return changed;
  870. };
  871. /**
  872. * Binds a buffer to a uniform.
  873. * @param buffer Buffer to bind.
  874. * @param name Name of the uniform variable to bind to.
  875. */
  876. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  877. var bufferName = this._uniformBuffersNames[name];
  878. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  879. return;
  880. }
  881. Effect._baseCache[bufferName] = buffer;
  882. this._engine.bindUniformBufferBase(buffer, bufferName);
  883. };
  884. /**
  885. * Binds block to a uniform.
  886. * @param blockName Name of the block to bind.
  887. * @param index Index to bind.
  888. */
  889. Effect.prototype.bindUniformBlock = function (blockName, index) {
  890. this._engine.bindUniformBlock(this._program, blockName, index);
  891. };
  892. /**
  893. * Sets an interger value on a uniform variable.
  894. * @param uniformName Name of the variable.
  895. * @param value Value to be set.
  896. * @returns this effect.
  897. */
  898. Effect.prototype.setInt = function (uniformName, value) {
  899. var cache = this._valueCache[uniformName];
  900. if (cache !== undefined && cache === value) {
  901. return this;
  902. }
  903. this._valueCache[uniformName] = value;
  904. this._engine.setInt(this.getUniform(uniformName), value);
  905. return this;
  906. };
  907. /**
  908. * Sets an int array on a uniform variable.
  909. * @param uniformName Name of the variable.
  910. * @param array array to be set.
  911. * @returns this effect.
  912. */
  913. Effect.prototype.setIntArray = function (uniformName, array) {
  914. this._valueCache[uniformName] = null;
  915. this._engine.setIntArray(this.getUniform(uniformName), array);
  916. return this;
  917. };
  918. /**
  919. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  920. * @param uniformName Name of the variable.
  921. * @param array array to be set.
  922. * @returns this effect.
  923. */
  924. Effect.prototype.setIntArray2 = function (uniformName, array) {
  925. this._valueCache[uniformName] = null;
  926. this._engine.setIntArray2(this.getUniform(uniformName), array);
  927. return this;
  928. };
  929. /**
  930. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  931. * @param uniformName Name of the variable.
  932. * @param array array to be set.
  933. * @returns this effect.
  934. */
  935. Effect.prototype.setIntArray3 = function (uniformName, array) {
  936. this._valueCache[uniformName] = null;
  937. this._engine.setIntArray3(this.getUniform(uniformName), array);
  938. return this;
  939. };
  940. /**
  941. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  942. * @param uniformName Name of the variable.
  943. * @param array array to be set.
  944. * @returns this effect.
  945. */
  946. Effect.prototype.setIntArray4 = function (uniformName, array) {
  947. this._valueCache[uniformName] = null;
  948. this._engine.setIntArray4(this.getUniform(uniformName), array);
  949. return this;
  950. };
  951. /**
  952. * Sets an float array on a uniform variable.
  953. * @param uniformName Name of the variable.
  954. * @param array array to be set.
  955. * @returns this effect.
  956. */
  957. Effect.prototype.setFloatArray = function (uniformName, array) {
  958. this._valueCache[uniformName] = null;
  959. this._engine.setFloatArray(this.getUniform(uniformName), array);
  960. return this;
  961. };
  962. /**
  963. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  964. * @param uniformName Name of the variable.
  965. * @param array array to be set.
  966. * @returns this effect.
  967. */
  968. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  969. this._valueCache[uniformName] = null;
  970. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  971. return this;
  972. };
  973. /**
  974. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  975. * @param uniformName Name of the variable.
  976. * @param array array to be set.
  977. * @returns this effect.
  978. */
  979. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  980. this._valueCache[uniformName] = null;
  981. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  982. return this;
  983. };
  984. /**
  985. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  986. * @param uniformName Name of the variable.
  987. * @param array array to be set.
  988. * @returns this effect.
  989. */
  990. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  991. this._valueCache[uniformName] = null;
  992. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  993. return this;
  994. };
  995. /**
  996. * Sets an array on a uniform variable.
  997. * @param uniformName Name of the variable.
  998. * @param array array to be set.
  999. * @returns this effect.
  1000. */
  1001. Effect.prototype.setArray = function (uniformName, array) {
  1002. this._valueCache[uniformName] = null;
  1003. this._engine.setArray(this.getUniform(uniformName), array);
  1004. return this;
  1005. };
  1006. /**
  1007. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1008. * @param uniformName Name of the variable.
  1009. * @param array array to be set.
  1010. * @returns this effect.
  1011. */
  1012. Effect.prototype.setArray2 = function (uniformName, array) {
  1013. this._valueCache[uniformName] = null;
  1014. this._engine.setArray2(this.getUniform(uniformName), array);
  1015. return this;
  1016. };
  1017. /**
  1018. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1019. * @param uniformName Name of the variable.
  1020. * @param array array to be set.
  1021. * @returns this effect.
  1022. */
  1023. Effect.prototype.setArray3 = function (uniformName, array) {
  1024. this._valueCache[uniformName] = null;
  1025. this._engine.setArray3(this.getUniform(uniformName), array);
  1026. return this;
  1027. };
  1028. /**
  1029. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1030. * @param uniformName Name of the variable.
  1031. * @param array array to be set.
  1032. * @returns this effect.
  1033. */
  1034. Effect.prototype.setArray4 = function (uniformName, array) {
  1035. this._valueCache[uniformName] = null;
  1036. this._engine.setArray4(this.getUniform(uniformName), array);
  1037. return this;
  1038. };
  1039. /**
  1040. * Sets matrices on a uniform variable.
  1041. * @param uniformName Name of the variable.
  1042. * @param matrices matrices to be set.
  1043. * @returns this effect.
  1044. */
  1045. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1046. if (!matrices) {
  1047. return this;
  1048. }
  1049. this._valueCache[uniformName] = null;
  1050. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1051. return this;
  1052. };
  1053. /**
  1054. * Sets matrix on a uniform variable.
  1055. * @param uniformName Name of the variable.
  1056. * @param matrix matrix to be set.
  1057. * @returns this effect.
  1058. */
  1059. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1060. if (this._cacheMatrix(uniformName, matrix)) {
  1061. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1062. }
  1063. return this;
  1064. };
  1065. /**
  1066. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1067. * @param uniformName Name of the variable.
  1068. * @param matrix matrix to be set.
  1069. * @returns this effect.
  1070. */
  1071. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1072. this._valueCache[uniformName] = null;
  1073. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1074. return this;
  1075. };
  1076. /**
  1077. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1078. * @param uniformName Name of the variable.
  1079. * @param matrix matrix to be set.
  1080. * @returns this effect.
  1081. */
  1082. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1083. this._valueCache[uniformName] = null;
  1084. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1085. return this;
  1086. };
  1087. /**
  1088. * Sets a float on a uniform variable.
  1089. * @param uniformName Name of the variable.
  1090. * @param value value to be set.
  1091. * @returns this effect.
  1092. */
  1093. Effect.prototype.setFloat = function (uniformName, value) {
  1094. var cache = this._valueCache[uniformName];
  1095. if (cache !== undefined && cache === value) {
  1096. return this;
  1097. }
  1098. this._valueCache[uniformName] = value;
  1099. this._engine.setFloat(this.getUniform(uniformName), value);
  1100. return this;
  1101. };
  1102. /**
  1103. * Sets a boolean on a uniform variable.
  1104. * @param uniformName Name of the variable.
  1105. * @param bool value to be set.
  1106. * @returns this effect.
  1107. */
  1108. Effect.prototype.setBool = function (uniformName, bool) {
  1109. var cache = this._valueCache[uniformName];
  1110. if (cache !== undefined && cache === bool) {
  1111. return this;
  1112. }
  1113. this._valueCache[uniformName] = bool;
  1114. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1115. return this;
  1116. };
  1117. /**
  1118. * Sets a Vector2 on a uniform variable.
  1119. * @param uniformName Name of the variable.
  1120. * @param vector2 vector2 to be set.
  1121. * @returns this effect.
  1122. */
  1123. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1124. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1125. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1126. }
  1127. return this;
  1128. };
  1129. /**
  1130. * Sets a float2 on a uniform variable.
  1131. * @param uniformName Name of the variable.
  1132. * @param x First float in float2.
  1133. * @param y Second float in float2.
  1134. * @returns this effect.
  1135. */
  1136. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1137. if (this._cacheFloat2(uniformName, x, y)) {
  1138. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1139. }
  1140. return this;
  1141. };
  1142. /**
  1143. * Sets a Vector3 on a uniform variable.
  1144. * @param uniformName Name of the variable.
  1145. * @param vector3 Value to be set.
  1146. * @returns this effect.
  1147. */
  1148. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1149. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1150. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1151. }
  1152. return this;
  1153. };
  1154. /**
  1155. * Sets a float3 on a uniform variable.
  1156. * @param uniformName Name of the variable.
  1157. * @param x First float in float3.
  1158. * @param y Second float in float3.
  1159. * @param z Third float in float3.
  1160. * @returns this effect.
  1161. */
  1162. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1163. if (this._cacheFloat3(uniformName, x, y, z)) {
  1164. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1165. }
  1166. return this;
  1167. };
  1168. /**
  1169. * Sets a Vector4 on a uniform variable.
  1170. * @param uniformName Name of the variable.
  1171. * @param vector4 Value to be set.
  1172. * @returns this effect.
  1173. */
  1174. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1175. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1176. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1177. }
  1178. return this;
  1179. };
  1180. /**
  1181. * Sets a float4 on a uniform variable.
  1182. * @param uniformName Name of the variable.
  1183. * @param x First float in float4.
  1184. * @param y Second float in float4.
  1185. * @param z Third float in float4.
  1186. * @param w Fourth float in float4.
  1187. * @returns this effect.
  1188. */
  1189. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1190. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1191. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1192. }
  1193. return this;
  1194. };
  1195. /**
  1196. * Sets a Color3 on a uniform variable.
  1197. * @param uniformName Name of the variable.
  1198. * @param color3 Value to be set.
  1199. * @returns this effect.
  1200. */
  1201. Effect.prototype.setColor3 = function (uniformName, color3) {
  1202. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1203. this._engine.setColor3(this.getUniform(uniformName), color3);
  1204. }
  1205. return this;
  1206. };
  1207. /**
  1208. * Sets a Color4 on a uniform variable.
  1209. * @param uniformName Name of the variable.
  1210. * @param color3 Value to be set.
  1211. * @param alpha Alpha value to be set.
  1212. * @returns this effect.
  1213. */
  1214. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1215. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1216. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1217. }
  1218. return this;
  1219. };
  1220. /**
  1221. * Sets a Color4 on a uniform variable
  1222. * @param uniformName defines the name of the variable
  1223. * @param color4 defines the value to be set
  1224. * @returns this effect.
  1225. */
  1226. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1227. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1228. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1229. }
  1230. return this;
  1231. };
  1232. /**
  1233. * This function will add a new shader to the shader store
  1234. * @param name the name of the shader
  1235. * @param pixelShader optional pixel shader content
  1236. * @param vertexShader optional vertex shader content
  1237. */
  1238. Effect.RegisterShader = function (name, pixelShader, vertexShader) {
  1239. if (pixelShader) {
  1240. Effect.ShadersStore[name + "PixelShader"] = pixelShader;
  1241. }
  1242. if (vertexShader) {
  1243. Effect.ShadersStore[name + "VertexShader"] = vertexShader;
  1244. }
  1245. };
  1246. /**
  1247. * Resets the cache of effects.
  1248. */
  1249. Effect.ResetCache = function () {
  1250. Effect._baseCache = {};
  1251. };
  1252. Effect._uniqueIdSeed = 0;
  1253. Effect._baseCache = {};
  1254. /**
  1255. * Store of each shader (The can be looked up using effect.key)
  1256. */
  1257. Effect.ShadersStore = {};
  1258. /**
  1259. * Store of each included file for a shader (The can be looked up using effect.key)
  1260. */
  1261. Effect.IncludesShadersStore = {};
  1262. return Effect;
  1263. }());
  1264. BABYLON.Effect = Effect;
  1265. })(BABYLON || (BABYLON = {}));
  1266. //# sourceMappingURL=babylon.effect.js.map
  1267. //# sourceMappingURL=babylon.types.js.map
  1268. var BABYLON;
  1269. (function (BABYLON) {
  1270. /**
  1271. * Gather the list of keyboard event types as constants.
  1272. */
  1273. var KeyboardEventTypes = /** @class */ (function () {
  1274. function KeyboardEventTypes() {
  1275. }
  1276. /**
  1277. * The keydown event is fired when a key becomes active (pressed).
  1278. */
  1279. KeyboardEventTypes.KEYDOWN = 0x01;
  1280. /**
  1281. * The keyup event is fired when a key has been released.
  1282. */
  1283. KeyboardEventTypes.KEYUP = 0x02;
  1284. return KeyboardEventTypes;
  1285. }());
  1286. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1287. /**
  1288. * This class is used to store keyboard related info for the onKeyboardObservable event.
  1289. */
  1290. var KeyboardInfo = /** @class */ (function () {
  1291. /**
  1292. * Instantiates a new keyboard info.
  1293. * This class is used to store keyboard related info for the onKeyboardObservable event.
  1294. * @param type Defines the type of event (BABYLON.KeyboardEventTypes)
  1295. * @param event Defines the related dom event
  1296. */
  1297. function KeyboardInfo(
  1298. /**
  1299. * Defines the type of event (BABYLON.KeyboardEventTypes)
  1300. */
  1301. type,
  1302. /**
  1303. * Defines the related dom event
  1304. */
  1305. event) {
  1306. this.type = type;
  1307. this.event = event;
  1308. }
  1309. return KeyboardInfo;
  1310. }());
  1311. BABYLON.KeyboardInfo = KeyboardInfo;
  1312. /**
  1313. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1314. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1315. */
  1316. var KeyboardInfoPre = /** @class */ (function (_super) {
  1317. __extends(KeyboardInfoPre, _super);
  1318. /**
  1319. * Instantiates a new keyboard pre info.
  1320. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1321. * @param type Defines the type of event (BABYLON.KeyboardEventTypes)
  1322. * @param event Defines the related dom event
  1323. */
  1324. function KeyboardInfoPre(
  1325. /**
  1326. * Defines the type of event (BABYLON.KeyboardEventTypes)
  1327. */
  1328. type,
  1329. /**
  1330. * Defines the related dom event
  1331. */
  1332. event) {
  1333. var _this = _super.call(this, type, event) || this;
  1334. _this.type = type;
  1335. _this.event = event;
  1336. _this.skipOnPointerObservable = false;
  1337. return _this;
  1338. }
  1339. return KeyboardInfoPre;
  1340. }(KeyboardInfo));
  1341. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1342. })(BABYLON || (BABYLON = {}));
  1343. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1344. var BABYLON;
  1345. (function (BABYLON) {
  1346. /**
  1347. * Gather the list of pointer event types as constants.
  1348. */
  1349. var PointerEventTypes = /** @class */ (function () {
  1350. function PointerEventTypes() {
  1351. }
  1352. /**
  1353. * 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.
  1354. */
  1355. PointerEventTypes.POINTERDOWN = 0x01;
  1356. /**
  1357. * The pointerup event is fired when a pointer is no longer active.
  1358. */
  1359. PointerEventTypes.POINTERUP = 0x02;
  1360. /**
  1361. * The pointermove event is fired when a pointer changes coordinates.
  1362. */
  1363. PointerEventTypes.POINTERMOVE = 0x04;
  1364. /**
  1365. * The pointerwheel event is fired when a mouse wheel has been rotated.
  1366. */
  1367. PointerEventTypes.POINTERWHEEL = 0x08;
  1368. /**
  1369. * The pointerpick event is fired when a mesh or sprite has been picked by the pointer.
  1370. */
  1371. PointerEventTypes.POINTERPICK = 0x10;
  1372. /**
  1373. * The pointertap event is fired when a the object has been touched and released without drag.
  1374. */
  1375. PointerEventTypes.POINTERTAP = 0x20;
  1376. /**
  1377. * The pointerdoubletap event is fired when a the object has been touched and released twice without drag.
  1378. */
  1379. PointerEventTypes.POINTERDOUBLETAP = 0x40;
  1380. return PointerEventTypes;
  1381. }());
  1382. BABYLON.PointerEventTypes = PointerEventTypes;
  1383. /**
  1384. * Base class of pointer info types.
  1385. */
  1386. var PointerInfoBase = /** @class */ (function () {
  1387. /**
  1388. * Instantiates the base class of pointers info.
  1389. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1390. * @param event Defines the related dom event
  1391. */
  1392. function PointerInfoBase(
  1393. /**
  1394. * Defines the type of event (BABYLON.PointerEventTypes)
  1395. */
  1396. type,
  1397. /**
  1398. * Defines the related dom event
  1399. */
  1400. event) {
  1401. this.type = type;
  1402. this.event = event;
  1403. }
  1404. return PointerInfoBase;
  1405. }());
  1406. BABYLON.PointerInfoBase = PointerInfoBase;
  1407. /**
  1408. * This class is used to store pointer related info for the onPrePointerObservable event.
  1409. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1410. */
  1411. var PointerInfoPre = /** @class */ (function (_super) {
  1412. __extends(PointerInfoPre, _super);
  1413. /**
  1414. * Instantiates a PointerInfoPre to store pointer related info to the onPrePointerObservable event.
  1415. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1416. * @param event Defines the related dom event
  1417. * @param localX Defines the local x coordinates of the pointer when the event occured
  1418. * @param localY Defines the local y coordinates of the pointer when the event occured
  1419. */
  1420. function PointerInfoPre(type, event, localX, localY) {
  1421. var _this = _super.call(this, type, event) || this;
  1422. /**
  1423. * Ray from a pointer if availible (eg. 6dof controller)
  1424. */
  1425. _this.ray = null;
  1426. _this.skipOnPointerObservable = false;
  1427. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1428. return _this;
  1429. }
  1430. return PointerInfoPre;
  1431. }(PointerInfoBase));
  1432. BABYLON.PointerInfoPre = PointerInfoPre;
  1433. /**
  1434. * This type contains all the data related to a pointer event in Babylon.js.
  1435. * 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.
  1436. */
  1437. var PointerInfo = /** @class */ (function (_super) {
  1438. __extends(PointerInfo, _super);
  1439. /**
  1440. * Instantiates a PointerInfo to store pointer related info to the onPointerObservable event.
  1441. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1442. * @param event Defines the related dom event
  1443. * @param pickInfo Defines the picking info associated to the info (if any)\
  1444. */
  1445. function PointerInfo(type, event,
  1446. /**
  1447. * Defines the picking info associated to the info (if any)\
  1448. */
  1449. pickInfo) {
  1450. var _this = _super.call(this, type, event) || this;
  1451. _this.pickInfo = pickInfo;
  1452. return _this;
  1453. }
  1454. return PointerInfo;
  1455. }(PointerInfoBase));
  1456. BABYLON.PointerInfo = PointerInfo;
  1457. })(BABYLON || (BABYLON = {}));
  1458. //# sourceMappingURL=babylon.pointerEvents.js.map
  1459. var BABYLON;
  1460. (function (BABYLON) {
  1461. /**
  1462. * Constant used to convert a value to gamma space
  1463. * @ignorenaming
  1464. */
  1465. BABYLON.ToGammaSpace = 1 / 2.2;
  1466. /**
  1467. * Constant used to convert a value to linear space
  1468. * @ignorenaming
  1469. */
  1470. BABYLON.ToLinearSpace = 2.2;
  1471. /**
  1472. * Constant used to define the minimal number value in Babylon.js
  1473. * @ignorenaming
  1474. */
  1475. BABYLON.Epsilon = 0.001;
  1476. /**
  1477. * Class used to hold a RBG color
  1478. */
  1479. var Color3 = /** @class */ (function () {
  1480. /**
  1481. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1482. * @param r defines the red component (between 0 and 1, default is 0)
  1483. * @param g defines the green component (between 0 and 1, default is 0)
  1484. * @param b defines the blue component (between 0 and 1, default is 0)
  1485. */
  1486. function Color3(
  1487. /**
  1488. * Defines the red component (between 0 and 1, default is 0)
  1489. */
  1490. r,
  1491. /**
  1492. * Defines the green component (between 0 and 1, default is 0)
  1493. */
  1494. g,
  1495. /**
  1496. * Defines the blue component (between 0 and 1, default is 0)
  1497. */
  1498. b) {
  1499. if (r === void 0) { r = 0; }
  1500. if (g === void 0) { g = 0; }
  1501. if (b === void 0) { b = 0; }
  1502. this.r = r;
  1503. this.g = g;
  1504. this.b = b;
  1505. }
  1506. /**
  1507. * Creates a string with the Color3 current values
  1508. * @returns the string representation of the Color3 object
  1509. */
  1510. Color3.prototype.toString = function () {
  1511. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1512. };
  1513. /**
  1514. * Returns the string "Color3"
  1515. * @returns "Color3"
  1516. */
  1517. Color3.prototype.getClassName = function () {
  1518. return "Color3";
  1519. };
  1520. /**
  1521. * Compute the Color3 hash code
  1522. * @returns an unique number that can be used to hash Color3 objects
  1523. */
  1524. Color3.prototype.getHashCode = function () {
  1525. var hash = this.r || 0;
  1526. hash = (hash * 397) ^ (this.g || 0);
  1527. hash = (hash * 397) ^ (this.b || 0);
  1528. return hash;
  1529. };
  1530. // Operators
  1531. /**
  1532. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1533. * @param array defines the array where to store the r,g,b components
  1534. * @param index defines an optional index in the target array to define where to start storing values
  1535. * @returns the current Color3 object
  1536. */
  1537. Color3.prototype.toArray = function (array, index) {
  1538. if (index === undefined) {
  1539. index = 0;
  1540. }
  1541. array[index] = this.r;
  1542. array[index + 1] = this.g;
  1543. array[index + 2] = this.b;
  1544. return this;
  1545. };
  1546. /**
  1547. * Returns a new Color4 object from the current Color3 and the given alpha
  1548. * @param alpha defines the alpha component on the new Color4 object (default is 1)
  1549. * @returns a new Color4 object
  1550. */
  1551. Color3.prototype.toColor4 = function (alpha) {
  1552. if (alpha === void 0) { alpha = 1; }
  1553. return new Color4(this.r, this.g, this.b, alpha);
  1554. };
  1555. /**
  1556. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1557. * @returns the new array
  1558. */
  1559. Color3.prototype.asArray = function () {
  1560. var result = new Array();
  1561. this.toArray(result, 0);
  1562. return result;
  1563. };
  1564. /**
  1565. * Returns the luminance value
  1566. * @returns a float value
  1567. */
  1568. Color3.prototype.toLuminance = function () {
  1569. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1570. };
  1571. /**
  1572. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1573. * @param otherColor defines the second operand
  1574. * @returns the new Color3 object
  1575. */
  1576. Color3.prototype.multiply = function (otherColor) {
  1577. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1578. };
  1579. /**
  1580. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1581. * @param otherColor defines the second operand
  1582. * @param result defines the Color3 object where to store the result
  1583. * @returns the current Color3
  1584. */
  1585. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1586. result.r = this.r * otherColor.r;
  1587. result.g = this.g * otherColor.g;
  1588. result.b = this.b * otherColor.b;
  1589. return this;
  1590. };
  1591. /**
  1592. * Determines equality between Color3 objects
  1593. * @param otherColor defines the second operand
  1594. * @returns true if the rgb values are equal to the given ones
  1595. */
  1596. Color3.prototype.equals = function (otherColor) {
  1597. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1598. };
  1599. /**
  1600. * Determines equality between the current Color3 object and a set of r,b,g values
  1601. * @param r defines the red component to check
  1602. * @param g defines the green component to check
  1603. * @param b defines the blue component to check
  1604. * @returns true if the rgb values are equal to the given ones
  1605. */
  1606. Color3.prototype.equalsFloats = function (r, g, b) {
  1607. return this.r === r && this.g === g && this.b === b;
  1608. };
  1609. /**
  1610. * Multiplies in place each rgb value by scale
  1611. * @param scale defines the scaling factor
  1612. * @returns the updated Color3
  1613. */
  1614. Color3.prototype.scale = function (scale) {
  1615. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1616. };
  1617. /**
  1618. * Multiplies the rgb values by scale and stores the result into "result"
  1619. * @param scale defines the scaling factor
  1620. * @param result defines the Color3 object where to store the result
  1621. * @returns the unmodified current Color3
  1622. */
  1623. Color3.prototype.scaleToRef = function (scale, result) {
  1624. result.r = this.r * scale;
  1625. result.g = this.g * scale;
  1626. result.b = this.b * scale;
  1627. return this;
  1628. };
  1629. /**
  1630. * Scale the current Color3 values by a factor and add the result to a given Color3
  1631. * @param scale defines the scale factor
  1632. * @param result defines color to store the result into
  1633. * @returns the unmodified current Color3
  1634. */
  1635. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1636. result.r += this.r * scale;
  1637. result.g += this.g * scale;
  1638. result.b += this.b * scale;
  1639. return this;
  1640. };
  1641. /**
  1642. * Clamps the rgb values by the min and max values and stores the result into "result"
  1643. * @param min defines minimum clamping value (default is 0)
  1644. * @param max defines maximum clamping value (default is 1)
  1645. * @param result defines color to store the result into
  1646. * @returns the original Color3
  1647. */
  1648. Color3.prototype.clampToRef = function (min, max, result) {
  1649. if (min === void 0) { min = 0; }
  1650. if (max === void 0) { max = 1; }
  1651. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1652. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1653. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1654. return this;
  1655. };
  1656. /**
  1657. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1658. * @param otherColor defines the second operand
  1659. * @returns the new Color3
  1660. */
  1661. Color3.prototype.add = function (otherColor) {
  1662. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1663. };
  1664. /**
  1665. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1666. * @param otherColor defines the second operand
  1667. * @param result defines Color3 object to store the result into
  1668. * @returns the unmodified current Color3
  1669. */
  1670. Color3.prototype.addToRef = function (otherColor, result) {
  1671. result.r = this.r + otherColor.r;
  1672. result.g = this.g + otherColor.g;
  1673. result.b = this.b + otherColor.b;
  1674. return this;
  1675. };
  1676. /**
  1677. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1678. * @param otherColor defines the second operand
  1679. * @returns the new Color3
  1680. */
  1681. Color3.prototype.subtract = function (otherColor) {
  1682. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1683. };
  1684. /**
  1685. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1686. * @param otherColor defines the second operand
  1687. * @param result defines Color3 object to store the result into
  1688. * @returns the unmodified current Color3
  1689. */
  1690. Color3.prototype.subtractToRef = function (otherColor, result) {
  1691. result.r = this.r - otherColor.r;
  1692. result.g = this.g - otherColor.g;
  1693. result.b = this.b - otherColor.b;
  1694. return this;
  1695. };
  1696. /**
  1697. * Copy the current object
  1698. * @returns a new Color3 copied the current one
  1699. */
  1700. Color3.prototype.clone = function () {
  1701. return new Color3(this.r, this.g, this.b);
  1702. };
  1703. /**
  1704. * Copies the rgb values from the source in the current Color3
  1705. * @param source defines the source Color3 object
  1706. * @returns the updated Color3 object
  1707. */
  1708. Color3.prototype.copyFrom = function (source) {
  1709. this.r = source.r;
  1710. this.g = source.g;
  1711. this.b = source.b;
  1712. return this;
  1713. };
  1714. /**
  1715. * Updates the Color3 rgb values from the given floats
  1716. * @param r defines the red component to read from
  1717. * @param g defines the green component to read from
  1718. * @param b defines the blue component to read from
  1719. * @returns the current Color3 object
  1720. */
  1721. Color3.prototype.copyFromFloats = function (r, g, b) {
  1722. this.r = r;
  1723. this.g = g;
  1724. this.b = b;
  1725. return this;
  1726. };
  1727. /**
  1728. * Updates the Color3 rgb values from the given floats
  1729. * @param r defines the red component to read from
  1730. * @param g defines the green component to read from
  1731. * @param b defines the blue component to read from
  1732. * @returns the current Color3 object
  1733. */
  1734. Color3.prototype.set = function (r, g, b) {
  1735. return this.copyFromFloats(r, g, b);
  1736. };
  1737. /**
  1738. * Compute the Color3 hexadecimal code as a string
  1739. * @returns a string containing the hexadecimal representation of the Color3 object
  1740. */
  1741. Color3.prototype.toHexString = function () {
  1742. var intR = (this.r * 255) | 0;
  1743. var intG = (this.g * 255) | 0;
  1744. var intB = (this.b * 255) | 0;
  1745. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1746. };
  1747. /**
  1748. * Computes a new Color3 converted from the current one to linear space
  1749. * @returns a new Color3 object
  1750. */
  1751. Color3.prototype.toLinearSpace = function () {
  1752. var convertedColor = new Color3();
  1753. this.toLinearSpaceToRef(convertedColor);
  1754. return convertedColor;
  1755. };
  1756. /**
  1757. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1758. * @param convertedColor defines the Color3 object where to store the linear space version
  1759. * @returns the unmodified Color3
  1760. */
  1761. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1762. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1763. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1764. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1765. return this;
  1766. };
  1767. /**
  1768. * Computes a new Color3 converted from the current one to gamma space
  1769. * @returns a new Color3 object
  1770. */
  1771. Color3.prototype.toGammaSpace = function () {
  1772. var convertedColor = new Color3();
  1773. this.toGammaSpaceToRef(convertedColor);
  1774. return convertedColor;
  1775. };
  1776. /**
  1777. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1778. * @param convertedColor defines the Color3 object where to store the gamma space version
  1779. * @returns the unmodified Color3
  1780. */
  1781. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1782. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1783. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1784. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1785. return this;
  1786. };
  1787. // Statics
  1788. /**
  1789. * Creates a new Color3 from the string containing valid hexadecimal values
  1790. * @param hex defines a string containing valid hexadecimal values
  1791. * @returns a new Color3 object
  1792. */
  1793. Color3.FromHexString = function (hex) {
  1794. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1795. return new Color3(0, 0, 0);
  1796. }
  1797. var r = parseInt(hex.substring(1, 3), 16);
  1798. var g = parseInt(hex.substring(3, 5), 16);
  1799. var b = parseInt(hex.substring(5, 7), 16);
  1800. return Color3.FromInts(r, g, b);
  1801. };
  1802. /**
  1803. * Creates a new Vector3 from the starting index of the given array
  1804. * @param array defines the source array
  1805. * @param offset defines an offset in the source array
  1806. * @returns a new Color3 object
  1807. */
  1808. Color3.FromArray = function (array, offset) {
  1809. if (offset === void 0) { offset = 0; }
  1810. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1811. };
  1812. /**
  1813. * Creates a new Color3 from integer values (< 256)
  1814. * @param r defines the red component to read from (value between 0 and 255)
  1815. * @param g defines the green component to read from (value between 0 and 255)
  1816. * @param b defines the blue component to read from (value between 0 and 255)
  1817. * @returns a new Color3 object
  1818. */
  1819. Color3.FromInts = function (r, g, b) {
  1820. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1821. };
  1822. /**
  1823. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1824. * @param start defines the start Color3 value
  1825. * @param end defines the end Color3 value
  1826. * @param amount defines the gradient value between start and end
  1827. * @returns a new Color3 object
  1828. */
  1829. Color3.Lerp = function (start, end, amount) {
  1830. var result = new Color3(0.0, 0.0, 0.0);
  1831. Color3.LerpToRef(start, end, amount, result);
  1832. return result;
  1833. };
  1834. /**
  1835. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1836. * @param left defines the start value
  1837. * @param right defines the end value
  1838. * @param amount defines the gradient factor
  1839. * @param result defines the Color3 object where to store the result
  1840. */
  1841. Color3.LerpToRef = function (left, right, amount, result) {
  1842. result.r = left.r + ((right.r - left.r) * amount);
  1843. result.g = left.g + ((right.g - left.g) * amount);
  1844. result.b = left.b + ((right.b - left.b) * amount);
  1845. };
  1846. /**
  1847. * Returns a Color3 value containing a red color
  1848. * @returns a new Color3 object
  1849. */
  1850. Color3.Red = function () { return new Color3(1, 0, 0); };
  1851. /**
  1852. * Returns a Color3 value containing a green color
  1853. * @returns a new Color3 object
  1854. */
  1855. Color3.Green = function () { return new Color3(0, 1, 0); };
  1856. /**
  1857. * Returns a Color3 value containing a blue color
  1858. * @returns a new Color3 object
  1859. */
  1860. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1861. /**
  1862. * Returns a Color3 value containing a black color
  1863. * @returns a new Color3 object
  1864. */
  1865. Color3.Black = function () { return new Color3(0, 0, 0); };
  1866. /**
  1867. * Returns a Color3 value containing a white color
  1868. * @returns a new Color3 object
  1869. */
  1870. Color3.White = function () { return new Color3(1, 1, 1); };
  1871. /**
  1872. * Returns a Color3 value containing a purple color
  1873. * @returns a new Color3 object
  1874. */
  1875. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1876. /**
  1877. * Returns a Color3 value containing a magenta color
  1878. * @returns a new Color3 object
  1879. */
  1880. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1881. /**
  1882. * Returns a Color3 value containing a yellow color
  1883. * @returns a new Color3 object
  1884. */
  1885. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1886. /**
  1887. * Returns a Color3 value containing a gray color
  1888. * @returns a new Color3 object
  1889. */
  1890. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1891. /**
  1892. * Returns a Color3 value containing a teal color
  1893. * @returns a new Color3 object
  1894. */
  1895. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1896. /**
  1897. * Returns a Color3 value containing a random color
  1898. * @returns a new Color3 object
  1899. */
  1900. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1901. return Color3;
  1902. }());
  1903. BABYLON.Color3 = Color3;
  1904. /**
  1905. * Class used to hold a RBGA color
  1906. */
  1907. var Color4 = /** @class */ (function () {
  1908. /**
  1909. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1910. * @param r defines the red component (between 0 and 1, default is 0)
  1911. * @param g defines the green component (between 0 and 1, default is 0)
  1912. * @param b defines the blue component (between 0 and 1, default is 0)
  1913. * @param a defines the alpha component (between 0 and 1, default is 1)
  1914. */
  1915. function Color4(
  1916. /**
  1917. * Defines the red component (between 0 and 1, default is 0)
  1918. */
  1919. r,
  1920. /**
  1921. * Defines the green component (between 0 and 1, default is 0)
  1922. */
  1923. g,
  1924. /**
  1925. * Defines the blue component (between 0 and 1, default is 0)
  1926. */
  1927. b,
  1928. /**
  1929. * Defines the alpha component (between 0 and 1, default is 1)
  1930. */
  1931. a) {
  1932. if (r === void 0) { r = 0; }
  1933. if (g === void 0) { g = 0; }
  1934. if (b === void 0) { b = 0; }
  1935. if (a === void 0) { a = 1; }
  1936. this.r = r;
  1937. this.g = g;
  1938. this.b = b;
  1939. this.a = a;
  1940. }
  1941. // Operators
  1942. /**
  1943. * Adds in place the given Color4 values to the current Color4 object
  1944. * @param right defines the second operand
  1945. * @returns the current updated Color4 object
  1946. */
  1947. Color4.prototype.addInPlace = function (right) {
  1948. this.r += right.r;
  1949. this.g += right.g;
  1950. this.b += right.b;
  1951. this.a += right.a;
  1952. return this;
  1953. };
  1954. /**
  1955. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1956. * @returns the new array
  1957. */
  1958. Color4.prototype.asArray = function () {
  1959. var result = new Array();
  1960. this.toArray(result, 0);
  1961. return result;
  1962. };
  1963. /**
  1964. * Stores from the starting index in the given array the Color4 successive values
  1965. * @param array defines the array where to store the r,g,b components
  1966. * @param index defines an optional index in the target array to define where to start storing values
  1967. * @returns the current Color4 object
  1968. */
  1969. Color4.prototype.toArray = function (array, index) {
  1970. if (index === undefined) {
  1971. index = 0;
  1972. }
  1973. array[index] = this.r;
  1974. array[index + 1] = this.g;
  1975. array[index + 2] = this.b;
  1976. array[index + 3] = this.a;
  1977. return this;
  1978. };
  1979. /**
  1980. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1981. * @param right defines the second operand
  1982. * @returns a new Color4 object
  1983. */
  1984. Color4.prototype.add = function (right) {
  1985. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1986. };
  1987. /**
  1988. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1989. * @param right defines the second operand
  1990. * @returns a new Color4 object
  1991. */
  1992. Color4.prototype.subtract = function (right) {
  1993. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1994. };
  1995. /**
  1996. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1997. * @param right defines the second operand
  1998. * @param result defines the Color4 object where to store the result
  1999. * @returns the current Color4 object
  2000. */
  2001. Color4.prototype.subtractToRef = function (right, result) {
  2002. result.r = this.r - right.r;
  2003. result.g = this.g - right.g;
  2004. result.b = this.b - right.b;
  2005. result.a = this.a - right.a;
  2006. return this;
  2007. };
  2008. /**
  2009. * Creates a new Color4 with the current Color4 values multiplied by scale
  2010. * @param scale defines the scaling factor to apply
  2011. * @returns a new Color4 object
  2012. */
  2013. Color4.prototype.scale = function (scale) {
  2014. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  2015. };
  2016. /**
  2017. * Multiplies the current Color4 values by scale and stores the result in "result"
  2018. * @param scale defines the scaling factor to apply
  2019. * @param result defines the Color4 object where to store the result
  2020. * @returns the current unmodified Color4
  2021. */
  2022. Color4.prototype.scaleToRef = function (scale, result) {
  2023. result.r = this.r * scale;
  2024. result.g = this.g * scale;
  2025. result.b = this.b * scale;
  2026. result.a = this.a * scale;
  2027. return this;
  2028. };
  2029. /**
  2030. * Scale the current Color4 values by a factor and add the result to a given Color4
  2031. * @param scale defines the scale factor
  2032. * @param result defines the Color4 object where to store the result
  2033. * @returns the unmodified current Color4
  2034. */
  2035. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  2036. result.r += this.r * scale;
  2037. result.g += this.g * scale;
  2038. result.b += this.b * scale;
  2039. result.a += this.a * scale;
  2040. return this;
  2041. };
  2042. /**
  2043. * Clamps the rgb values by the min and max values and stores the result into "result"
  2044. * @param min defines minimum clamping value (default is 0)
  2045. * @param max defines maximum clamping value (default is 1)
  2046. * @param result defines color to store the result into.
  2047. * @returns the cuurent Color4
  2048. */
  2049. Color4.prototype.clampToRef = function (min, max, result) {
  2050. if (min === void 0) { min = 0; }
  2051. if (max === void 0) { max = 1; }
  2052. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  2053. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  2054. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  2055. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  2056. return this;
  2057. };
  2058. /**
  2059. * Multipy an Color4 value by another and return a new Color4 object
  2060. * @param color defines the Color4 value to multiply by
  2061. * @returns a new Color4 object
  2062. */
  2063. Color4.prototype.multiply = function (color) {
  2064. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2065. };
  2066. /**
  2067. * Multipy a Color4 value by another and push the result in a reference value
  2068. * @param color defines the Color4 value to multiply by
  2069. * @param result defines the Color4 to fill the result in
  2070. * @returns the result Color4
  2071. */
  2072. Color4.prototype.multiplyToRef = function (color, result) {
  2073. result.r = this.r * color.r;
  2074. result.g = this.g * color.g;
  2075. result.b = this.b * color.b;
  2076. result.a = this.a * color.a;
  2077. return result;
  2078. };
  2079. /**
  2080. * Creates a string with the Color4 current values
  2081. * @returns the string representation of the Color4 object
  2082. */
  2083. Color4.prototype.toString = function () {
  2084. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2085. };
  2086. /**
  2087. * Returns the string "Color4"
  2088. * @returns "Color4"
  2089. */
  2090. Color4.prototype.getClassName = function () {
  2091. return "Color4";
  2092. };
  2093. /**
  2094. * Compute the Color4 hash code
  2095. * @returns an unique number that can be used to hash Color4 objects
  2096. */
  2097. Color4.prototype.getHashCode = function () {
  2098. var hash = this.r || 0;
  2099. hash = (hash * 397) ^ (this.g || 0);
  2100. hash = (hash * 397) ^ (this.b || 0);
  2101. hash = (hash * 397) ^ (this.a || 0);
  2102. return hash;
  2103. };
  2104. /**
  2105. * Creates a new Color4 copied from the current one
  2106. * @returns a new Color4 object
  2107. */
  2108. Color4.prototype.clone = function () {
  2109. return new Color4(this.r, this.g, this.b, this.a);
  2110. };
  2111. /**
  2112. * Copies the given Color4 values into the current one
  2113. * @param source defines the source Color4 object
  2114. * @returns the current updated Color4 object
  2115. */
  2116. Color4.prototype.copyFrom = function (source) {
  2117. this.r = source.r;
  2118. this.g = source.g;
  2119. this.b = source.b;
  2120. this.a = source.a;
  2121. return this;
  2122. };
  2123. /**
  2124. * Copies the given float values into the current one
  2125. * @param r defines the red component to read from
  2126. * @param g defines the green component to read from
  2127. * @param b defines the blue component to read from
  2128. * @param a defines the alpha component to read from
  2129. * @returns the current updated Color4 object
  2130. */
  2131. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2132. this.r = r;
  2133. this.g = g;
  2134. this.b = b;
  2135. this.a = a;
  2136. return this;
  2137. };
  2138. /**
  2139. * Copies the given float values into the current one
  2140. * @param r defines the red component to read from
  2141. * @param g defines the green component to read from
  2142. * @param b defines the blue component to read from
  2143. * @param a defines the alpha component to read from
  2144. * @returns the current updated Color4 object
  2145. */
  2146. Color4.prototype.set = function (r, g, b, a) {
  2147. return this.copyFromFloats(r, g, b, a);
  2148. };
  2149. /**
  2150. * Compute the Color4 hexadecimal code as a string
  2151. * @returns a string containing the hexadecimal representation of the Color4 object
  2152. */
  2153. Color4.prototype.toHexString = function () {
  2154. var intR = (this.r * 255) | 0;
  2155. var intG = (this.g * 255) | 0;
  2156. var intB = (this.b * 255) | 0;
  2157. var intA = (this.a * 255) | 0;
  2158. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2159. };
  2160. /**
  2161. * Computes a new Color4 converted from the current one to linear space
  2162. * @returns a new Color4 object
  2163. */
  2164. Color4.prototype.toLinearSpace = function () {
  2165. var convertedColor = new Color4();
  2166. this.toLinearSpaceToRef(convertedColor);
  2167. return convertedColor;
  2168. };
  2169. /**
  2170. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2171. * @param convertedColor defines the Color4 object where to store the linear space version
  2172. * @returns the unmodified Color4
  2173. */
  2174. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2175. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2176. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2177. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2178. convertedColor.a = this.a;
  2179. return this;
  2180. };
  2181. /**
  2182. * Computes a new Color4 converted from the current one to gamma space
  2183. * @returns a new Color4 object
  2184. */
  2185. Color4.prototype.toGammaSpace = function () {
  2186. var convertedColor = new Color4();
  2187. this.toGammaSpaceToRef(convertedColor);
  2188. return convertedColor;
  2189. };
  2190. /**
  2191. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2192. * @param convertedColor defines the Color4 object where to store the gamma space version
  2193. * @returns the unmodified Color4
  2194. */
  2195. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2196. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2197. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2198. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2199. convertedColor.a = this.a;
  2200. return this;
  2201. };
  2202. // Statics
  2203. /**
  2204. * Creates a new Color4 from the string containing valid hexadecimal values
  2205. * @param hex defines a string containing valid hexadecimal values
  2206. * @returns a new Color4 object
  2207. */
  2208. Color4.FromHexString = function (hex) {
  2209. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2210. return new Color4(0.0, 0.0, 0.0, 0.0);
  2211. }
  2212. var r = parseInt(hex.substring(1, 3), 16);
  2213. var g = parseInt(hex.substring(3, 5), 16);
  2214. var b = parseInt(hex.substring(5, 7), 16);
  2215. var a = parseInt(hex.substring(7, 9), 16);
  2216. return Color4.FromInts(r, g, b, a);
  2217. };
  2218. /**
  2219. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2220. * @param left defines the start value
  2221. * @param right defines the end value
  2222. * @param amount defines the gradient factor
  2223. * @returns a new Color4 object
  2224. */
  2225. Color4.Lerp = function (left, right, amount) {
  2226. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2227. Color4.LerpToRef(left, right, amount, result);
  2228. return result;
  2229. };
  2230. /**
  2231. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2232. * @param left defines the start value
  2233. * @param right defines the end value
  2234. * @param amount defines the gradient factor
  2235. * @param result defines the Color4 object where to store data
  2236. */
  2237. Color4.LerpToRef = function (left, right, amount, result) {
  2238. result.r = left.r + (right.r - left.r) * amount;
  2239. result.g = left.g + (right.g - left.g) * amount;
  2240. result.b = left.b + (right.b - left.b) * amount;
  2241. result.a = left.a + (right.a - left.a) * amount;
  2242. };
  2243. /**
  2244. * Creates a new Color4 from a Color3 and an alpha value
  2245. * @param color3 defines the source Color3 to read from
  2246. * @param alpha defines the alpha component (1.0 by default)
  2247. * @returns a new Color4 object
  2248. */
  2249. Color4.FromColor3 = function (color3, alpha) {
  2250. if (alpha === void 0) { alpha = 1.0; }
  2251. return new Color4(color3.r, color3.g, color3.b, alpha);
  2252. };
  2253. /**
  2254. * Creates a new Color4 from the starting index element of the given array
  2255. * @param array defines the source array to read from
  2256. * @param offset defines the offset in the source array
  2257. * @returns a new Color4 object
  2258. */
  2259. Color4.FromArray = function (array, offset) {
  2260. if (offset === void 0) { offset = 0; }
  2261. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2262. };
  2263. /**
  2264. * Creates a new Color3 from integer values (< 256)
  2265. * @param r defines the red component to read from (value between 0 and 255)
  2266. * @param g defines the green component to read from (value between 0 and 255)
  2267. * @param b defines the blue component to read from (value between 0 and 255)
  2268. * @param a defines the alpha component to read from (value between 0 and 255)
  2269. * @returns a new Color3 object
  2270. */
  2271. Color4.FromInts = function (r, g, b, a) {
  2272. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2273. };
  2274. /**
  2275. * Check the content of a given array and convert it to an array containing RGBA data
  2276. * If the original array was already containing count * 4 values then it is returned directly
  2277. * @param colors defines the array to check
  2278. * @param count defines the number of RGBA data to expect
  2279. * @returns an array containing count * 4 values (RGBA)
  2280. */
  2281. Color4.CheckColors4 = function (colors, count) {
  2282. // Check if color3 was used
  2283. if (colors.length === count * 3) {
  2284. var colors4 = [];
  2285. for (var index = 0; index < colors.length; index += 3) {
  2286. var newIndex = (index / 3) * 4;
  2287. colors4[newIndex] = colors[index];
  2288. colors4[newIndex + 1] = colors[index + 1];
  2289. colors4[newIndex + 2] = colors[index + 2];
  2290. colors4[newIndex + 3] = 1.0;
  2291. }
  2292. return colors4;
  2293. }
  2294. return colors;
  2295. };
  2296. return Color4;
  2297. }());
  2298. BABYLON.Color4 = Color4;
  2299. /**
  2300. * Class representing a vector containing 2 coordinates
  2301. */
  2302. var Vector2 = /** @class */ (function () {
  2303. /**
  2304. * Creates a new Vector2 from the given x and y coordinates
  2305. * @param x defines the first coordinate
  2306. * @param y defines the second coordinate
  2307. */
  2308. function Vector2(
  2309. /** defines the first coordinate */
  2310. x,
  2311. /** defines the second coordinate */
  2312. y) {
  2313. if (x === void 0) { x = 0; }
  2314. if (y === void 0) { y = 0; }
  2315. this.x = x;
  2316. this.y = y;
  2317. }
  2318. /**
  2319. * Gets a string with the Vector2 coordinates
  2320. * @returns a string with the Vector2 coordinates
  2321. */
  2322. Vector2.prototype.toString = function () {
  2323. return "{X: " + this.x + " Y:" + this.y + "}";
  2324. };
  2325. /**
  2326. * Gets class name
  2327. * @returns the string "Vector2"
  2328. */
  2329. Vector2.prototype.getClassName = function () {
  2330. return "Vector2";
  2331. };
  2332. /**
  2333. * Gets current vector hash code
  2334. * @returns the Vector2 hash code as a number
  2335. */
  2336. Vector2.prototype.getHashCode = function () {
  2337. var hash = this.x || 0;
  2338. hash = (hash * 397) ^ (this.y || 0);
  2339. return hash;
  2340. };
  2341. // Operators
  2342. /**
  2343. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2344. * @param array defines the source array
  2345. * @param index defines the offset in source array
  2346. * @returns the current Vector2
  2347. */
  2348. Vector2.prototype.toArray = function (array, index) {
  2349. if (index === void 0) { index = 0; }
  2350. array[index] = this.x;
  2351. array[index + 1] = this.y;
  2352. return this;
  2353. };
  2354. /**
  2355. * Copy the current vector to an array
  2356. * @returns a new array with 2 elements: the Vector2 coordinates.
  2357. */
  2358. Vector2.prototype.asArray = function () {
  2359. var result = new Array();
  2360. this.toArray(result, 0);
  2361. return result;
  2362. };
  2363. /**
  2364. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2365. * @param source defines the source Vector2
  2366. * @returns the current updated Vector2
  2367. */
  2368. Vector2.prototype.copyFrom = function (source) {
  2369. this.x = source.x;
  2370. this.y = source.y;
  2371. return this;
  2372. };
  2373. /**
  2374. * Sets the Vector2 coordinates with the given floats
  2375. * @param x defines the first coordinate
  2376. * @param y defines the second coordinate
  2377. * @returns the current updated Vector2
  2378. */
  2379. Vector2.prototype.copyFromFloats = function (x, y) {
  2380. this.x = x;
  2381. this.y = y;
  2382. return this;
  2383. };
  2384. /**
  2385. * Sets the Vector2 coordinates with the given floats
  2386. * @param x defines the first coordinate
  2387. * @param y defines the second coordinate
  2388. * @returns the current updated Vector2
  2389. */
  2390. Vector2.prototype.set = function (x, y) {
  2391. return this.copyFromFloats(x, y);
  2392. };
  2393. /**
  2394. * Add another vector with the current one
  2395. * @param otherVector defines the other vector
  2396. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2397. */
  2398. Vector2.prototype.add = function (otherVector) {
  2399. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2400. };
  2401. /**
  2402. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2403. * @param otherVector defines the other vector
  2404. * @param result defines the target vector
  2405. * @returns the unmodified current Vector2
  2406. */
  2407. Vector2.prototype.addToRef = function (otherVector, result) {
  2408. result.x = this.x + otherVector.x;
  2409. result.y = this.y + otherVector.y;
  2410. return this;
  2411. };
  2412. /**
  2413. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2414. * @param otherVector defines the other vector
  2415. * @returns the current updated Vector2
  2416. */
  2417. Vector2.prototype.addInPlace = function (otherVector) {
  2418. this.x += otherVector.x;
  2419. this.y += otherVector.y;
  2420. return this;
  2421. };
  2422. /**
  2423. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2424. * @param otherVector defines the other vector
  2425. * @returns a new Vector2
  2426. */
  2427. Vector2.prototype.addVector3 = function (otherVector) {
  2428. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2429. };
  2430. /**
  2431. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2432. * @param otherVector defines the other vector
  2433. * @returns a new Vector2
  2434. */
  2435. Vector2.prototype.subtract = function (otherVector) {
  2436. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2437. };
  2438. /**
  2439. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2440. * @param otherVector defines the other vector
  2441. * @param result defines the target vector
  2442. * @returns the unmodified current Vector2
  2443. */
  2444. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2445. result.x = this.x - otherVector.x;
  2446. result.y = this.y - otherVector.y;
  2447. return this;
  2448. };
  2449. /**
  2450. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2451. * @param otherVector defines the other vector
  2452. * @returns the current updated Vector2
  2453. */
  2454. Vector2.prototype.subtractInPlace = function (otherVector) {
  2455. this.x -= otherVector.x;
  2456. this.y -= otherVector.y;
  2457. return this;
  2458. };
  2459. /**
  2460. * Multiplies in place the current Vector2 coordinates by the given ones
  2461. * @param otherVector defines the other vector
  2462. * @returns the current updated Vector2
  2463. */
  2464. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2465. this.x *= otherVector.x;
  2466. this.y *= otherVector.y;
  2467. return this;
  2468. };
  2469. /**
  2470. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2471. * @param otherVector defines the other vector
  2472. * @returns a new Vector2
  2473. */
  2474. Vector2.prototype.multiply = function (otherVector) {
  2475. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2476. };
  2477. /**
  2478. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2479. * @param otherVector defines the other vector
  2480. * @param result defines the target vector
  2481. * @returns the unmodified current Vector2
  2482. */
  2483. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2484. result.x = this.x * otherVector.x;
  2485. result.y = this.y * otherVector.y;
  2486. return this;
  2487. };
  2488. /**
  2489. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2490. * @param x defines the first coordinate
  2491. * @param y defines the second coordinate
  2492. * @returns a new Vector2
  2493. */
  2494. Vector2.prototype.multiplyByFloats = function (x, y) {
  2495. return new Vector2(this.x * x, this.y * y);
  2496. };
  2497. /**
  2498. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2499. * @param otherVector defines the other vector
  2500. * @returns a new Vector2
  2501. */
  2502. Vector2.prototype.divide = function (otherVector) {
  2503. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2504. };
  2505. /**
  2506. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2507. * @param otherVector defines the other vector
  2508. * @param result defines the target vector
  2509. * @returns the unmodified current Vector2
  2510. */
  2511. Vector2.prototype.divideToRef = function (otherVector, result) {
  2512. result.x = this.x / otherVector.x;
  2513. result.y = this.y / otherVector.y;
  2514. return this;
  2515. };
  2516. /**
  2517. * Divides the current Vector2 coordinates by the given ones
  2518. * @param otherVector defines the other vector
  2519. * @returns the current updated Vector2
  2520. */
  2521. Vector2.prototype.divideInPlace = function (otherVector) {
  2522. return this.divideToRef(otherVector, this);
  2523. };
  2524. /**
  2525. * Gets a new Vector2 with current Vector2 negated coordinates
  2526. * @returns a new Vector2
  2527. */
  2528. Vector2.prototype.negate = function () {
  2529. return new Vector2(-this.x, -this.y);
  2530. };
  2531. /**
  2532. * Multiply the Vector2 coordinates by scale
  2533. * @param scale defines the scaling factor
  2534. * @returns the current updated Vector2
  2535. */
  2536. Vector2.prototype.scaleInPlace = function (scale) {
  2537. this.x *= scale;
  2538. this.y *= scale;
  2539. return this;
  2540. };
  2541. /**
  2542. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2543. * @param scale defines the scaling factor
  2544. * @returns a new Vector2
  2545. */
  2546. Vector2.prototype.scale = function (scale) {
  2547. var result = new Vector2(0, 0);
  2548. this.scaleToRef(scale, result);
  2549. return result;
  2550. };
  2551. /**
  2552. * Scale the current Vector2 values by a factor to a given Vector2
  2553. * @param scale defines the scale factor
  2554. * @param result defines the Vector2 object where to store the result
  2555. * @returns the unmodified current Vector2
  2556. */
  2557. Vector2.prototype.scaleToRef = function (scale, result) {
  2558. result.x = this.x * scale;
  2559. result.y = this.y * scale;
  2560. return this;
  2561. };
  2562. /**
  2563. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2564. * @param scale defines the scale factor
  2565. * @param result defines the Vector2 object where to store the result
  2566. * @returns the unmodified current Vector2
  2567. */
  2568. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2569. result.x += this.x * scale;
  2570. result.y += this.y * scale;
  2571. return this;
  2572. };
  2573. /**
  2574. * Gets a boolean if two vectors are equals
  2575. * @param otherVector defines the other vector
  2576. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2577. */
  2578. Vector2.prototype.equals = function (otherVector) {
  2579. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2580. };
  2581. /**
  2582. * Gets a boolean if two vectors are equals (using an epsilon value)
  2583. * @param otherVector defines the other vector
  2584. * @param epsilon defines the minimal distance to consider equality
  2585. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2586. */
  2587. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2588. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2589. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2590. };
  2591. /**
  2592. * Gets a new Vector2 from current Vector2 floored values
  2593. * @returns a new Vector2
  2594. */
  2595. Vector2.prototype.floor = function () {
  2596. return new Vector2(Math.floor(this.x), Math.floor(this.y));
  2597. };
  2598. /**
  2599. * Gets a new Vector2 from current Vector2 floored values
  2600. * @returns a new Vector2
  2601. */
  2602. Vector2.prototype.fract = function () {
  2603. return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
  2604. };
  2605. // Properties
  2606. /**
  2607. * Gets the length of the vector
  2608. * @returns the vector length (float)
  2609. */
  2610. Vector2.prototype.length = function () {
  2611. return Math.sqrt(this.x * this.x + this.y * this.y);
  2612. };
  2613. /**
  2614. * Gets the vector squared length
  2615. * @returns the vector squared length (float)
  2616. */
  2617. Vector2.prototype.lengthSquared = function () {
  2618. return (this.x * this.x + this.y * this.y);
  2619. };
  2620. // Methods
  2621. /**
  2622. * Normalize the vector
  2623. * @returns the current updated Vector2
  2624. */
  2625. Vector2.prototype.normalize = function () {
  2626. var len = this.length();
  2627. if (len === 0) {
  2628. return this;
  2629. }
  2630. var num = 1.0 / len;
  2631. this.x *= num;
  2632. this.y *= num;
  2633. return this;
  2634. };
  2635. /**
  2636. * Gets a new Vector2 copied from the Vector2
  2637. * @returns a new Vector2
  2638. */
  2639. Vector2.prototype.clone = function () {
  2640. return new Vector2(this.x, this.y);
  2641. };
  2642. // Statics
  2643. /**
  2644. * Gets a new Vector2(0, 0)
  2645. * @returns a new Vector2
  2646. */
  2647. Vector2.Zero = function () {
  2648. return new Vector2(0, 0);
  2649. };
  2650. /**
  2651. * Gets a new Vector2(1, 1)
  2652. * @returns a new Vector2
  2653. */
  2654. Vector2.One = function () {
  2655. return new Vector2(1, 1);
  2656. };
  2657. /**
  2658. * Gets a new Vector2 set from the given index element of the given array
  2659. * @param array defines the data source
  2660. * @param offset defines the offset in the data source
  2661. * @returns a new Vector2
  2662. */
  2663. Vector2.FromArray = function (array, offset) {
  2664. if (offset === void 0) { offset = 0; }
  2665. return new Vector2(array[offset], array[offset + 1]);
  2666. };
  2667. /**
  2668. * Sets "result" from the given index element of the given array
  2669. * @param array defines the data source
  2670. * @param offset defines the offset in the data source
  2671. * @param result defines the target vector
  2672. */
  2673. Vector2.FromArrayToRef = function (array, offset, result) {
  2674. result.x = array[offset];
  2675. result.y = array[offset + 1];
  2676. };
  2677. /**
  2678. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2679. * @param value1 defines 1st point of control
  2680. * @param value2 defines 2nd point of control
  2681. * @param value3 defines 3rd point of control
  2682. * @param value4 defines 4th point of control
  2683. * @param amount defines the interpolation factor
  2684. * @returns a new Vector2
  2685. */
  2686. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2687. var squared = amount * amount;
  2688. var cubed = amount * squared;
  2689. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2690. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2691. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2692. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2693. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2694. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2695. return new Vector2(x, y);
  2696. };
  2697. /**
  2698. * 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".
  2699. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2700. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2701. * @param value defines the value to clamp
  2702. * @param min defines the lower limit
  2703. * @param max defines the upper limit
  2704. * @returns a new Vector2
  2705. */
  2706. Vector2.Clamp = function (value, min, max) {
  2707. var x = value.x;
  2708. x = (x > max.x) ? max.x : x;
  2709. x = (x < min.x) ? min.x : x;
  2710. var y = value.y;
  2711. y = (y > max.y) ? max.y : y;
  2712. y = (y < min.y) ? min.y : y;
  2713. return new Vector2(x, y);
  2714. };
  2715. /**
  2716. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2717. * @param value1 defines the 1st control point
  2718. * @param tangent1 defines the outgoing tangent
  2719. * @param value2 defines the 2nd control point
  2720. * @param tangent2 defines the incoming tangent
  2721. * @param amount defines the interpolation factor
  2722. * @returns a new Vector2
  2723. */
  2724. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2725. var squared = amount * amount;
  2726. var cubed = amount * squared;
  2727. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2728. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2729. var part3 = (cubed - (2.0 * squared)) + amount;
  2730. var part4 = cubed - squared;
  2731. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2732. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2733. return new Vector2(x, y);
  2734. };
  2735. /**
  2736. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2737. * @param start defines the start vector
  2738. * @param end defines the end vector
  2739. * @param amount defines the interpolation factor
  2740. * @returns a new Vector2
  2741. */
  2742. Vector2.Lerp = function (start, end, amount) {
  2743. var x = start.x + ((end.x - start.x) * amount);
  2744. var y = start.y + ((end.y - start.y) * amount);
  2745. return new Vector2(x, y);
  2746. };
  2747. /**
  2748. * Gets the dot product of the vector "left" and the vector "right"
  2749. * @param left defines first vector
  2750. * @param right defines second vector
  2751. * @returns the dot product (float)
  2752. */
  2753. Vector2.Dot = function (left, right) {
  2754. return left.x * right.x + left.y * right.y;
  2755. };
  2756. /**
  2757. * Returns a new Vector2 equal to the normalized given vector
  2758. * @param vector defines the vector to normalize
  2759. * @returns a new Vector2
  2760. */
  2761. Vector2.Normalize = function (vector) {
  2762. var newVector = vector.clone();
  2763. newVector.normalize();
  2764. return newVector;
  2765. };
  2766. /**
  2767. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2768. * @param left defines 1st vector
  2769. * @param right defines 2nd vector
  2770. * @returns a new Vector2
  2771. */
  2772. Vector2.Minimize = function (left, right) {
  2773. var x = (left.x < right.x) ? left.x : right.x;
  2774. var y = (left.y < right.y) ? left.y : right.y;
  2775. return new Vector2(x, y);
  2776. };
  2777. /**
  2778. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2779. * @param left defines 1st vector
  2780. * @param right defines 2nd vector
  2781. * @returns a new Vector2
  2782. */
  2783. Vector2.Maximize = function (left, right) {
  2784. var x = (left.x > right.x) ? left.x : right.x;
  2785. var y = (left.y > right.y) ? left.y : right.y;
  2786. return new Vector2(x, y);
  2787. };
  2788. /**
  2789. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2790. * @param vector defines the vector to transform
  2791. * @param transformation defines the matrix to apply
  2792. * @returns a new Vector2
  2793. */
  2794. Vector2.Transform = function (vector, transformation) {
  2795. var r = Vector2.Zero();
  2796. Vector2.TransformToRef(vector, transformation, r);
  2797. return r;
  2798. };
  2799. /**
  2800. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2801. * @param vector defines the vector to transform
  2802. * @param transformation defines the matrix to apply
  2803. * @param result defines the target vector
  2804. */
  2805. Vector2.TransformToRef = function (vector, transformation, result) {
  2806. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2807. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2808. result.x = x;
  2809. result.y = y;
  2810. };
  2811. /**
  2812. * Determines if a given vector is included in a triangle
  2813. * @param p defines the vector to test
  2814. * @param p0 defines 1st triangle point
  2815. * @param p1 defines 2nd triangle point
  2816. * @param p2 defines 3rd triangle point
  2817. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2818. */
  2819. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2820. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2821. var sign = a < 0 ? -1 : 1;
  2822. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2823. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2824. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2825. };
  2826. /**
  2827. * Gets the distance between the vectors "value1" and "value2"
  2828. * @param value1 defines first vector
  2829. * @param value2 defines second vector
  2830. * @returns the distance between vectors
  2831. */
  2832. Vector2.Distance = function (value1, value2) {
  2833. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2834. };
  2835. /**
  2836. * Returns the squared distance between the vectors "value1" and "value2"
  2837. * @param value1 defines first vector
  2838. * @param value2 defines second vector
  2839. * @returns the squared distance between vectors
  2840. */
  2841. Vector2.DistanceSquared = function (value1, value2) {
  2842. var x = value1.x - value2.x;
  2843. var y = value1.y - value2.y;
  2844. return (x * x) + (y * y);
  2845. };
  2846. /**
  2847. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2848. * @param value1 defines first vector
  2849. * @param value2 defines second vector
  2850. * @returns a new Vector2
  2851. */
  2852. Vector2.Center = function (value1, value2) {
  2853. var center = value1.add(value2);
  2854. center.scaleInPlace(0.5);
  2855. return center;
  2856. };
  2857. /**
  2858. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2859. * @param p defines the middle point
  2860. * @param segA defines one point of the segment
  2861. * @param segB defines the other point of the segment
  2862. * @returns the shortest distance
  2863. */
  2864. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2865. var l2 = Vector2.DistanceSquared(segA, segB);
  2866. if (l2 === 0.0) {
  2867. return Vector2.Distance(p, segA);
  2868. }
  2869. var v = segB.subtract(segA);
  2870. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2871. var proj = segA.add(v.multiplyByFloats(t, t));
  2872. return Vector2.Distance(p, proj);
  2873. };
  2874. return Vector2;
  2875. }());
  2876. BABYLON.Vector2 = Vector2;
  2877. /**
  2878. * Classed used to store (x,y,z) vector representation
  2879. * A Vector3 is the main object used in 3D geometry
  2880. * It can represent etiher the coordinates of a point the space, either a direction
  2881. * Reminder: Babylon.js uses a left handed forward facing system
  2882. */
  2883. var Vector3 = /** @class */ (function () {
  2884. /**
  2885. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2886. * @param x defines the first coordinates (on X axis)
  2887. * @param y defines the second coordinates (on Y axis)
  2888. * @param z defines the third coordinates (on Z axis)
  2889. */
  2890. function Vector3(
  2891. /**
  2892. * Defines the first coordinates (on X axis)
  2893. */
  2894. x,
  2895. /**
  2896. * Defines the second coordinates (on Y axis)
  2897. */
  2898. y,
  2899. /**
  2900. * Defines the third coordinates (on Z axis)
  2901. */
  2902. z) {
  2903. if (x === void 0) { x = 0; }
  2904. if (y === void 0) { y = 0; }
  2905. if (z === void 0) { z = 0; }
  2906. this.x = x;
  2907. this.y = y;
  2908. this.z = z;
  2909. }
  2910. /**
  2911. * Creates a string representation of the Vector3
  2912. * @returns a string with the Vector3 coordinates.
  2913. */
  2914. Vector3.prototype.toString = function () {
  2915. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2916. };
  2917. /**
  2918. * Gets the class name
  2919. * @returns the string "Vector3"
  2920. */
  2921. Vector3.prototype.getClassName = function () {
  2922. return "Vector3";
  2923. };
  2924. /**
  2925. * Creates the Vector3 hash code
  2926. * @returns a number which tends to be unique between Vector3 instances
  2927. */
  2928. Vector3.prototype.getHashCode = function () {
  2929. var hash = this.x || 0;
  2930. hash = (hash * 397) ^ (this.y || 0);
  2931. hash = (hash * 397) ^ (this.z || 0);
  2932. return hash;
  2933. };
  2934. // Operators
  2935. /**
  2936. * Creates an array containing three elements : the coordinates of the Vector3
  2937. * @returns a new array of numbers
  2938. */
  2939. Vector3.prototype.asArray = function () {
  2940. var result = [];
  2941. this.toArray(result, 0);
  2942. return result;
  2943. };
  2944. /**
  2945. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2946. * @param array defines the destination array
  2947. * @param index defines the offset in the destination array
  2948. * @returns the current Vector3
  2949. */
  2950. Vector3.prototype.toArray = function (array, index) {
  2951. if (index === void 0) { index = 0; }
  2952. array[index] = this.x;
  2953. array[index + 1] = this.y;
  2954. array[index + 2] = this.z;
  2955. return this;
  2956. };
  2957. /**
  2958. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2959. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2960. */
  2961. Vector3.prototype.toQuaternion = function () {
  2962. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2963. };
  2964. /**
  2965. * Adds the given vector to the current Vector3
  2966. * @param otherVector defines the second operand
  2967. * @returns the current updated Vector3
  2968. */
  2969. Vector3.prototype.addInPlace = function (otherVector) {
  2970. this.x += otherVector.x;
  2971. this.y += otherVector.y;
  2972. this.z += otherVector.z;
  2973. return this;
  2974. };
  2975. /**
  2976. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2977. * @param otherVector defines the second operand
  2978. * @returns the resulting Vector3
  2979. */
  2980. Vector3.prototype.add = function (otherVector) {
  2981. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2982. };
  2983. /**
  2984. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2985. * @param otherVector defines the second operand
  2986. * @param result defines the Vector3 object where to store the result
  2987. * @returns the current Vector3
  2988. */
  2989. Vector3.prototype.addToRef = function (otherVector, result) {
  2990. result.x = this.x + otherVector.x;
  2991. result.y = this.y + otherVector.y;
  2992. result.z = this.z + otherVector.z;
  2993. return this;
  2994. };
  2995. /**
  2996. * Subtract the given vector from the current Vector3
  2997. * @param otherVector defines the second operand
  2998. * @returns the current updated Vector3
  2999. */
  3000. Vector3.prototype.subtractInPlace = function (otherVector) {
  3001. this.x -= otherVector.x;
  3002. this.y -= otherVector.y;
  3003. this.z -= otherVector.z;
  3004. return this;
  3005. };
  3006. /**
  3007. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  3008. * @param otherVector defines the second operand
  3009. * @returns the resulting Vector3
  3010. */
  3011. Vector3.prototype.subtract = function (otherVector) {
  3012. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  3013. };
  3014. /**
  3015. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  3016. * @param otherVector defines the second operand
  3017. * @param result defines the Vector3 object where to store the result
  3018. * @returns the current Vector3
  3019. */
  3020. Vector3.prototype.subtractToRef = function (otherVector, result) {
  3021. result.x = this.x - otherVector.x;
  3022. result.y = this.y - otherVector.y;
  3023. result.z = this.z - otherVector.z;
  3024. return this;
  3025. };
  3026. /**
  3027. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  3028. * @param x defines the x coordinate of the operand
  3029. * @param y defines the y coordinate of the operand
  3030. * @param z defines the z coordinate of the operand
  3031. * @returns the resulting Vector3
  3032. */
  3033. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  3034. return new Vector3(this.x - x, this.y - y, this.z - z);
  3035. };
  3036. /**
  3037. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  3038. * @param x defines the x coordinate of the operand
  3039. * @param y defines the y coordinate of the operand
  3040. * @param z defines the z coordinate of the operand
  3041. * @param result defines the Vector3 object where to store the result
  3042. * @returns the current Vector3
  3043. */
  3044. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  3045. result.x = this.x - x;
  3046. result.y = this.y - y;
  3047. result.z = this.z - z;
  3048. return this;
  3049. };
  3050. /**
  3051. * Gets a new Vector3 set with the current Vector3 negated coordinates
  3052. * @returns a new Vector3
  3053. */
  3054. Vector3.prototype.negate = function () {
  3055. return new Vector3(-this.x, -this.y, -this.z);
  3056. };
  3057. /**
  3058. * Multiplies the Vector3 coordinates by the float "scale"
  3059. * @param scale defines the multiplier factor
  3060. * @returns the current updated Vector3
  3061. */
  3062. Vector3.prototype.scaleInPlace = function (scale) {
  3063. this.x *= scale;
  3064. this.y *= scale;
  3065. this.z *= scale;
  3066. return this;
  3067. };
  3068. /**
  3069. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  3070. * @param scale defines the multiplier factor
  3071. * @returns a new Vector3
  3072. */
  3073. Vector3.prototype.scale = function (scale) {
  3074. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  3075. };
  3076. /**
  3077. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  3078. * @param scale defines the multiplier factor
  3079. * @param result defines the Vector3 object where to store the result
  3080. * @returns the current Vector3
  3081. */
  3082. Vector3.prototype.scaleToRef = function (scale, result) {
  3083. result.x = this.x * scale;
  3084. result.y = this.y * scale;
  3085. result.z = this.z * scale;
  3086. return this;
  3087. };
  3088. /**
  3089. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  3090. * @param scale defines the scale factor
  3091. * @param result defines the Vector3 object where to store the result
  3092. * @returns the unmodified current Vector3
  3093. */
  3094. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  3095. result.x += this.x * scale;
  3096. result.y += this.y * scale;
  3097. result.z += this.z * scale;
  3098. return this;
  3099. };
  3100. /**
  3101. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3102. * @param otherVector defines the second operand
  3103. * @returns true if both vectors are equals
  3104. */
  3105. Vector3.prototype.equals = function (otherVector) {
  3106. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3107. };
  3108. /**
  3109. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3110. * @param otherVector defines the second operand
  3111. * @param epsilon defines the minimal distance to define values as equals
  3112. * @returns true if both vectors are distant less than epsilon
  3113. */
  3114. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3115. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3116. 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);
  3117. };
  3118. /**
  3119. * Returns true if the current Vector3 coordinates equals the given floats
  3120. * @param x defines the x coordinate of the operand
  3121. * @param y defines the y coordinate of the operand
  3122. * @param z defines the z coordinate of the operand
  3123. * @returns true if both vectors are equals
  3124. */
  3125. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3126. return this.x === x && this.y === y && this.z === z;
  3127. };
  3128. /**
  3129. * Multiplies the current Vector3 coordinates by the given ones
  3130. * @param otherVector defines the second operand
  3131. * @returns the current updated Vector3
  3132. */
  3133. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3134. this.x *= otherVector.x;
  3135. this.y *= otherVector.y;
  3136. this.z *= otherVector.z;
  3137. return this;
  3138. };
  3139. /**
  3140. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3141. * @param otherVector defines the second operand
  3142. * @returns the new Vector3
  3143. */
  3144. Vector3.prototype.multiply = function (otherVector) {
  3145. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3146. };
  3147. /**
  3148. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3149. * @param otherVector defines the second operand
  3150. * @param result defines the Vector3 object where to store the result
  3151. * @returns the current Vector3
  3152. */
  3153. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3154. result.x = this.x * otherVector.x;
  3155. result.y = this.y * otherVector.y;
  3156. result.z = this.z * otherVector.z;
  3157. return this;
  3158. };
  3159. /**
  3160. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3161. * @param x defines the x coordinate of the operand
  3162. * @param y defines the y coordinate of the operand
  3163. * @param z defines the z coordinate of the operand
  3164. * @returns the new Vector3
  3165. */
  3166. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3167. return new Vector3(this.x * x, this.y * y, this.z * z);
  3168. };
  3169. /**
  3170. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3171. * @param otherVector defines the second operand
  3172. * @returns the new Vector3
  3173. */
  3174. Vector3.prototype.divide = function (otherVector) {
  3175. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3176. };
  3177. /**
  3178. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3179. * @param otherVector defines the second operand
  3180. * @param result defines the Vector3 object where to store the result
  3181. * @returns the current Vector3
  3182. */
  3183. Vector3.prototype.divideToRef = function (otherVector, result) {
  3184. result.x = this.x / otherVector.x;
  3185. result.y = this.y / otherVector.y;
  3186. result.z = this.z / otherVector.z;
  3187. return this;
  3188. };
  3189. /**
  3190. * Divides the current Vector3 coordinates by the given ones.
  3191. * @param otherVector defines the second operand
  3192. * @returns the current updated Vector3
  3193. */
  3194. Vector3.prototype.divideInPlace = function (otherVector) {
  3195. return this.divideToRef(otherVector, this);
  3196. };
  3197. /**
  3198. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3199. * @param other defines the second operand
  3200. * @returns the current updated Vector3
  3201. */
  3202. Vector3.prototype.minimizeInPlace = function (other) {
  3203. return this.minimizeInPlaceFromFloats(other.x, other.y, other.z);
  3204. };
  3205. /**
  3206. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3207. * @param other defines the second operand
  3208. * @returns the current updated Vector3
  3209. */
  3210. Vector3.prototype.maximizeInPlace = function (other) {
  3211. return this.maximizeInPlaceFromFloats(other.x, other.y, other.z);
  3212. };
  3213. /**
  3214. * Updates the current Vector3 with the minimal coordinate values between its and the given coordinates
  3215. * @param x defines the x coordinate of the operand
  3216. * @param y defines the y coordinate of the operand
  3217. * @param z defines the z coordinate of the operand
  3218. * @returns the current updated Vector3
  3219. */
  3220. Vector3.prototype.minimizeInPlaceFromFloats = function (x, y, z) {
  3221. if (x < this.x) {
  3222. this.x = x;
  3223. }
  3224. if (y < this.y) {
  3225. this.y = y;
  3226. }
  3227. if (z < this.z) {
  3228. this.z = z;
  3229. }
  3230. return this;
  3231. };
  3232. /**
  3233. * Updates the current Vector3 with the maximal coordinate values between its and the given coordinates.
  3234. * @param x defines the x coordinate of the operand
  3235. * @param y defines the y coordinate of the operand
  3236. * @param z defines the z coordinate of the operand
  3237. * @returns the current updated Vector3
  3238. */
  3239. Vector3.prototype.maximizeInPlaceFromFloats = function (x, y, z) {
  3240. if (x > this.x) {
  3241. this.x = x;
  3242. }
  3243. if (y > this.y) {
  3244. this.y = y;
  3245. }
  3246. if (z > this.z) {
  3247. this.z = z;
  3248. }
  3249. return this;
  3250. };
  3251. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3252. /**
  3253. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3254. */
  3255. get: function () {
  3256. var absX = Math.abs(this.x);
  3257. var absY = Math.abs(this.y);
  3258. if (absX !== absY) {
  3259. return true;
  3260. }
  3261. var absZ = Math.abs(this.z);
  3262. if (absX !== absZ) {
  3263. return true;
  3264. }
  3265. if (absY !== absZ) {
  3266. return true;
  3267. }
  3268. return false;
  3269. },
  3270. enumerable: true,
  3271. configurable: true
  3272. });
  3273. /**
  3274. * Gets a new Vector3 from current Vector3 floored values
  3275. * @returns a new Vector3
  3276. */
  3277. Vector3.prototype.floor = function () {
  3278. return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
  3279. };
  3280. /**
  3281. * Gets a new Vector3 from current Vector3 floored values
  3282. * @returns a new Vector3
  3283. */
  3284. Vector3.prototype.fract = function () {
  3285. return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));
  3286. };
  3287. // Properties
  3288. /**
  3289. * Gets the length of the Vector3
  3290. * @returns the length of the Vecto3
  3291. */
  3292. Vector3.prototype.length = function () {
  3293. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3294. };
  3295. /**
  3296. * Gets the squared length of the Vector3
  3297. * @returns squared length of the Vector3
  3298. */
  3299. Vector3.prototype.lengthSquared = function () {
  3300. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3301. };
  3302. /**
  3303. * Normalize the current Vector3.
  3304. * Please note that this is an in place operation.
  3305. * @returns the current updated Vector3
  3306. */
  3307. Vector3.prototype.normalize = function () {
  3308. var len = this.length();
  3309. if (len === 0 || len === 1.0) {
  3310. return this;
  3311. }
  3312. var num = 1.0 / len;
  3313. this.x *= num;
  3314. this.y *= num;
  3315. this.z *= num;
  3316. return this;
  3317. };
  3318. /**
  3319. * Normalize the current Vector3 to a new vector
  3320. * @returns the new Vector3
  3321. */
  3322. Vector3.prototype.normalizeToNew = function () {
  3323. var normalized = new Vector3(0, 0, 0);
  3324. this.normalizeToRef(normalized);
  3325. return normalized;
  3326. };
  3327. /**
  3328. * Normalize the current Vector3 to the reference
  3329. * @param reference define the Vector3 to update
  3330. * @returns the updated Vector3
  3331. */
  3332. Vector3.prototype.normalizeToRef = function (reference) {
  3333. var len = this.length();
  3334. if (len === 0 || len === 1.0) {
  3335. reference.set(this.x, this.y, this.z);
  3336. return reference;
  3337. }
  3338. var scale = 1.0 / len;
  3339. this.scaleToRef(scale, reference);
  3340. return reference;
  3341. };
  3342. /**
  3343. * Creates a new Vector3 copied from the current Vector3
  3344. * @returns the new Vector3
  3345. */
  3346. Vector3.prototype.clone = function () {
  3347. return new Vector3(this.x, this.y, this.z);
  3348. };
  3349. /**
  3350. * Copies the given vector coordinates to the current Vector3 ones
  3351. * @param source defines the source Vector3
  3352. * @returns the current updated Vector3
  3353. */
  3354. Vector3.prototype.copyFrom = function (source) {
  3355. this.x = source.x;
  3356. this.y = source.y;
  3357. this.z = source.z;
  3358. return this;
  3359. };
  3360. /**
  3361. * Copies the given floats to the current Vector3 coordinates
  3362. * @param x defines the x coordinate of the operand
  3363. * @param y defines the y coordinate of the operand
  3364. * @param z defines the z coordinate of the operand
  3365. * @returns the current updated Vector3
  3366. */
  3367. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3368. this.x = x;
  3369. this.y = y;
  3370. this.z = z;
  3371. return this;
  3372. };
  3373. /**
  3374. * Copies the given floats to the current Vector3 coordinates
  3375. * @param x defines the x coordinate of the operand
  3376. * @param y defines the y coordinate of the operand
  3377. * @param z defines the z coordinate of the operand
  3378. * @returns the current updated Vector3
  3379. */
  3380. Vector3.prototype.set = function (x, y, z) {
  3381. return this.copyFromFloats(x, y, z);
  3382. };
  3383. // Statics
  3384. /**
  3385. * Get the clip factor between two vectors
  3386. * @param vector0 defines the first operand
  3387. * @param vector1 defines the second operand
  3388. * @param axis defines the axis to use
  3389. * @param size defines the size along the axis
  3390. * @returns the clip factor
  3391. */
  3392. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3393. var d0 = Vector3.Dot(vector0, axis) - size;
  3394. var d1 = Vector3.Dot(vector1, axis) - size;
  3395. var s = d0 / (d0 - d1);
  3396. return s;
  3397. };
  3398. /**
  3399. * Get angle between two vectors
  3400. * @param vector0 angle between vector0 and vector1
  3401. * @param vector1 angle between vector0 and vector1
  3402. * @param normal direction of the normal
  3403. * @return the angle between vector0 and vector1
  3404. */
  3405. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3406. var v0 = MathTmp.Vector3[1].copyFrom(vector0).normalize();
  3407. var v1 = MathTmp.Vector3[2].copyFrom(vector1).normalize();
  3408. var dot = Vector3.Dot(v0, v1);
  3409. var n = MathTmp.Vector3[3];
  3410. Vector3.CrossToRef(v0, v1, n);
  3411. if (Vector3.Dot(n, normal) > 0) {
  3412. return Math.acos(dot);
  3413. }
  3414. return -Math.acos(dot);
  3415. };
  3416. /**
  3417. * Returns a new Vector3 set from the index "offset" of the given array
  3418. * @param array defines the source array
  3419. * @param offset defines the offset in the source array
  3420. * @returns the new Vector3
  3421. */
  3422. Vector3.FromArray = function (array, offset) {
  3423. if (!offset) {
  3424. offset = 0;
  3425. }
  3426. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3427. };
  3428. /**
  3429. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3430. * This function is deprecated. Use FromArray instead
  3431. * @param array defines the source array
  3432. * @param offset defines the offset in the source array
  3433. * @returns the new Vector3
  3434. */
  3435. Vector3.FromFloatArray = function (array, offset) {
  3436. return Vector3.FromArray(array, offset);
  3437. };
  3438. /**
  3439. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3440. * @param array defines the source array
  3441. * @param offset defines the offset in the source array
  3442. * @param result defines the Vector3 where to store the result
  3443. */
  3444. Vector3.FromArrayToRef = function (array, offset, result) {
  3445. result.x = array[offset];
  3446. result.y = array[offset + 1];
  3447. result.z = array[offset + 2];
  3448. };
  3449. /**
  3450. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3451. * This function is deprecated. Use FromArrayToRef instead.
  3452. * @param array defines the source array
  3453. * @param offset defines the offset in the source array
  3454. * @param result defines the Vector3 where to store the result
  3455. */
  3456. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3457. return Vector3.FromArrayToRef(array, offset, result);
  3458. };
  3459. /**
  3460. * Sets the given vector "result" with the given floats.
  3461. * @param x defines the x coordinate of the source
  3462. * @param y defines the y coordinate of the source
  3463. * @param z defines the z coordinate of the source
  3464. * @param result defines the Vector3 where to store the result
  3465. */
  3466. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3467. result.x = x;
  3468. result.y = y;
  3469. result.z = z;
  3470. };
  3471. /**
  3472. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3473. * @returns a new empty Vector3
  3474. */
  3475. Vector3.Zero = function () {
  3476. return new Vector3(0.0, 0.0, 0.0);
  3477. };
  3478. /**
  3479. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3480. * @returns a new unit Vector3
  3481. */
  3482. Vector3.One = function () {
  3483. return new Vector3(1.0, 1.0, 1.0);
  3484. };
  3485. /**
  3486. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3487. * @returns a new up Vector3
  3488. */
  3489. Vector3.Up = function () {
  3490. return new Vector3(0.0, 1.0, 0.0);
  3491. };
  3492. /**
  3493. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3494. * @returns a new down Vector3
  3495. */
  3496. Vector3.Down = function () {
  3497. return new Vector3(0.0, -1.0, 0.0);
  3498. };
  3499. /**
  3500. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3501. * @returns a new forward Vector3
  3502. */
  3503. Vector3.Forward = function () {
  3504. return new Vector3(0.0, 0.0, 1.0);
  3505. };
  3506. /**
  3507. * Returns a new Vector3 set to (0.0, 0.0, -1.0)
  3508. * @returns a new forward Vector3
  3509. */
  3510. Vector3.Backward = function () {
  3511. return new Vector3(0.0, 0.0, -1.0);
  3512. };
  3513. /**
  3514. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3515. * @returns a new right Vector3
  3516. */
  3517. Vector3.Right = function () {
  3518. return new Vector3(1.0, 0.0, 0.0);
  3519. };
  3520. /**
  3521. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3522. * @returns a new left Vector3
  3523. */
  3524. Vector3.Left = function () {
  3525. return new Vector3(-1.0, 0.0, 0.0);
  3526. };
  3527. /**
  3528. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3529. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3530. * @param vector defines the Vector3 to transform
  3531. * @param transformation defines the transformation matrix
  3532. * @returns the transformed Vector3
  3533. */
  3534. Vector3.TransformCoordinates = function (vector, transformation) {
  3535. var result = Vector3.Zero();
  3536. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3537. return result;
  3538. };
  3539. /**
  3540. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3541. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3542. * @param vector defines the Vector3 to transform
  3543. * @param transformation defines the transformation matrix
  3544. * @param result defines the Vector3 where to store the result
  3545. */
  3546. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3547. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3548. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3549. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3550. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3551. result.x = x / w;
  3552. result.y = y / w;
  3553. result.z = z / w;
  3554. };
  3555. /**
  3556. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3557. * This method computes tranformed coordinates only, not transformed direction vectors
  3558. * @param x define the x coordinate of the source vector
  3559. * @param y define the y coordinate of the source vector
  3560. * @param z define the z coordinate of the source vector
  3561. * @param transformation defines the transformation matrix
  3562. * @param result defines the Vector3 where to store the result
  3563. */
  3564. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3565. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3566. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3567. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3568. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3569. result.x = rx / rw;
  3570. result.y = ry / rw;
  3571. result.z = rz / rw;
  3572. };
  3573. /**
  3574. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3575. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3576. * @param vector defines the Vector3 to transform
  3577. * @param transformation defines the transformation matrix
  3578. * @returns the new Vector3
  3579. */
  3580. Vector3.TransformNormal = function (vector, transformation) {
  3581. var result = Vector3.Zero();
  3582. Vector3.TransformNormalToRef(vector, transformation, result);
  3583. return result;
  3584. };
  3585. /**
  3586. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3587. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3588. * @param vector defines the Vector3 to transform
  3589. * @param transformation defines the transformation matrix
  3590. * @param result defines the Vector3 where to store the result
  3591. */
  3592. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3593. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3594. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3595. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3596. result.x = x;
  3597. result.y = y;
  3598. result.z = z;
  3599. };
  3600. /**
  3601. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3602. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3603. * @param x define the x coordinate of the source vector
  3604. * @param y define the y coordinate of the source vector
  3605. * @param z define the z coordinate of the source vector
  3606. * @param transformation defines the transformation matrix
  3607. * @param result defines the Vector3 where to store the result
  3608. */
  3609. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3610. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3611. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3612. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3613. };
  3614. /**
  3615. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3616. * @param value1 defines the first control point
  3617. * @param value2 defines the second control point
  3618. * @param value3 defines the third control point
  3619. * @param value4 defines the fourth control point
  3620. * @param amount defines the amount on the spline to use
  3621. * @returns the new Vector3
  3622. */
  3623. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3624. var squared = amount * amount;
  3625. var cubed = amount * squared;
  3626. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3627. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3628. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3629. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3630. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3631. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3632. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3633. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3634. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3635. return new Vector3(x, y, z);
  3636. };
  3637. /**
  3638. * 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"
  3639. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3640. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3641. * @param value defines the current value
  3642. * @param min defines the lower range value
  3643. * @param max defines the upper range value
  3644. * @returns the new Vector3
  3645. */
  3646. Vector3.Clamp = function (value, min, max) {
  3647. var x = value.x;
  3648. x = (x > max.x) ? max.x : x;
  3649. x = (x < min.x) ? min.x : x;
  3650. var y = value.y;
  3651. y = (y > max.y) ? max.y : y;
  3652. y = (y < min.y) ? min.y : y;
  3653. var z = value.z;
  3654. z = (z > max.z) ? max.z : z;
  3655. z = (z < min.z) ? min.z : z;
  3656. return new Vector3(x, y, z);
  3657. };
  3658. /**
  3659. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3660. * @param value1 defines the first control point
  3661. * @param tangent1 defines the first tangent vector
  3662. * @param value2 defines the second control point
  3663. * @param tangent2 defines the second tangent vector
  3664. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3665. * @returns the new Vector3
  3666. */
  3667. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3668. var squared = amount * amount;
  3669. var cubed = amount * squared;
  3670. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3671. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3672. var part3 = (cubed - (2.0 * squared)) + amount;
  3673. var part4 = cubed - squared;
  3674. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3675. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3676. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3677. return new Vector3(x, y, z);
  3678. };
  3679. /**
  3680. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3681. * @param start defines the start value
  3682. * @param end defines the end value
  3683. * @param amount max defines amount between both (between 0 and 1)
  3684. * @returns the new Vector3
  3685. */
  3686. Vector3.Lerp = function (start, end, amount) {
  3687. var result = new Vector3(0, 0, 0);
  3688. Vector3.LerpToRef(start, end, amount, result);
  3689. return result;
  3690. };
  3691. /**
  3692. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3693. * @param start defines the start value
  3694. * @param end defines the end value
  3695. * @param amount max defines amount between both (between 0 and 1)
  3696. * @param result defines the Vector3 where to store the result
  3697. */
  3698. Vector3.LerpToRef = function (start, end, amount, result) {
  3699. result.x = start.x + ((end.x - start.x) * amount);
  3700. result.y = start.y + ((end.y - start.y) * amount);
  3701. result.z = start.z + ((end.z - start.z) * amount);
  3702. };
  3703. /**
  3704. * Returns the dot product (float) between the vectors "left" and "right"
  3705. * @param left defines the left operand
  3706. * @param right defines the right operand
  3707. * @returns the dot product
  3708. */
  3709. Vector3.Dot = function (left, right) {
  3710. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3711. };
  3712. /**
  3713. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3714. * The cross product is then orthogonal to both "left" and "right"
  3715. * @param left defines the left operand
  3716. * @param right defines the right operand
  3717. * @returns the cross product
  3718. */
  3719. Vector3.Cross = function (left, right) {
  3720. var result = Vector3.Zero();
  3721. Vector3.CrossToRef(left, right, result);
  3722. return result;
  3723. };
  3724. /**
  3725. * Sets the given vector "result" with the cross product of "left" and "right"
  3726. * The cross product is then orthogonal to both "left" and "right"
  3727. * @param left defines the left operand
  3728. * @param right defines the right operand
  3729. * @param result defines the Vector3 where to store the result
  3730. */
  3731. Vector3.CrossToRef = function (left, right, result) {
  3732. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3733. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3734. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3735. result.copyFrom(MathTmp.Vector3[0]);
  3736. };
  3737. /**
  3738. * Returns a new Vector3 as the normalization of the given vector
  3739. * @param vector defines the Vector3 to normalize
  3740. * @returns the new Vector3
  3741. */
  3742. Vector3.Normalize = function (vector) {
  3743. var result = Vector3.Zero();
  3744. Vector3.NormalizeToRef(vector, result);
  3745. return result;
  3746. };
  3747. /**
  3748. * Sets the given vector "result" with the normalization of the given first vector
  3749. * @param vector defines the Vector3 to normalize
  3750. * @param result defines the Vector3 where to store the result
  3751. */
  3752. Vector3.NormalizeToRef = function (vector, result) {
  3753. result.copyFrom(vector);
  3754. result.normalize();
  3755. };
  3756. /**
  3757. * Project a Vector3 onto screen space
  3758. * @param vector defines the Vector3 to project
  3759. * @param world defines the world matrix to use
  3760. * @param transform defines the transform (view x projection) matrix to use
  3761. * @param viewport defines the screen viewport to use
  3762. * @returns the new Vector3
  3763. */
  3764. Vector3.Project = function (vector, world, transform, viewport) {
  3765. var cw = viewport.width;
  3766. var ch = viewport.height;
  3767. var cx = viewport.x;
  3768. var cy = viewport.y;
  3769. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3770. 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);
  3771. var matrix = MathTmp.Matrix[0];
  3772. world.multiplyToRef(transform, matrix);
  3773. matrix.multiplyToRef(viewportMatrix, matrix);
  3774. return Vector3.TransformCoordinates(vector, matrix);
  3775. };
  3776. /**
  3777. * Unproject from screen space to object space
  3778. * @param source defines the screen space Vector3 to use
  3779. * @param viewportWidth defines the current width of the viewport
  3780. * @param viewportHeight defines the current height of the viewport
  3781. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3782. * @param transform defines the transform (view x projection) matrix to use
  3783. * @returns the new Vector3
  3784. */
  3785. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3786. var matrix = MathTmp.Matrix[0];
  3787. world.multiplyToRef(transform, matrix);
  3788. matrix.invert();
  3789. source.x = source.x / viewportWidth * 2 - 1;
  3790. source.y = -(source.y / viewportHeight * 2 - 1);
  3791. var vector = Vector3.TransformCoordinates(source, matrix);
  3792. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3793. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3794. vector = vector.scale(1.0 / num);
  3795. }
  3796. return vector;
  3797. };
  3798. /**
  3799. * Unproject from screen space to object space
  3800. * @param source defines the screen space Vector3 to use
  3801. * @param viewportWidth defines the current width of the viewport
  3802. * @param viewportHeight defines the current height of the viewport
  3803. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3804. * @param view defines the view matrix to use
  3805. * @param projection defines the projection matrix to use
  3806. * @returns the new Vector3
  3807. */
  3808. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3809. var result = Vector3.Zero();
  3810. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3811. return result;
  3812. };
  3813. /**
  3814. * Unproject from screen space to object space
  3815. * @param source defines the screen space Vector3 to use
  3816. * @param viewportWidth defines the current width of the viewport
  3817. * @param viewportHeight defines the current height of the viewport
  3818. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3819. * @param view defines the view matrix to use
  3820. * @param projection defines the projection matrix to use
  3821. * @param result defines the Vector3 where to store the result
  3822. */
  3823. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3824. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3825. };
  3826. /**
  3827. * Unproject from screen space to object space
  3828. * @param sourceX defines the screen space x coordinate to use
  3829. * @param sourceY defines the screen space y coordinate to use
  3830. * @param sourceZ defines the screen space z coordinate to use
  3831. * @param viewportWidth defines the current width of the viewport
  3832. * @param viewportHeight defines the current height of the viewport
  3833. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3834. * @param view defines the view matrix to use
  3835. * @param projection defines the projection matrix to use
  3836. * @param result defines the Vector3 where to store the result
  3837. */
  3838. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3839. var matrix = MathTmp.Matrix[0];
  3840. world.multiplyToRef(view, matrix);
  3841. matrix.multiplyToRef(projection, matrix);
  3842. matrix.invert();
  3843. var screenSource = MathTmp.Vector3[0];
  3844. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3845. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3846. screenSource.z = 2 * sourceZ - 1.0;
  3847. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3848. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3849. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3850. result.scaleInPlace(1.0 / num);
  3851. }
  3852. };
  3853. /**
  3854. * Gets the minimal coordinate values between two Vector3
  3855. * @param left defines the first operand
  3856. * @param right defines the second operand
  3857. * @returns the new Vector3
  3858. */
  3859. Vector3.Minimize = function (left, right) {
  3860. var min = left.clone();
  3861. min.minimizeInPlace(right);
  3862. return min;
  3863. };
  3864. /**
  3865. * Gets the maximal coordinate values between two Vector3
  3866. * @param left defines the first operand
  3867. * @param right defines the second operand
  3868. * @returns the new Vector3
  3869. */
  3870. Vector3.Maximize = function (left, right) {
  3871. var max = left.clone();
  3872. max.maximizeInPlace(right);
  3873. return max;
  3874. };
  3875. /**
  3876. * Returns the distance between the vectors "value1" and "value2"
  3877. * @param value1 defines the first operand
  3878. * @param value2 defines the second operand
  3879. * @returns the distance
  3880. */
  3881. Vector3.Distance = function (value1, value2) {
  3882. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3883. };
  3884. /**
  3885. * Returns the squared distance between the vectors "value1" and "value2"
  3886. * @param value1 defines the first operand
  3887. * @param value2 defines the second operand
  3888. * @returns the squared distance
  3889. */
  3890. Vector3.DistanceSquared = function (value1, value2) {
  3891. var x = value1.x - value2.x;
  3892. var y = value1.y - value2.y;
  3893. var z = value1.z - value2.z;
  3894. return (x * x) + (y * y) + (z * z);
  3895. };
  3896. /**
  3897. * Returns a new Vector3 located at the center between "value1" and "value2"
  3898. * @param value1 defines the first operand
  3899. * @param value2 defines the second operand
  3900. * @returns the new Vector3
  3901. */
  3902. Vector3.Center = function (value1, value2) {
  3903. var center = value1.add(value2);
  3904. center.scaleInPlace(0.5);
  3905. return center;
  3906. };
  3907. /**
  3908. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3909. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3910. * to something in order to rotate it from its local system to the given target system
  3911. * Note: axis1, axis2 and axis3 are normalized during this operation
  3912. * @param axis1 defines the first axis
  3913. * @param axis2 defines the second axis
  3914. * @param axis3 defines the third axis
  3915. * @returns a new Vector3
  3916. */
  3917. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3918. var rotation = Vector3.Zero();
  3919. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3920. return rotation;
  3921. };
  3922. /**
  3923. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3924. * @param axis1 defines the first axis
  3925. * @param axis2 defines the second axis
  3926. * @param axis3 defines the third axis
  3927. * @param ref defines the Vector3 where to store the result
  3928. */
  3929. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3930. var quat = MathTmp.Quaternion[0];
  3931. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3932. quat.toEulerAnglesToRef(ref);
  3933. };
  3934. return Vector3;
  3935. }());
  3936. BABYLON.Vector3 = Vector3;
  3937. /**
  3938. * Vector4 class created for EulerAngle class conversion to Quaternion
  3939. */
  3940. var Vector4 = /** @class */ (function () {
  3941. /**
  3942. * Creates a Vector4 object from the given floats.
  3943. * @param x x value of the vector
  3944. * @param y y value of the vector
  3945. * @param z z value of the vector
  3946. * @param w w value of the vector
  3947. */
  3948. function Vector4(
  3949. /** x value of the vector */
  3950. x,
  3951. /** y value of the vector */
  3952. y,
  3953. /** z value of the vector */
  3954. z,
  3955. /** w value of the vector */
  3956. w) {
  3957. this.x = x;
  3958. this.y = y;
  3959. this.z = z;
  3960. this.w = w;
  3961. }
  3962. /**
  3963. * Returns the string with the Vector4 coordinates.
  3964. * @returns a string containing all the vector values
  3965. */
  3966. Vector4.prototype.toString = function () {
  3967. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3968. };
  3969. /**
  3970. * Returns the string "Vector4".
  3971. * @returns "Vector4"
  3972. */
  3973. Vector4.prototype.getClassName = function () {
  3974. return "Vector4";
  3975. };
  3976. /**
  3977. * Returns the Vector4 hash code.
  3978. * @returns a unique hash code
  3979. */
  3980. Vector4.prototype.getHashCode = function () {
  3981. var hash = this.x || 0;
  3982. hash = (hash * 397) ^ (this.y || 0);
  3983. hash = (hash * 397) ^ (this.z || 0);
  3984. hash = (hash * 397) ^ (this.w || 0);
  3985. return hash;
  3986. };
  3987. // Operators
  3988. /**
  3989. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3990. * @returns the resulting array
  3991. */
  3992. Vector4.prototype.asArray = function () {
  3993. var result = new Array();
  3994. this.toArray(result, 0);
  3995. return result;
  3996. };
  3997. /**
  3998. * Populates the given array from the given index with the Vector4 coordinates.
  3999. * @param array array to populate
  4000. * @param index index of the array to start at (default: 0)
  4001. * @returns the Vector4.
  4002. */
  4003. Vector4.prototype.toArray = function (array, index) {
  4004. if (index === undefined) {
  4005. index = 0;
  4006. }
  4007. array[index] = this.x;
  4008. array[index + 1] = this.y;
  4009. array[index + 2] = this.z;
  4010. array[index + 3] = this.w;
  4011. return this;
  4012. };
  4013. /**
  4014. * Adds the given vector to the current Vector4.
  4015. * @param otherVector the vector to add
  4016. * @returns the updated Vector4.
  4017. */
  4018. Vector4.prototype.addInPlace = function (otherVector) {
  4019. this.x += otherVector.x;
  4020. this.y += otherVector.y;
  4021. this.z += otherVector.z;
  4022. this.w += otherVector.w;
  4023. return this;
  4024. };
  4025. /**
  4026. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  4027. * @param otherVector the vector to add
  4028. * @returns the resulting vector
  4029. */
  4030. Vector4.prototype.add = function (otherVector) {
  4031. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  4032. };
  4033. /**
  4034. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  4035. * @param otherVector the vector to add
  4036. * @param result the vector to store the result
  4037. * @returns the current Vector4.
  4038. */
  4039. Vector4.prototype.addToRef = function (otherVector, result) {
  4040. result.x = this.x + otherVector.x;
  4041. result.y = this.y + otherVector.y;
  4042. result.z = this.z + otherVector.z;
  4043. result.w = this.w + otherVector.w;
  4044. return this;
  4045. };
  4046. /**
  4047. * Subtract in place the given vector from the current Vector4.
  4048. * @param otherVector the vector to subtract
  4049. * @returns the updated Vector4.
  4050. */
  4051. Vector4.prototype.subtractInPlace = function (otherVector) {
  4052. this.x -= otherVector.x;
  4053. this.y -= otherVector.y;
  4054. this.z -= otherVector.z;
  4055. this.w -= otherVector.w;
  4056. return this;
  4057. };
  4058. /**
  4059. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  4060. * @param otherVector the vector to add
  4061. * @returns the new vector with the result
  4062. */
  4063. Vector4.prototype.subtract = function (otherVector) {
  4064. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  4065. };
  4066. /**
  4067. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  4068. * @param otherVector the vector to subtract
  4069. * @param result the vector to store the result
  4070. * @returns the current Vector4.
  4071. */
  4072. Vector4.prototype.subtractToRef = function (otherVector, result) {
  4073. result.x = this.x - otherVector.x;
  4074. result.y = this.y - otherVector.y;
  4075. result.z = this.z - otherVector.z;
  4076. result.w = this.w - otherVector.w;
  4077. return this;
  4078. };
  4079. /**
  4080. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  4081. */
  4082. /**
  4083. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  4084. * @param x value to subtract
  4085. * @param y value to subtract
  4086. * @param z value to subtract
  4087. * @param w value to subtract
  4088. * @returns new vector containing the result
  4089. */
  4090. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  4091. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  4092. };
  4093. /**
  4094. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  4095. * @param x value to subtract
  4096. * @param y value to subtract
  4097. * @param z value to subtract
  4098. * @param w value to subtract
  4099. * @param result the vector to store the result in
  4100. * @returns the current Vector4.
  4101. */
  4102. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  4103. result.x = this.x - x;
  4104. result.y = this.y - y;
  4105. result.z = this.z - z;
  4106. result.w = this.w - w;
  4107. return this;
  4108. };
  4109. /**
  4110. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  4111. * @returns a new vector with the negated values
  4112. */
  4113. Vector4.prototype.negate = function () {
  4114. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  4115. };
  4116. /**
  4117. * Multiplies the current Vector4 coordinates by scale (float).
  4118. * @param scale the number to scale with
  4119. * @returns the updated Vector4.
  4120. */
  4121. Vector4.prototype.scaleInPlace = function (scale) {
  4122. this.x *= scale;
  4123. this.y *= scale;
  4124. this.z *= scale;
  4125. this.w *= scale;
  4126. return this;
  4127. };
  4128. /**
  4129. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  4130. * @param scale the number to scale with
  4131. * @returns a new vector with the result
  4132. */
  4133. Vector4.prototype.scale = function (scale) {
  4134. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  4135. };
  4136. /**
  4137. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  4138. * @param scale the number to scale with
  4139. * @param result a vector to store the result in
  4140. * @returns the current Vector4.
  4141. */
  4142. Vector4.prototype.scaleToRef = function (scale, result) {
  4143. result.x = this.x * scale;
  4144. result.y = this.y * scale;
  4145. result.z = this.z * scale;
  4146. result.w = this.w * scale;
  4147. return this;
  4148. };
  4149. /**
  4150. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  4151. * @param scale defines the scale factor
  4152. * @param result defines the Vector4 object where to store the result
  4153. * @returns the unmodified current Vector4
  4154. */
  4155. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  4156. result.x += this.x * scale;
  4157. result.y += this.y * scale;
  4158. result.z += this.z * scale;
  4159. result.w += this.w * scale;
  4160. return this;
  4161. };
  4162. /**
  4163. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  4164. * @param otherVector the vector to compare against
  4165. * @returns true if they are equal
  4166. */
  4167. Vector4.prototype.equals = function (otherVector) {
  4168. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  4169. };
  4170. /**
  4171. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  4172. * @param otherVector vector to compare against
  4173. * @param epsilon (Default: very small number)
  4174. * @returns true if they are equal
  4175. */
  4176. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4177. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4178. return otherVector
  4179. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  4180. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  4181. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  4182. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  4183. };
  4184. /**
  4185. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  4186. * @param x x value to compare against
  4187. * @param y y value to compare against
  4188. * @param z z value to compare against
  4189. * @param w w value to compare against
  4190. * @returns true if equal
  4191. */
  4192. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4193. return this.x === x && this.y === y && this.z === z && this.w === w;
  4194. };
  4195. /**
  4196. * Multiplies in place the current Vector4 by the given one.
  4197. * @param otherVector vector to multiple with
  4198. * @returns the updated Vector4.
  4199. */
  4200. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4201. this.x *= otherVector.x;
  4202. this.y *= otherVector.y;
  4203. this.z *= otherVector.z;
  4204. this.w *= otherVector.w;
  4205. return this;
  4206. };
  4207. /**
  4208. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4209. * @param otherVector vector to multiple with
  4210. * @returns resulting new vector
  4211. */
  4212. Vector4.prototype.multiply = function (otherVector) {
  4213. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4214. };
  4215. /**
  4216. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4217. * @param otherVector vector to multiple with
  4218. * @param result vector to store the result
  4219. * @returns the current Vector4.
  4220. */
  4221. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4222. result.x = this.x * otherVector.x;
  4223. result.y = this.y * otherVector.y;
  4224. result.z = this.z * otherVector.z;
  4225. result.w = this.w * otherVector.w;
  4226. return this;
  4227. };
  4228. /**
  4229. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4230. * @param x x value multiply with
  4231. * @param y y value multiply with
  4232. * @param z z value multiply with
  4233. * @param w w value multiply with
  4234. * @returns resulting new vector
  4235. */
  4236. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4237. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4238. };
  4239. /**
  4240. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4241. * @param otherVector vector to devide with
  4242. * @returns resulting new vector
  4243. */
  4244. Vector4.prototype.divide = function (otherVector) {
  4245. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4246. };
  4247. /**
  4248. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4249. * @param otherVector vector to devide with
  4250. * @param result vector to store the result
  4251. * @returns the current Vector4.
  4252. */
  4253. Vector4.prototype.divideToRef = function (otherVector, result) {
  4254. result.x = this.x / otherVector.x;
  4255. result.y = this.y / otherVector.y;
  4256. result.z = this.z / otherVector.z;
  4257. result.w = this.w / otherVector.w;
  4258. return this;
  4259. };
  4260. /**
  4261. * Divides the current Vector3 coordinates by the given ones.
  4262. * @param otherVector vector to devide with
  4263. * @returns the updated Vector3.
  4264. */
  4265. Vector4.prototype.divideInPlace = function (otherVector) {
  4266. return this.divideToRef(otherVector, this);
  4267. };
  4268. /**
  4269. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4270. * @param other defines the second operand
  4271. * @returns the current updated Vector4
  4272. */
  4273. Vector4.prototype.minimizeInPlace = function (other) {
  4274. if (other.x < this.x) {
  4275. this.x = other.x;
  4276. }
  4277. if (other.y < this.y) {
  4278. this.y = other.y;
  4279. }
  4280. if (other.z < this.z) {
  4281. this.z = other.z;
  4282. }
  4283. if (other.w < this.w) {
  4284. this.w = other.w;
  4285. }
  4286. return this;
  4287. };
  4288. /**
  4289. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4290. * @param other defines the second operand
  4291. * @returns the current updated Vector4
  4292. */
  4293. Vector4.prototype.maximizeInPlace = function (other) {
  4294. if (other.x > this.x) {
  4295. this.x = other.x;
  4296. }
  4297. if (other.y > this.y) {
  4298. this.y = other.y;
  4299. }
  4300. if (other.z > this.z) {
  4301. this.z = other.z;
  4302. }
  4303. if (other.w > this.w) {
  4304. this.w = other.w;
  4305. }
  4306. return this;
  4307. };
  4308. /**
  4309. * Gets a new Vector4 from current Vector4 floored values
  4310. * @returns a new Vector4
  4311. */
  4312. Vector4.prototype.floor = function () {
  4313. return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
  4314. };
  4315. /**
  4316. * Gets a new Vector4 from current Vector3 floored values
  4317. * @returns a new Vector4
  4318. */
  4319. Vector4.prototype.fract = function () {
  4320. 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));
  4321. };
  4322. // Properties
  4323. /**
  4324. * Returns the Vector4 length (float).
  4325. * @returns the length
  4326. */
  4327. Vector4.prototype.length = function () {
  4328. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4329. };
  4330. /**
  4331. * Returns the Vector4 squared length (float).
  4332. * @returns the length squared
  4333. */
  4334. Vector4.prototype.lengthSquared = function () {
  4335. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4336. };
  4337. // Methods
  4338. /**
  4339. * Normalizes in place the Vector4.
  4340. * @returns the updated Vector4.
  4341. */
  4342. Vector4.prototype.normalize = function () {
  4343. var len = this.length();
  4344. if (len === 0) {
  4345. return this;
  4346. }
  4347. var num = 1.0 / len;
  4348. this.x *= num;
  4349. this.y *= num;
  4350. this.z *= num;
  4351. this.w *= num;
  4352. return this;
  4353. };
  4354. /**
  4355. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4356. * @returns this converted to a new vector3
  4357. */
  4358. Vector4.prototype.toVector3 = function () {
  4359. return new Vector3(this.x, this.y, this.z);
  4360. };
  4361. /**
  4362. * Returns a new Vector4 copied from the current one.
  4363. * @returns the new cloned vector
  4364. */
  4365. Vector4.prototype.clone = function () {
  4366. return new Vector4(this.x, this.y, this.z, this.w);
  4367. };
  4368. /**
  4369. * Updates the current Vector4 with the given one coordinates.
  4370. * @param source the source vector to copy from
  4371. * @returns the updated Vector4.
  4372. */
  4373. Vector4.prototype.copyFrom = function (source) {
  4374. this.x = source.x;
  4375. this.y = source.y;
  4376. this.z = source.z;
  4377. this.w = source.w;
  4378. return this;
  4379. };
  4380. /**
  4381. * Updates the current Vector4 coordinates with the given floats.
  4382. * @param x float to copy from
  4383. * @param y float to copy from
  4384. * @param z float to copy from
  4385. * @param w float to copy from
  4386. * @returns the updated Vector4.
  4387. */
  4388. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4389. this.x = x;
  4390. this.y = y;
  4391. this.z = z;
  4392. this.w = w;
  4393. return this;
  4394. };
  4395. /**
  4396. * Updates the current Vector4 coordinates with the given floats.
  4397. * @param x float to set from
  4398. * @param y float to set from
  4399. * @param z float to set from
  4400. * @param w float to set from
  4401. * @returns the updated Vector4.
  4402. */
  4403. Vector4.prototype.set = function (x, y, z, w) {
  4404. return this.copyFromFloats(x, y, z, w);
  4405. };
  4406. // Statics
  4407. /**
  4408. * Returns a new Vector4 set from the starting index of the given array.
  4409. * @param array the array to pull values from
  4410. * @param offset the offset into the array to start at
  4411. * @returns the new vector
  4412. */
  4413. Vector4.FromArray = function (array, offset) {
  4414. if (!offset) {
  4415. offset = 0;
  4416. }
  4417. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4418. };
  4419. /**
  4420. * Updates the given vector "result" from the starting index of the given array.
  4421. * @param array the array to pull values from
  4422. * @param offset the offset into the array to start at
  4423. * @param result the vector to store the result in
  4424. */
  4425. Vector4.FromArrayToRef = function (array, offset, result) {
  4426. result.x = array[offset];
  4427. result.y = array[offset + 1];
  4428. result.z = array[offset + 2];
  4429. result.w = array[offset + 3];
  4430. };
  4431. /**
  4432. * Updates the given vector "result" from the starting index of the given Float32Array.
  4433. * @param array the array to pull values from
  4434. * @param offset the offset into the array to start at
  4435. * @param result the vector to store the result in
  4436. */
  4437. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4438. Vector4.FromArrayToRef(array, offset, result);
  4439. };
  4440. /**
  4441. * Updates the given vector "result" coordinates from the given floats.
  4442. * @param x float to set from
  4443. * @param y float to set from
  4444. * @param z float to set from
  4445. * @param w float to set from
  4446. * @param result the vector to the floats in
  4447. */
  4448. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4449. result.x = x;
  4450. result.y = y;
  4451. result.z = z;
  4452. result.w = w;
  4453. };
  4454. /**
  4455. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4456. * @returns the new vector
  4457. */
  4458. Vector4.Zero = function () {
  4459. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4460. };
  4461. /**
  4462. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4463. * @returns the new vector
  4464. */
  4465. Vector4.One = function () {
  4466. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4467. };
  4468. /**
  4469. * Returns a new normalized Vector4 from the given one.
  4470. * @param vector the vector to normalize
  4471. * @returns the vector
  4472. */
  4473. Vector4.Normalize = function (vector) {
  4474. var result = Vector4.Zero();
  4475. Vector4.NormalizeToRef(vector, result);
  4476. return result;
  4477. };
  4478. /**
  4479. * Updates the given vector "result" from the normalization of the given one.
  4480. * @param vector the vector to normalize
  4481. * @param result the vector to store the result in
  4482. */
  4483. Vector4.NormalizeToRef = function (vector, result) {
  4484. result.copyFrom(vector);
  4485. result.normalize();
  4486. };
  4487. /**
  4488. * Returns a vector with the minimum values from the left and right vectors
  4489. * @param left left vector to minimize
  4490. * @param right right vector to minimize
  4491. * @returns a new vector with the minimum of the left and right vector values
  4492. */
  4493. Vector4.Minimize = function (left, right) {
  4494. var min = left.clone();
  4495. min.minimizeInPlace(right);
  4496. return min;
  4497. };
  4498. /**
  4499. * Returns a vector with the maximum values from the left and right vectors
  4500. * @param left left vector to maximize
  4501. * @param right right vector to maximize
  4502. * @returns a new vector with the maximum of the left and right vector values
  4503. */
  4504. Vector4.Maximize = function (left, right) {
  4505. var max = left.clone();
  4506. max.maximizeInPlace(right);
  4507. return max;
  4508. };
  4509. /**
  4510. * Returns the distance (float) between the vectors "value1" and "value2".
  4511. * @param value1 value to calulate the distance between
  4512. * @param value2 value to calulate the distance between
  4513. * @return the distance between the two vectors
  4514. */
  4515. Vector4.Distance = function (value1, value2) {
  4516. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4517. };
  4518. /**
  4519. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4520. * @param value1 value to calulate the distance between
  4521. * @param value2 value to calulate the distance between
  4522. * @return the distance between the two vectors squared
  4523. */
  4524. Vector4.DistanceSquared = function (value1, value2) {
  4525. var x = value1.x - value2.x;
  4526. var y = value1.y - value2.y;
  4527. var z = value1.z - value2.z;
  4528. var w = value1.w - value2.w;
  4529. return (x * x) + (y * y) + (z * z) + (w * w);
  4530. };
  4531. /**
  4532. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4533. * @param value1 value to calulate the center between
  4534. * @param value2 value to calulate the center between
  4535. * @return the center between the two vectors
  4536. */
  4537. Vector4.Center = function (value1, value2) {
  4538. var center = value1.add(value2);
  4539. center.scaleInPlace(0.5);
  4540. return center;
  4541. };
  4542. /**
  4543. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4544. * This methods computes transformed normalized direction vectors only.
  4545. * @param vector the vector to transform
  4546. * @param transformation the transformation matrix to apply
  4547. * @returns the new vector
  4548. */
  4549. Vector4.TransformNormal = function (vector, transformation) {
  4550. var result = Vector4.Zero();
  4551. Vector4.TransformNormalToRef(vector, transformation, result);
  4552. return result;
  4553. };
  4554. /**
  4555. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4556. * This methods computes transformed normalized direction vectors only.
  4557. * @param vector the vector to transform
  4558. * @param transformation the transformation matrix to apply
  4559. * @param result the vector to store the result in
  4560. */
  4561. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4562. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4563. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4564. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4565. result.x = x;
  4566. result.y = y;
  4567. result.z = z;
  4568. result.w = vector.w;
  4569. };
  4570. /**
  4571. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4572. * This methods computes transformed normalized direction vectors only.
  4573. * @param x value to transform
  4574. * @param y value to transform
  4575. * @param z value to transform
  4576. * @param w value to transform
  4577. * @param transformation the transformation matrix to apply
  4578. * @param result the vector to store the results in
  4579. */
  4580. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4581. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4582. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4583. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4584. result.w = w;
  4585. };
  4586. return Vector4;
  4587. }());
  4588. BABYLON.Vector4 = Vector4;
  4589. /**
  4590. * Size containing widht and height
  4591. */
  4592. var Size = /** @class */ (function () {
  4593. /**
  4594. * Creates a Size object from the given width and height (floats).
  4595. * @param width width of the new size
  4596. * @param height height of the new size
  4597. */
  4598. function Size(width, height) {
  4599. this.width = width;
  4600. this.height = height;
  4601. }
  4602. /**
  4603. * Returns a string with the Size width and height
  4604. * @returns a string with the Size width and height
  4605. */
  4606. Size.prototype.toString = function () {
  4607. return "{W: " + this.width + ", H: " + this.height + "}";
  4608. };
  4609. /**
  4610. * "Size"
  4611. * @returns the string "Size"
  4612. */
  4613. Size.prototype.getClassName = function () {
  4614. return "Size";
  4615. };
  4616. /**
  4617. * Returns the Size hash code.
  4618. * @returns a hash code for a unique width and height
  4619. */
  4620. Size.prototype.getHashCode = function () {
  4621. var hash = this.width || 0;
  4622. hash = (hash * 397) ^ (this.height || 0);
  4623. return hash;
  4624. };
  4625. /**
  4626. * Updates the current size from the given one.
  4627. * @param src the given size
  4628. */
  4629. Size.prototype.copyFrom = function (src) {
  4630. this.width = src.width;
  4631. this.height = src.height;
  4632. };
  4633. /**
  4634. * Updates in place the current Size from the given floats.
  4635. * @param width width of the new size
  4636. * @param height height of the new size
  4637. * @returns the updated Size.
  4638. */
  4639. Size.prototype.copyFromFloats = function (width, height) {
  4640. this.width = width;
  4641. this.height = height;
  4642. return this;
  4643. };
  4644. /**
  4645. * Updates in place the current Size from the given floats.
  4646. * @param width width to set
  4647. * @param height height to set
  4648. * @returns the updated Size.
  4649. */
  4650. Size.prototype.set = function (width, height) {
  4651. return this.copyFromFloats(width, height);
  4652. };
  4653. /**
  4654. * Multiplies the width and height by numbers
  4655. * @param w factor to multiple the width by
  4656. * @param h factor to multiple the height by
  4657. * @returns a new Size set with the multiplication result of the current Size and the given floats.
  4658. */
  4659. Size.prototype.multiplyByFloats = function (w, h) {
  4660. return new Size(this.width * w, this.height * h);
  4661. };
  4662. /**
  4663. * Clones the size
  4664. * @returns a new Size copied from the given one.
  4665. */
  4666. Size.prototype.clone = function () {
  4667. return new Size(this.width, this.height);
  4668. };
  4669. /**
  4670. * True if the current Size and the given one width and height are strictly equal.
  4671. * @param other the other size to compare against
  4672. * @returns True if the current Size and the given one width and height are strictly equal.
  4673. */
  4674. Size.prototype.equals = function (other) {
  4675. if (!other) {
  4676. return false;
  4677. }
  4678. return (this.width === other.width) && (this.height === other.height);
  4679. };
  4680. Object.defineProperty(Size.prototype, "surface", {
  4681. /**
  4682. * The surface of the Size : width * height (float).
  4683. */
  4684. get: function () {
  4685. return this.width * this.height;
  4686. },
  4687. enumerable: true,
  4688. configurable: true
  4689. });
  4690. /**
  4691. * Create a new size of zero
  4692. * @returns a new Size set to (0.0, 0.0)
  4693. */
  4694. Size.Zero = function () {
  4695. return new Size(0.0, 0.0);
  4696. };
  4697. /**
  4698. * Sums the width and height of two sizes
  4699. * @param otherSize size to add to this size
  4700. * @returns a new Size set as the addition result of the current Size and the given one.
  4701. */
  4702. Size.prototype.add = function (otherSize) {
  4703. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4704. return r;
  4705. };
  4706. /**
  4707. * Subtracts the width and height of two
  4708. * @param otherSize size to subtract to this size
  4709. * @returns a new Size set as the subtraction result of the given one from the current Size.
  4710. */
  4711. Size.prototype.subtract = function (otherSize) {
  4712. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4713. return r;
  4714. };
  4715. /**
  4716. * Creates a new Size set at the linear interpolation "amount" between "start" and "end"
  4717. * @param start starting size to lerp between
  4718. * @param end end size to lerp between
  4719. * @param amount amount to lerp between the start and end values
  4720. * @returns a new Size set at the linear interpolation "amount" between "start" and "end"
  4721. */
  4722. Size.Lerp = function (start, end, amount) {
  4723. var w = start.width + ((end.width - start.width) * amount);
  4724. var h = start.height + ((end.height - start.height) * amount);
  4725. return new Size(w, h);
  4726. };
  4727. return Size;
  4728. }());
  4729. BABYLON.Size = Size;
  4730. /**
  4731. * Class used to store quaternion data
  4732. * @see https://en.wikipedia.org/wiki/Quaternion
  4733. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4734. */
  4735. var Quaternion = /** @class */ (function () {
  4736. /**
  4737. * Creates a new Quaternion from the given floats
  4738. * @param x defines the first component (0 by default)
  4739. * @param y defines the second component (0 by default)
  4740. * @param z defines the third component (0 by default)
  4741. * @param w defines the fourth component (1.0 by default)
  4742. */
  4743. function Quaternion(
  4744. /** defines the first component (0 by default) */
  4745. x,
  4746. /** defines the second component (0 by default) */
  4747. y,
  4748. /** defines the third component (0 by default) */
  4749. z,
  4750. /** defines the fourth component (1.0 by default) */
  4751. w) {
  4752. if (x === void 0) { x = 0.0; }
  4753. if (y === void 0) { y = 0.0; }
  4754. if (z === void 0) { z = 0.0; }
  4755. if (w === void 0) { w = 1.0; }
  4756. this.x = x;
  4757. this.y = y;
  4758. this.z = z;
  4759. this.w = w;
  4760. }
  4761. /**
  4762. * Gets a string representation for the current quaternion
  4763. * @returns a string with the Quaternion coordinates
  4764. */
  4765. Quaternion.prototype.toString = function () {
  4766. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4767. };
  4768. /**
  4769. * Gets the class name of the quaternion
  4770. * @returns the string "Quaternion"
  4771. */
  4772. Quaternion.prototype.getClassName = function () {
  4773. return "Quaternion";
  4774. };
  4775. /**
  4776. * Gets a hash code for this quaternion
  4777. * @returns the quaternion hash code
  4778. */
  4779. Quaternion.prototype.getHashCode = function () {
  4780. var hash = this.x || 0;
  4781. hash = (hash * 397) ^ (this.y || 0);
  4782. hash = (hash * 397) ^ (this.z || 0);
  4783. hash = (hash * 397) ^ (this.w || 0);
  4784. return hash;
  4785. };
  4786. /**
  4787. * Copy the quaternion to an array
  4788. * @returns a new array populated with 4 elements from the quaternion coordinates
  4789. */
  4790. Quaternion.prototype.asArray = function () {
  4791. return [this.x, this.y, this.z, this.w];
  4792. };
  4793. /**
  4794. * Check if two quaternions are equals
  4795. * @param otherQuaternion defines the second operand
  4796. * @return true if the current quaternion and the given one coordinates are strictly equals
  4797. */
  4798. Quaternion.prototype.equals = function (otherQuaternion) {
  4799. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4800. };
  4801. /**
  4802. * Clone the current quaternion
  4803. * @returns a new quaternion copied from the current one
  4804. */
  4805. Quaternion.prototype.clone = function () {
  4806. return new Quaternion(this.x, this.y, this.z, this.w);
  4807. };
  4808. /**
  4809. * Copy a quaternion to the current one
  4810. * @param other defines the other quaternion
  4811. * @returns the updated current quaternion
  4812. */
  4813. Quaternion.prototype.copyFrom = function (other) {
  4814. this.x = other.x;
  4815. this.y = other.y;
  4816. this.z = other.z;
  4817. this.w = other.w;
  4818. return this;
  4819. };
  4820. /**
  4821. * Updates the current quaternion with the given float coordinates
  4822. * @param x defines the x coordinate
  4823. * @param y defines the y coordinate
  4824. * @param z defines the z coordinate
  4825. * @param w defines the w coordinate
  4826. * @returns the updated current quaternion
  4827. */
  4828. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4829. this.x = x;
  4830. this.y = y;
  4831. this.z = z;
  4832. this.w = w;
  4833. return this;
  4834. };
  4835. /**
  4836. * Updates the current quaternion from the given float coordinates
  4837. * @param x defines the x coordinate
  4838. * @param y defines the y coordinate
  4839. * @param z defines the z coordinate
  4840. * @param w defines the w coordinate
  4841. * @returns the updated current quaternion
  4842. */
  4843. Quaternion.prototype.set = function (x, y, z, w) {
  4844. return this.copyFromFloats(x, y, z, w);
  4845. };
  4846. /**
  4847. * Adds two quaternions
  4848. * @param other defines the second operand
  4849. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4850. */
  4851. Quaternion.prototype.add = function (other) {
  4852. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4853. };
  4854. /**
  4855. * Add a quaternion to the current one
  4856. * @param other defines the quaternion to add
  4857. * @returns the current quaternion
  4858. */
  4859. Quaternion.prototype.addInPlace = function (other) {
  4860. this.x += other.x;
  4861. this.y += other.y;
  4862. this.z += other.z;
  4863. this.w += other.w;
  4864. return this;
  4865. };
  4866. /**
  4867. * Subtract two quaternions
  4868. * @param other defines the second operand
  4869. * @returns a new quaternion as the subtraction result of the given one from the current one
  4870. */
  4871. Quaternion.prototype.subtract = function (other) {
  4872. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4873. };
  4874. /**
  4875. * Multiplies the current quaternion by a scale factor
  4876. * @param value defines the scale factor
  4877. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4878. */
  4879. Quaternion.prototype.scale = function (value) {
  4880. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4881. };
  4882. /**
  4883. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4884. * @param scale defines the scale factor
  4885. * @param result defines the Quaternion object where to store the result
  4886. * @returns the unmodified current quaternion
  4887. */
  4888. Quaternion.prototype.scaleToRef = function (scale, result) {
  4889. result.x = this.x * scale;
  4890. result.y = this.y * scale;
  4891. result.z = this.z * scale;
  4892. result.w = this.w * scale;
  4893. return this;
  4894. };
  4895. /**
  4896. * Multiplies in place the current quaternion by a scale factor
  4897. * @param value defines the scale factor
  4898. * @returns the current modified quaternion
  4899. */
  4900. Quaternion.prototype.scaleInPlace = function (value) {
  4901. this.x *= value;
  4902. this.y *= value;
  4903. this.z *= value;
  4904. this.w *= value;
  4905. return this;
  4906. };
  4907. /**
  4908. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4909. * @param scale defines the scale factor
  4910. * @param result defines the Quaternion object where to store the result
  4911. * @returns the unmodified current quaternion
  4912. */
  4913. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4914. result.x += this.x * scale;
  4915. result.y += this.y * scale;
  4916. result.z += this.z * scale;
  4917. result.w += this.w * scale;
  4918. return this;
  4919. };
  4920. /**
  4921. * Multiplies two quaternions
  4922. * @param q1 defines the second operand
  4923. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4924. */
  4925. Quaternion.prototype.multiply = function (q1) {
  4926. var result = new Quaternion(0, 0, 0, 1.0);
  4927. this.multiplyToRef(q1, result);
  4928. return result;
  4929. };
  4930. /**
  4931. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4932. * @param q1 defines the second operand
  4933. * @param result defines the target quaternion
  4934. * @returns the current quaternion
  4935. */
  4936. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4937. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4938. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4939. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4940. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4941. result.copyFromFloats(x, y, z, w);
  4942. return this;
  4943. };
  4944. /**
  4945. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4946. * @param q1 defines the second operand
  4947. * @returns the currentupdated quaternion
  4948. */
  4949. Quaternion.prototype.multiplyInPlace = function (q1) {
  4950. this.multiplyToRef(q1, this);
  4951. return this;
  4952. };
  4953. /**
  4954. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4955. * @param ref defines the target quaternion
  4956. * @returns the current quaternion
  4957. */
  4958. Quaternion.prototype.conjugateToRef = function (ref) {
  4959. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4960. return this;
  4961. };
  4962. /**
  4963. * Conjugates in place (1-q) the current quaternion
  4964. * @returns the current updated quaternion
  4965. */
  4966. Quaternion.prototype.conjugateInPlace = function () {
  4967. this.x *= -1;
  4968. this.y *= -1;
  4969. this.z *= -1;
  4970. return this;
  4971. };
  4972. /**
  4973. * Conjugates in place (1-q) the current quaternion
  4974. * @returns a new quaternion
  4975. */
  4976. Quaternion.prototype.conjugate = function () {
  4977. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4978. return result;
  4979. };
  4980. /**
  4981. * Gets length of current quaternion
  4982. * @returns the quaternion length (float)
  4983. */
  4984. Quaternion.prototype.length = function () {
  4985. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4986. };
  4987. /**
  4988. * Normalize in place the current quaternion
  4989. * @returns the current updated quaternion
  4990. */
  4991. Quaternion.prototype.normalize = function () {
  4992. var length = 1.0 / this.length();
  4993. this.x *= length;
  4994. this.y *= length;
  4995. this.z *= length;
  4996. this.w *= length;
  4997. return this;
  4998. };
  4999. /**
  5000. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  5001. * @param order is a reserved parameter and is ignore for now
  5002. * @returns a new Vector3 containing the Euler angles
  5003. */
  5004. Quaternion.prototype.toEulerAngles = function (order) {
  5005. if (order === void 0) { order = "YZX"; }
  5006. var result = Vector3.Zero();
  5007. this.toEulerAnglesToRef(result, order);
  5008. return result;
  5009. };
  5010. /**
  5011. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  5012. * @param result defines the vector which will be filled with the Euler angles
  5013. * @param order is a reserved parameter and is ignore for now
  5014. * @returns the current unchanged quaternion
  5015. */
  5016. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  5017. if (order === void 0) { order = "YZX"; }
  5018. var qz = this.z;
  5019. var qx = this.x;
  5020. var qy = this.y;
  5021. var qw = this.w;
  5022. var sqw = qw * qw;
  5023. var sqz = qz * qz;
  5024. var sqx = qx * qx;
  5025. var sqy = qy * qy;
  5026. var zAxisY = qy * qz - qx * qw;
  5027. var limit = .4999999;
  5028. if (zAxisY < -limit) {
  5029. result.y = 2 * Math.atan2(qy, qw);
  5030. result.x = Math.PI / 2;
  5031. result.z = 0;
  5032. }
  5033. else if (zAxisY > limit) {
  5034. result.y = 2 * Math.atan2(qy, qw);
  5035. result.x = -Math.PI / 2;
  5036. result.z = 0;
  5037. }
  5038. else {
  5039. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  5040. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  5041. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  5042. }
  5043. return this;
  5044. };
  5045. /**
  5046. * Updates the given rotation matrix with the current quaternion values
  5047. * @param result defines the target matrix
  5048. * @returns the current unchanged quaternion
  5049. */
  5050. Quaternion.prototype.toRotationMatrix = function (result) {
  5051. var xx = this.x * this.x;
  5052. var yy = this.y * this.y;
  5053. var zz = this.z * this.z;
  5054. var xy = this.x * this.y;
  5055. var zw = this.z * this.w;
  5056. var zx = this.z * this.x;
  5057. var yw = this.y * this.w;
  5058. var yz = this.y * this.z;
  5059. var xw = this.x * this.w;
  5060. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5061. result.m[1] = 2.0 * (xy + zw);
  5062. result.m[2] = 2.0 * (zx - yw);
  5063. result.m[3] = 0;
  5064. result.m[4] = 2.0 * (xy - zw);
  5065. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5066. result.m[6] = 2.0 * (yz + xw);
  5067. result.m[7] = 0;
  5068. result.m[8] = 2.0 * (zx + yw);
  5069. result.m[9] = 2.0 * (yz - xw);
  5070. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5071. result.m[11] = 0;
  5072. result.m[12] = 0;
  5073. result.m[13] = 0;
  5074. result.m[14] = 0;
  5075. result.m[15] = 1.0;
  5076. result._markAsUpdated();
  5077. return this;
  5078. };
  5079. /**
  5080. * Updates the current quaternion from the given rotation matrix values
  5081. * @param matrix defines the source matrix
  5082. * @returns the current updated quaternion
  5083. */
  5084. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  5085. Quaternion.FromRotationMatrixToRef(matrix, this);
  5086. return this;
  5087. };
  5088. // Statics
  5089. /**
  5090. * Creates a new quaternion from a rotation matrix
  5091. * @param matrix defines the source matrix
  5092. * @returns a new quaternion created from the given rotation matrix values
  5093. */
  5094. Quaternion.FromRotationMatrix = function (matrix) {
  5095. var result = new Quaternion();
  5096. Quaternion.FromRotationMatrixToRef(matrix, result);
  5097. return result;
  5098. };
  5099. /**
  5100. * Updates the given quaternion with the given rotation matrix values
  5101. * @param matrix defines the source matrix
  5102. * @param result defines the target quaternion
  5103. */
  5104. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  5105. var data = matrix.m;
  5106. var m11 = data[0], m12 = data[4], m13 = data[8];
  5107. var m21 = data[1], m22 = data[5], m23 = data[9];
  5108. var m31 = data[2], m32 = data[6], m33 = data[10];
  5109. var trace = m11 + m22 + m33;
  5110. var s;
  5111. if (trace > 0) {
  5112. s = 0.5 / Math.sqrt(trace + 1.0);
  5113. result.w = 0.25 / s;
  5114. result.x = (m32 - m23) * s;
  5115. result.y = (m13 - m31) * s;
  5116. result.z = (m21 - m12) * s;
  5117. }
  5118. else if (m11 > m22 && m11 > m33) {
  5119. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  5120. result.w = (m32 - m23) / s;
  5121. result.x = 0.25 * s;
  5122. result.y = (m12 + m21) / s;
  5123. result.z = (m13 + m31) / s;
  5124. }
  5125. else if (m22 > m33) {
  5126. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  5127. result.w = (m13 - m31) / s;
  5128. result.x = (m12 + m21) / s;
  5129. result.y = 0.25 * s;
  5130. result.z = (m23 + m32) / s;
  5131. }
  5132. else {
  5133. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  5134. result.w = (m21 - m12) / s;
  5135. result.x = (m13 + m31) / s;
  5136. result.y = (m23 + m32) / s;
  5137. result.z = 0.25 * s;
  5138. }
  5139. };
  5140. /**
  5141. * Returns the dot product (float) between the quaternions "left" and "right"
  5142. * @param left defines the left operand
  5143. * @param right defines the right operand
  5144. * @returns the dot product
  5145. */
  5146. Quaternion.Dot = function (left, right) {
  5147. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  5148. };
  5149. /**
  5150. * Checks if the two quaternions are close to each other
  5151. * @param quat0 defines the first quaternion to check
  5152. * @param quat1 defines the second quaternion to check
  5153. * @returns true if the two quaternions are close to each other
  5154. */
  5155. Quaternion.AreClose = function (quat0, quat1) {
  5156. var dot = Quaternion.Dot(quat0, quat1);
  5157. return dot >= 0;
  5158. };
  5159. /**
  5160. * Creates an empty quaternion
  5161. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  5162. */
  5163. Quaternion.Zero = function () {
  5164. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  5165. };
  5166. /**
  5167. * Inverse a given quaternion
  5168. * @param q defines the source quaternion
  5169. * @returns a new quaternion as the inverted current quaternion
  5170. */
  5171. Quaternion.Inverse = function (q) {
  5172. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  5173. };
  5174. /**
  5175. * Creates an identity quaternion
  5176. * @returns the identity quaternion
  5177. */
  5178. Quaternion.Identity = function () {
  5179. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  5180. };
  5181. /**
  5182. * Gets a boolean indicating if the given quaternion is identity
  5183. * @param quaternion defines the quaternion to check
  5184. * @returns true if the quaternion is identity
  5185. */
  5186. Quaternion.IsIdentity = function (quaternion) {
  5187. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  5188. };
  5189. /**
  5190. * Creates a quaternion from a rotation around an axis
  5191. * @param axis defines the axis to use
  5192. * @param angle defines the angle to use
  5193. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  5194. */
  5195. Quaternion.RotationAxis = function (axis, angle) {
  5196. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  5197. };
  5198. /**
  5199. * Creates a rotation around an axis and stores it into the given quaternion
  5200. * @param axis defines the axis to use
  5201. * @param angle defines the angle to use
  5202. * @param result defines the target quaternion
  5203. * @returns the target quaternion
  5204. */
  5205. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  5206. var sin = Math.sin(angle / 2);
  5207. axis.normalize();
  5208. result.w = Math.cos(angle / 2);
  5209. result.x = axis.x * sin;
  5210. result.y = axis.y * sin;
  5211. result.z = axis.z * sin;
  5212. return result;
  5213. };
  5214. /**
  5215. * Creates a new quaternion from data stored into an array
  5216. * @param array defines the data source
  5217. * @param offset defines the offset in the source array where the data starts
  5218. * @returns a new quaternion
  5219. */
  5220. Quaternion.FromArray = function (array, offset) {
  5221. if (!offset) {
  5222. offset = 0;
  5223. }
  5224. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  5225. };
  5226. /**
  5227. * Creates a new quaternion from the given Euler float angles (y, x, z)
  5228. * @param yaw defines the rotation around Y axis
  5229. * @param pitch defines the rotation around X axis
  5230. * @param roll defines the rotation around Z axis
  5231. * @returns the new quaternion
  5232. */
  5233. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5234. var q = new Quaternion();
  5235. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  5236. return q;
  5237. };
  5238. /**
  5239. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  5240. * @param yaw defines the rotation around Y axis
  5241. * @param pitch defines the rotation around X axis
  5242. * @param roll defines the rotation around Z axis
  5243. * @param result defines the target quaternion
  5244. */
  5245. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5246. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  5247. var halfRoll = roll * 0.5;
  5248. var halfPitch = pitch * 0.5;
  5249. var halfYaw = yaw * 0.5;
  5250. var sinRoll = Math.sin(halfRoll);
  5251. var cosRoll = Math.cos(halfRoll);
  5252. var sinPitch = Math.sin(halfPitch);
  5253. var cosPitch = Math.cos(halfPitch);
  5254. var sinYaw = Math.sin(halfYaw);
  5255. var cosYaw = Math.cos(halfYaw);
  5256. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  5257. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  5258. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  5259. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  5260. };
  5261. /**
  5262. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  5263. * @param alpha defines the rotation around first axis
  5264. * @param beta defines the rotation around second axis
  5265. * @param gamma defines the rotation around third axis
  5266. * @returns the new quaternion
  5267. */
  5268. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  5269. var result = new Quaternion();
  5270. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  5271. return result;
  5272. };
  5273. /**
  5274. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  5275. * @param alpha defines the rotation around first axis
  5276. * @param beta defines the rotation around second axis
  5277. * @param gamma defines the rotation around third axis
  5278. * @param result defines the target quaternion
  5279. */
  5280. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  5281. // Produces a quaternion from Euler angles in the z-x-z orientation
  5282. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  5283. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  5284. var halfBeta = beta * 0.5;
  5285. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5286. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5287. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5288. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5289. };
  5290. /**
  5291. * 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)
  5292. * @param axis1 defines the first axis
  5293. * @param axis2 defines the second axis
  5294. * @param axis3 defines the third axis
  5295. * @returns the new quaternion
  5296. */
  5297. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  5298. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  5299. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5300. return quat;
  5301. };
  5302. /**
  5303. * 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
  5304. * @param axis1 defines the first axis
  5305. * @param axis2 defines the second axis
  5306. * @param axis3 defines the third axis
  5307. * @param ref defines the target quaternion
  5308. */
  5309. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5310. var rotMat = MathTmp.Matrix[0];
  5311. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5312. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5313. };
  5314. /**
  5315. * Interpolates between two quaternions
  5316. * @param left defines first quaternion
  5317. * @param right defines second quaternion
  5318. * @param amount defines the gradient to use
  5319. * @returns the new interpolated quaternion
  5320. */
  5321. Quaternion.Slerp = function (left, right, amount) {
  5322. var result = Quaternion.Identity();
  5323. Quaternion.SlerpToRef(left, right, amount, result);
  5324. return result;
  5325. };
  5326. /**
  5327. * Interpolates between two quaternions and stores it into a target quaternion
  5328. * @param left defines first quaternion
  5329. * @param right defines second quaternion
  5330. * @param amount defines the gradient to use
  5331. * @param result defines the target quaternion
  5332. */
  5333. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5334. var num2;
  5335. var num3;
  5336. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5337. var flag = false;
  5338. if (num4 < 0) {
  5339. flag = true;
  5340. num4 = -num4;
  5341. }
  5342. if (num4 > 0.999999) {
  5343. num3 = 1 - amount;
  5344. num2 = flag ? -amount : amount;
  5345. }
  5346. else {
  5347. var num5 = Math.acos(num4);
  5348. var num6 = (1.0 / Math.sin(num5));
  5349. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5350. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5351. }
  5352. result.x = (num3 * left.x) + (num2 * right.x);
  5353. result.y = (num3 * left.y) + (num2 * right.y);
  5354. result.z = (num3 * left.z) + (num2 * right.z);
  5355. result.w = (num3 * left.w) + (num2 * right.w);
  5356. };
  5357. /**
  5358. * Interpolate between two quaternions using Hermite interpolation
  5359. * @param value1 defines first quaternion
  5360. * @param tangent1 defines the incoming tangent
  5361. * @param value2 defines second quaternion
  5362. * @param tangent2 defines the outgoing tangent
  5363. * @param amount defines the target quaternion
  5364. * @returns the new interpolated quaternion
  5365. */
  5366. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5367. var squared = amount * amount;
  5368. var cubed = amount * squared;
  5369. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5370. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5371. var part3 = (cubed - (2.0 * squared)) + amount;
  5372. var part4 = cubed - squared;
  5373. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5374. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5375. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5376. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5377. return new Quaternion(x, y, z, w);
  5378. };
  5379. return Quaternion;
  5380. }());
  5381. BABYLON.Quaternion = Quaternion;
  5382. /**
  5383. * Class used to store matrix data (4x4)
  5384. */
  5385. var Matrix = /** @class */ (function () {
  5386. /**
  5387. * Creates an empty matrix (filled with zeros)
  5388. */
  5389. function Matrix() {
  5390. this._isIdentity = false;
  5391. this._isIdentityDirty = true;
  5392. /**
  5393. * Gets or sets the internal data of the matrix
  5394. */
  5395. this.m = new Float32Array(16);
  5396. this._markAsUpdated();
  5397. }
  5398. /** @hidden */
  5399. Matrix.prototype._markAsUpdated = function () {
  5400. this.updateFlag = Matrix._updateFlagSeed++;
  5401. this._isIdentityDirty = true;
  5402. };
  5403. // Properties
  5404. /**
  5405. * Check if the current matrix is indentity
  5406. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5407. * @returns true is the matrix is the identity matrix
  5408. */
  5409. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5410. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5411. if (this._isIdentityDirty) {
  5412. this._isIdentityDirty = false;
  5413. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5414. this._isIdentity = false;
  5415. }
  5416. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5417. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5418. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5419. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5420. this._isIdentity = false;
  5421. }
  5422. else {
  5423. this._isIdentity = true;
  5424. }
  5425. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5426. this._isIdentity = false;
  5427. }
  5428. }
  5429. return this._isIdentity;
  5430. };
  5431. /**
  5432. * Gets the determinant of the matrix
  5433. * @returns the matrix determinant
  5434. */
  5435. Matrix.prototype.determinant = function () {
  5436. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5437. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5438. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5439. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5440. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5441. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5442. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5443. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5444. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5445. };
  5446. // Methods
  5447. /**
  5448. * Returns the matrix as a Float32Array
  5449. * @returns the matrix underlying array
  5450. */
  5451. Matrix.prototype.toArray = function () {
  5452. return this.m;
  5453. };
  5454. /**
  5455. * Returns the matrix as a Float32Array
  5456. * @returns the matrix underlying array.
  5457. */
  5458. Matrix.prototype.asArray = function () {
  5459. return this.toArray();
  5460. };
  5461. /**
  5462. * Inverts the current matrix in place
  5463. * @returns the current inverted matrix
  5464. */
  5465. Matrix.prototype.invert = function () {
  5466. this.invertToRef(this);
  5467. return this;
  5468. };
  5469. /**
  5470. * Sets all the matrix elements to zero
  5471. * @returns the current matrix
  5472. */
  5473. Matrix.prototype.reset = function () {
  5474. for (var index = 0; index < 16; index++) {
  5475. this.m[index] = 0.0;
  5476. }
  5477. this._markAsUpdated();
  5478. return this;
  5479. };
  5480. /**
  5481. * Adds the current matrix with a second one
  5482. * @param other defines the matrix to add
  5483. * @returns a new matrix as the addition of the current matrix and the given one
  5484. */
  5485. Matrix.prototype.add = function (other) {
  5486. var result = new Matrix();
  5487. this.addToRef(other, result);
  5488. return result;
  5489. };
  5490. /**
  5491. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5492. * @param other defines the matrix to add
  5493. * @param result defines the target matrix
  5494. * @returns the current matrix
  5495. */
  5496. Matrix.prototype.addToRef = function (other, result) {
  5497. for (var index = 0; index < 16; index++) {
  5498. result.m[index] = this.m[index] + other.m[index];
  5499. }
  5500. result._markAsUpdated();
  5501. return this;
  5502. };
  5503. /**
  5504. * Adds in place the given matrix to the current matrix
  5505. * @param other defines the second operand
  5506. * @returns the current updated matrix
  5507. */
  5508. Matrix.prototype.addToSelf = function (other) {
  5509. for (var index = 0; index < 16; index++) {
  5510. this.m[index] += other.m[index];
  5511. }
  5512. this._markAsUpdated();
  5513. return this;
  5514. };
  5515. /**
  5516. * Sets the given matrix to the current inverted Matrix
  5517. * @param other defines the target matrix
  5518. * @returns the unmodified current matrix
  5519. */
  5520. Matrix.prototype.invertToRef = function (other) {
  5521. var l1 = this.m[0];
  5522. var l2 = this.m[1];
  5523. var l3 = this.m[2];
  5524. var l4 = this.m[3];
  5525. var l5 = this.m[4];
  5526. var l6 = this.m[5];
  5527. var l7 = this.m[6];
  5528. var l8 = this.m[7];
  5529. var l9 = this.m[8];
  5530. var l10 = this.m[9];
  5531. var l11 = this.m[10];
  5532. var l12 = this.m[11];
  5533. var l13 = this.m[12];
  5534. var l14 = this.m[13];
  5535. var l15 = this.m[14];
  5536. var l16 = this.m[15];
  5537. var l17 = (l11 * l16) - (l12 * l15);
  5538. var l18 = (l10 * l16) - (l12 * l14);
  5539. var l19 = (l10 * l15) - (l11 * l14);
  5540. var l20 = (l9 * l16) - (l12 * l13);
  5541. var l21 = (l9 * l15) - (l11 * l13);
  5542. var l22 = (l9 * l14) - (l10 * l13);
  5543. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5544. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5545. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5546. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5547. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5548. var l28 = (l7 * l16) - (l8 * l15);
  5549. var l29 = (l6 * l16) - (l8 * l14);
  5550. var l30 = (l6 * l15) - (l7 * l14);
  5551. var l31 = (l5 * l16) - (l8 * l13);
  5552. var l32 = (l5 * l15) - (l7 * l13);
  5553. var l33 = (l5 * l14) - (l6 * l13);
  5554. var l34 = (l7 * l12) - (l8 * l11);
  5555. var l35 = (l6 * l12) - (l8 * l10);
  5556. var l36 = (l6 * l11) - (l7 * l10);
  5557. var l37 = (l5 * l12) - (l8 * l9);
  5558. var l38 = (l5 * l11) - (l7 * l9);
  5559. var l39 = (l5 * l10) - (l6 * l9);
  5560. other.m[0] = l23 * l27;
  5561. other.m[4] = l24 * l27;
  5562. other.m[8] = l25 * l27;
  5563. other.m[12] = l26 * l27;
  5564. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5565. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5566. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5567. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5568. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5569. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5570. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5571. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5572. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5573. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5574. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5575. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5576. other._markAsUpdated();
  5577. return this;
  5578. };
  5579. /**
  5580. * Inserts the translation vector (using 3 floats) in the current matrix
  5581. * @param x defines the 1st component of the translation
  5582. * @param y defines the 2nd component of the translation
  5583. * @param z defines the 3rd component of the translation
  5584. * @returns the current updated matrix
  5585. */
  5586. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5587. this.m[12] = x;
  5588. this.m[13] = y;
  5589. this.m[14] = z;
  5590. this._markAsUpdated();
  5591. return this;
  5592. };
  5593. /**
  5594. * Inserts the translation vector in the current matrix
  5595. * @param vector3 defines the translation to insert
  5596. * @returns the current updated matrix
  5597. */
  5598. Matrix.prototype.setTranslation = function (vector3) {
  5599. this.m[12] = vector3.x;
  5600. this.m[13] = vector3.y;
  5601. this.m[14] = vector3.z;
  5602. this._markAsUpdated();
  5603. return this;
  5604. };
  5605. /**
  5606. * Gets the translation value of the current matrix
  5607. * @returns a new Vector3 as the extracted translation from the matrix
  5608. */
  5609. Matrix.prototype.getTranslation = function () {
  5610. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5611. };
  5612. /**
  5613. * Fill a Vector3 with the extracted translation from the matrix
  5614. * @param result defines the Vector3 where to store the translation
  5615. * @returns the current matrix
  5616. */
  5617. Matrix.prototype.getTranslationToRef = function (result) {
  5618. result.x = this.m[12];
  5619. result.y = this.m[13];
  5620. result.z = this.m[14];
  5621. return this;
  5622. };
  5623. /**
  5624. * Remove rotation and scaling part from the matrix
  5625. * @returns the updated matrix
  5626. */
  5627. Matrix.prototype.removeRotationAndScaling = function () {
  5628. this.setRowFromFloats(0, 1, 0, 0, 0);
  5629. this.setRowFromFloats(1, 0, 1, 0, 0);
  5630. this.setRowFromFloats(2, 0, 0, 1, 0);
  5631. return this;
  5632. };
  5633. /**
  5634. * Multiply two matrices
  5635. * @param other defines the second operand
  5636. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5637. */
  5638. Matrix.prototype.multiply = function (other) {
  5639. var result = new Matrix();
  5640. this.multiplyToRef(other, result);
  5641. return result;
  5642. };
  5643. /**
  5644. * Copy the current matrix from the given one
  5645. * @param other defines the source matrix
  5646. * @returns the current updated matrix
  5647. */
  5648. Matrix.prototype.copyFrom = function (other) {
  5649. for (var index = 0; index < 16; index++) {
  5650. this.m[index] = other.m[index];
  5651. }
  5652. this._markAsUpdated();
  5653. return this;
  5654. };
  5655. /**
  5656. * Populates the given array from the starting index with the current matrix values
  5657. * @param array defines the target array
  5658. * @param offset defines the offset in the target array where to start storing values
  5659. * @returns the current matrix
  5660. */
  5661. Matrix.prototype.copyToArray = function (array, offset) {
  5662. if (offset === void 0) { offset = 0; }
  5663. for (var index = 0; index < 16; index++) {
  5664. array[offset + index] = this.m[index];
  5665. }
  5666. return this;
  5667. };
  5668. /**
  5669. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5670. * @param other defines the second operand
  5671. * @param result defines the matrix where to store the multiplication
  5672. * @returns the current matrix
  5673. */
  5674. Matrix.prototype.multiplyToRef = function (other, result) {
  5675. this.multiplyToArray(other, result.m, 0);
  5676. result._markAsUpdated();
  5677. return this;
  5678. };
  5679. /**
  5680. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5681. * @param other defines the second operand
  5682. * @param result defines the array where to store the multiplication
  5683. * @param offset defines the offset in the target array where to start storing values
  5684. * @returns the current matrix
  5685. */
  5686. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5687. var tm0 = this.m[0];
  5688. var tm1 = this.m[1];
  5689. var tm2 = this.m[2];
  5690. var tm3 = this.m[3];
  5691. var tm4 = this.m[4];
  5692. var tm5 = this.m[5];
  5693. var tm6 = this.m[6];
  5694. var tm7 = this.m[7];
  5695. var tm8 = this.m[8];
  5696. var tm9 = this.m[9];
  5697. var tm10 = this.m[10];
  5698. var tm11 = this.m[11];
  5699. var tm12 = this.m[12];
  5700. var tm13 = this.m[13];
  5701. var tm14 = this.m[14];
  5702. var tm15 = this.m[15];
  5703. var om0 = other.m[0];
  5704. var om1 = other.m[1];
  5705. var om2 = other.m[2];
  5706. var om3 = other.m[3];
  5707. var om4 = other.m[4];
  5708. var om5 = other.m[5];
  5709. var om6 = other.m[6];
  5710. var om7 = other.m[7];
  5711. var om8 = other.m[8];
  5712. var om9 = other.m[9];
  5713. var om10 = other.m[10];
  5714. var om11 = other.m[11];
  5715. var om12 = other.m[12];
  5716. var om13 = other.m[13];
  5717. var om14 = other.m[14];
  5718. var om15 = other.m[15];
  5719. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5720. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5721. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5722. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5723. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5724. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5725. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5726. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5727. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5728. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5729. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5730. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5731. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5732. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5733. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5734. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5735. return this;
  5736. };
  5737. /**
  5738. * Check equality between this matrix and a second one
  5739. * @param value defines the second matrix to compare
  5740. * @returns true is the current matrix and the given one values are strictly equal
  5741. */
  5742. Matrix.prototype.equals = function (value) {
  5743. return value &&
  5744. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5745. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5746. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5747. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5748. };
  5749. /**
  5750. * Clone the current matrix
  5751. * @returns a new matrix from the current matrix
  5752. */
  5753. Matrix.prototype.clone = function () {
  5754. 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]);
  5755. };
  5756. /**
  5757. * Returns the name of the current matrix class
  5758. * @returns the string "Matrix"
  5759. */
  5760. Matrix.prototype.getClassName = function () {
  5761. return "Matrix";
  5762. };
  5763. /**
  5764. * Gets the hash code of the current matrix
  5765. * @returns the hash code
  5766. */
  5767. Matrix.prototype.getHashCode = function () {
  5768. var hash = this.m[0] || 0;
  5769. for (var i = 1; i < 16; i++) {
  5770. hash = (hash * 397) ^ (this.m[i] || 0);
  5771. }
  5772. return hash;
  5773. };
  5774. /**
  5775. * Decomposes the current Matrix into a translation, rotation and scaling components
  5776. * @param scale defines the scale vector3 given as a reference to update
  5777. * @param rotation defines the rotation quaternion given as a reference to update
  5778. * @param translation defines the translation vector3 given as a reference to update
  5779. * @returns true if operation was successful
  5780. */
  5781. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5782. if (translation) {
  5783. translation.x = this.m[12];
  5784. translation.y = this.m[13];
  5785. translation.z = this.m[14];
  5786. }
  5787. scale = scale || MathTmp.Vector3[0];
  5788. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5789. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5790. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5791. if (this.determinant() <= 0) {
  5792. scale.y *= -1;
  5793. }
  5794. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5795. if (rotation) {
  5796. rotation.x = 0;
  5797. rotation.y = 0;
  5798. rotation.z = 0;
  5799. rotation.w = 1;
  5800. }
  5801. return false;
  5802. }
  5803. if (rotation) {
  5804. 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]);
  5805. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5806. }
  5807. return true;
  5808. };
  5809. /**
  5810. * Gets specific row of the matrix
  5811. * @param index defines the number of the row to get
  5812. * @returns the index-th row of the current matrix as a new Vector4
  5813. */
  5814. Matrix.prototype.getRow = function (index) {
  5815. if (index < 0 || index > 3) {
  5816. return null;
  5817. }
  5818. var i = index * 4;
  5819. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5820. };
  5821. /**
  5822. * Sets the index-th row of the current matrix to the vector4 values
  5823. * @param index defines the number of the row to set
  5824. * @param row defines the target vector4
  5825. * @returns the updated current matrix
  5826. */
  5827. Matrix.prototype.setRow = function (index, row) {
  5828. if (index < 0 || index > 3) {
  5829. return this;
  5830. }
  5831. var i = index * 4;
  5832. this.m[i + 0] = row.x;
  5833. this.m[i + 1] = row.y;
  5834. this.m[i + 2] = row.z;
  5835. this.m[i + 3] = row.w;
  5836. this._markAsUpdated();
  5837. return this;
  5838. };
  5839. /**
  5840. * Compute the transpose of the matrix
  5841. * @returns the new transposed matrix
  5842. */
  5843. Matrix.prototype.transpose = function () {
  5844. return Matrix.Transpose(this);
  5845. };
  5846. /**
  5847. * Compute the transpose of the matrix and store it in a given matrix
  5848. * @param result defines the target matrix
  5849. * @returns the current matrix
  5850. */
  5851. Matrix.prototype.transposeToRef = function (result) {
  5852. Matrix.TransposeToRef(this, result);
  5853. return this;
  5854. };
  5855. /**
  5856. * Sets the index-th row of the current matrix with the given 4 x float values
  5857. * @param index defines the row index
  5858. * @param x defines the x component to set
  5859. * @param y defines the y component to set
  5860. * @param z defines the z component to set
  5861. * @param w defines the w component to set
  5862. * @returns the updated current matrix
  5863. */
  5864. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5865. if (index < 0 || index > 3) {
  5866. return this;
  5867. }
  5868. var i = index * 4;
  5869. this.m[i + 0] = x;
  5870. this.m[i + 1] = y;
  5871. this.m[i + 2] = z;
  5872. this.m[i + 3] = w;
  5873. this._markAsUpdated();
  5874. return this;
  5875. };
  5876. /**
  5877. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5878. * @param scale defines the scale factor
  5879. * @returns a new matrix
  5880. */
  5881. Matrix.prototype.scale = function (scale) {
  5882. var result = new Matrix();
  5883. this.scaleToRef(scale, result);
  5884. return result;
  5885. };
  5886. /**
  5887. * Scale the current matrix values by a factor to a given result matrix
  5888. * @param scale defines the scale factor
  5889. * @param result defines the matrix to store the result
  5890. * @returns the current matrix
  5891. */
  5892. Matrix.prototype.scaleToRef = function (scale, result) {
  5893. for (var index = 0; index < 16; index++) {
  5894. result.m[index] = this.m[index] * scale;
  5895. }
  5896. result._markAsUpdated();
  5897. return this;
  5898. };
  5899. /**
  5900. * Scale the current matrix values by a factor and add the result to a given matrix
  5901. * @param scale defines the scale factor
  5902. * @param result defines the Matrix to store the result
  5903. * @returns the current matrix
  5904. */
  5905. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5906. for (var index = 0; index < 16; index++) {
  5907. result.m[index] += this.m[index] * scale;
  5908. }
  5909. result._markAsUpdated();
  5910. return this;
  5911. };
  5912. /**
  5913. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5914. * @param ref matrix to store the result
  5915. */
  5916. Matrix.prototype.toNormalMatrix = function (ref) {
  5917. this.invertToRef(ref);
  5918. ref.transpose();
  5919. var m = ref.m;
  5920. 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);
  5921. };
  5922. /**
  5923. * Gets only rotation part of the current matrix
  5924. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5925. */
  5926. Matrix.prototype.getRotationMatrix = function () {
  5927. var result = Matrix.Identity();
  5928. this.getRotationMatrixToRef(result);
  5929. return result;
  5930. };
  5931. /**
  5932. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5933. * @param result defines the target matrix to store data to
  5934. * @returns the current matrix
  5935. */
  5936. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5937. var m = this.m;
  5938. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5939. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5940. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5941. if (this.determinant() <= 0) {
  5942. sy *= -1;
  5943. }
  5944. if (sx === 0 || sy === 0 || sz === 0) {
  5945. Matrix.IdentityToRef(result);
  5946. }
  5947. else {
  5948. 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);
  5949. }
  5950. return this;
  5951. };
  5952. // Statics
  5953. /**
  5954. * Creates a matrix from an array
  5955. * @param array defines the source array
  5956. * @param offset defines an offset in the source array
  5957. * @returns a new Matrix set from the starting index of the given array
  5958. */
  5959. Matrix.FromArray = function (array, offset) {
  5960. var result = new Matrix();
  5961. if (!offset) {
  5962. offset = 0;
  5963. }
  5964. Matrix.FromArrayToRef(array, offset, result);
  5965. return result;
  5966. };
  5967. /**
  5968. * Copy the content of an array into a given matrix
  5969. * @param array defines the source array
  5970. * @param offset defines an offset in the source array
  5971. * @param result defines the target matrix
  5972. */
  5973. Matrix.FromArrayToRef = function (array, offset, result) {
  5974. for (var index = 0; index < 16; index++) {
  5975. result.m[index] = array[index + offset];
  5976. }
  5977. result._markAsUpdated();
  5978. };
  5979. /**
  5980. * Stores an array into a matrix after having multiplied each component by a given factor
  5981. * @param array defines the source array
  5982. * @param offset defines the offset in the source array
  5983. * @param scale defines the scaling factor
  5984. * @param result defines the target matrix
  5985. */
  5986. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5987. for (var index = 0; index < 16; index++) {
  5988. result.m[index] = array[index + offset] * scale;
  5989. }
  5990. result._markAsUpdated();
  5991. };
  5992. /**
  5993. * Stores a list of values (16) inside a given matrix
  5994. * @param initialM11 defines 1st value of 1st row
  5995. * @param initialM12 defines 2nd value of 1st row
  5996. * @param initialM13 defines 3rd value of 1st row
  5997. * @param initialM14 defines 4th value of 1st row
  5998. * @param initialM21 defines 1st value of 2nd row
  5999. * @param initialM22 defines 2nd value of 2nd row
  6000. * @param initialM23 defines 3rd value of 2nd row
  6001. * @param initialM24 defines 4th value of 2nd row
  6002. * @param initialM31 defines 1st value of 3rd row
  6003. * @param initialM32 defines 2nd value of 3rd row
  6004. * @param initialM33 defines 3rd value of 3rd row
  6005. * @param initialM34 defines 4th value of 3rd row
  6006. * @param initialM41 defines 1st value of 4th row
  6007. * @param initialM42 defines 2nd value of 4th row
  6008. * @param initialM43 defines 3rd value of 4th row
  6009. * @param initialM44 defines 4th value of 4th row
  6010. * @param result defines the target matrix
  6011. */
  6012. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  6013. result.m[0] = initialM11;
  6014. result.m[1] = initialM12;
  6015. result.m[2] = initialM13;
  6016. result.m[3] = initialM14;
  6017. result.m[4] = initialM21;
  6018. result.m[5] = initialM22;
  6019. result.m[6] = initialM23;
  6020. result.m[7] = initialM24;
  6021. result.m[8] = initialM31;
  6022. result.m[9] = initialM32;
  6023. result.m[10] = initialM33;
  6024. result.m[11] = initialM34;
  6025. result.m[12] = initialM41;
  6026. result.m[13] = initialM42;
  6027. result.m[14] = initialM43;
  6028. result.m[15] = initialM44;
  6029. result._markAsUpdated();
  6030. };
  6031. Object.defineProperty(Matrix, "IdentityReadOnly", {
  6032. /**
  6033. * Gets an identity matrix that must not be updated
  6034. */
  6035. get: function () {
  6036. return Matrix._identityReadOnly;
  6037. },
  6038. enumerable: true,
  6039. configurable: true
  6040. });
  6041. /**
  6042. * Creates new matrix from a list of values (16)
  6043. * @param initialM11 defines 1st value of 1st row
  6044. * @param initialM12 defines 2nd value of 1st row
  6045. * @param initialM13 defines 3rd value of 1st row
  6046. * @param initialM14 defines 4th value of 1st row
  6047. * @param initialM21 defines 1st value of 2nd row
  6048. * @param initialM22 defines 2nd value of 2nd row
  6049. * @param initialM23 defines 3rd value of 2nd row
  6050. * @param initialM24 defines 4th value of 2nd row
  6051. * @param initialM31 defines 1st value of 3rd row
  6052. * @param initialM32 defines 2nd value of 3rd row
  6053. * @param initialM33 defines 3rd value of 3rd row
  6054. * @param initialM34 defines 4th value of 3rd row
  6055. * @param initialM41 defines 1st value of 4th row
  6056. * @param initialM42 defines 2nd value of 4th row
  6057. * @param initialM43 defines 3rd value of 4th row
  6058. * @param initialM44 defines 4th value of 4th row
  6059. * @returns the new matrix
  6060. */
  6061. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  6062. var result = new Matrix();
  6063. result.m[0] = initialM11;
  6064. result.m[1] = initialM12;
  6065. result.m[2] = initialM13;
  6066. result.m[3] = initialM14;
  6067. result.m[4] = initialM21;
  6068. result.m[5] = initialM22;
  6069. result.m[6] = initialM23;
  6070. result.m[7] = initialM24;
  6071. result.m[8] = initialM31;
  6072. result.m[9] = initialM32;
  6073. result.m[10] = initialM33;
  6074. result.m[11] = initialM34;
  6075. result.m[12] = initialM41;
  6076. result.m[13] = initialM42;
  6077. result.m[14] = initialM43;
  6078. result.m[15] = initialM44;
  6079. return result;
  6080. };
  6081. /**
  6082. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  6083. * @param scale defines the scale vector3
  6084. * @param rotation defines the rotation quaternion
  6085. * @param translation defines the translation vector3
  6086. * @returns a new matrix
  6087. */
  6088. Matrix.Compose = function (scale, rotation, translation) {
  6089. var result = Matrix.Identity();
  6090. Matrix.ComposeToRef(scale, rotation, translation, result);
  6091. return result;
  6092. };
  6093. /**
  6094. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  6095. * @param scale defines the scale vector3
  6096. * @param rotation defines the rotation quaternion
  6097. * @param translation defines the translation vector3
  6098. * @param result defines the target matrix
  6099. */
  6100. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  6101. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  6102. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  6103. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  6104. result.setTranslation(translation);
  6105. };
  6106. /**
  6107. * Creates a new identity matrix
  6108. * @returns a new identity matrix
  6109. */
  6110. Matrix.Identity = function () {
  6111. 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);
  6112. };
  6113. /**
  6114. * Creates a new identity matrix and stores the result in a given matrix
  6115. * @param result defines the target matrix
  6116. */
  6117. Matrix.IdentityToRef = function (result) {
  6118. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  6119. };
  6120. /**
  6121. * Creates a new zero matrix
  6122. * @returns a new zero matrix
  6123. */
  6124. Matrix.Zero = function () {
  6125. 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);
  6126. };
  6127. /**
  6128. * Creates a new rotation matrix for "angle" radians around the X axis
  6129. * @param angle defines the angle (in radians) to use
  6130. * @return the new matrix
  6131. */
  6132. Matrix.RotationX = function (angle) {
  6133. var result = new Matrix();
  6134. Matrix.RotationXToRef(angle, result);
  6135. return result;
  6136. };
  6137. /**
  6138. * Creates a new matrix as the invert of a given matrix
  6139. * @param source defines the source matrix
  6140. * @returns the new matrix
  6141. */
  6142. Matrix.Invert = function (source) {
  6143. var result = new Matrix();
  6144. source.invertToRef(result);
  6145. return result;
  6146. };
  6147. /**
  6148. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  6149. * @param angle defines the angle (in radians) to use
  6150. * @param result defines the target matrix
  6151. */
  6152. Matrix.RotationXToRef = function (angle, result) {
  6153. var s = Math.sin(angle);
  6154. var c = Math.cos(angle);
  6155. result.m[0] = 1.0;
  6156. result.m[15] = 1.0;
  6157. result.m[5] = c;
  6158. result.m[10] = c;
  6159. result.m[9] = -s;
  6160. result.m[6] = s;
  6161. result.m[1] = 0.0;
  6162. result.m[2] = 0.0;
  6163. result.m[3] = 0.0;
  6164. result.m[4] = 0.0;
  6165. result.m[7] = 0.0;
  6166. result.m[8] = 0.0;
  6167. result.m[11] = 0.0;
  6168. result.m[12] = 0.0;
  6169. result.m[13] = 0.0;
  6170. result.m[14] = 0.0;
  6171. result._markAsUpdated();
  6172. };
  6173. /**
  6174. * Creates a new rotation matrix for "angle" radians around the Y axis
  6175. * @param angle defines the angle (in radians) to use
  6176. * @return the new matrix
  6177. */
  6178. Matrix.RotationY = function (angle) {
  6179. var result = new Matrix();
  6180. Matrix.RotationYToRef(angle, result);
  6181. return result;
  6182. };
  6183. /**
  6184. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  6185. * @param angle defines the angle (in radians) to use
  6186. * @param result defines the target matrix
  6187. */
  6188. Matrix.RotationYToRef = function (angle, result) {
  6189. var s = Math.sin(angle);
  6190. var c = Math.cos(angle);
  6191. result.m[5] = 1.0;
  6192. result.m[15] = 1.0;
  6193. result.m[0] = c;
  6194. result.m[2] = -s;
  6195. result.m[8] = s;
  6196. result.m[10] = c;
  6197. result.m[1] = 0.0;
  6198. result.m[3] = 0.0;
  6199. result.m[4] = 0.0;
  6200. result.m[6] = 0.0;
  6201. result.m[7] = 0.0;
  6202. result.m[9] = 0.0;
  6203. result.m[11] = 0.0;
  6204. result.m[12] = 0.0;
  6205. result.m[13] = 0.0;
  6206. result.m[14] = 0.0;
  6207. result._markAsUpdated();
  6208. };
  6209. /**
  6210. * Creates a new rotation matrix for "angle" radians around the Z axis
  6211. * @param angle defines the angle (in radians) to use
  6212. * @return the new matrix
  6213. */
  6214. Matrix.RotationZ = function (angle) {
  6215. var result = new Matrix();
  6216. Matrix.RotationZToRef(angle, result);
  6217. return result;
  6218. };
  6219. /**
  6220. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  6221. * @param angle defines the angle (in radians) to use
  6222. * @param result defines the target matrix
  6223. */
  6224. Matrix.RotationZToRef = function (angle, result) {
  6225. var s = Math.sin(angle);
  6226. var c = Math.cos(angle);
  6227. result.m[10] = 1.0;
  6228. result.m[15] = 1.0;
  6229. result.m[0] = c;
  6230. result.m[1] = s;
  6231. result.m[4] = -s;
  6232. result.m[5] = c;
  6233. result.m[2] = 0.0;
  6234. result.m[3] = 0.0;
  6235. result.m[6] = 0.0;
  6236. result.m[7] = 0.0;
  6237. result.m[8] = 0.0;
  6238. result.m[9] = 0.0;
  6239. result.m[11] = 0.0;
  6240. result.m[12] = 0.0;
  6241. result.m[13] = 0.0;
  6242. result.m[14] = 0.0;
  6243. result._markAsUpdated();
  6244. };
  6245. /**
  6246. * Creates a new rotation matrix for "angle" radians around the given axis
  6247. * @param axis defines the axis to use
  6248. * @param angle defines the angle (in radians) to use
  6249. * @return the new matrix
  6250. */
  6251. Matrix.RotationAxis = function (axis, angle) {
  6252. var result = Matrix.Zero();
  6253. Matrix.RotationAxisToRef(axis, angle, result);
  6254. return result;
  6255. };
  6256. /**
  6257. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  6258. * @param axis defines the axis to use
  6259. * @param angle defines the angle (in radians) to use
  6260. * @param result defines the target matrix
  6261. */
  6262. Matrix.RotationAxisToRef = function (axis, angle, result) {
  6263. var s = Math.sin(-angle);
  6264. var c = Math.cos(-angle);
  6265. var c1 = 1 - c;
  6266. axis.normalize();
  6267. result.m[0] = (axis.x * axis.x) * c1 + c;
  6268. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  6269. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  6270. result.m[3] = 0.0;
  6271. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  6272. result.m[5] = (axis.y * axis.y) * c1 + c;
  6273. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  6274. result.m[7] = 0.0;
  6275. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  6276. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  6277. result.m[10] = (axis.z * axis.z) * c1 + c;
  6278. result.m[11] = 0.0;
  6279. result.m[15] = 1.0;
  6280. result._markAsUpdated();
  6281. };
  6282. /**
  6283. * Creates a rotation matrix
  6284. * @param yaw defines the yaw angle in radians (Y axis)
  6285. * @param pitch defines the pitch angle in radians (X axis)
  6286. * @param roll defines the roll angle in radians (X axis)
  6287. * @returns the new rotation matrix
  6288. */
  6289. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  6290. var result = new Matrix();
  6291. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  6292. return result;
  6293. };
  6294. /**
  6295. * Creates a rotation matrix and stores it in a given matrix
  6296. * @param yaw defines the yaw angle in radians (Y axis)
  6297. * @param pitch defines the pitch angle in radians (X axis)
  6298. * @param roll defines the roll angle in radians (X axis)
  6299. * @param result defines the target matrix
  6300. */
  6301. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  6302. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  6303. this._tempQuaternion.toRotationMatrix(result);
  6304. };
  6305. /**
  6306. * Creates a scaling matrix
  6307. * @param x defines the scale factor on X axis
  6308. * @param y defines the scale factor on Y axis
  6309. * @param z defines the scale factor on Z axis
  6310. * @returns the new matrix
  6311. */
  6312. Matrix.Scaling = function (x, y, z) {
  6313. var result = Matrix.Zero();
  6314. Matrix.ScalingToRef(x, y, z, result);
  6315. return result;
  6316. };
  6317. /**
  6318. * Creates a scaling matrix and stores it in a given matrix
  6319. * @param x defines the scale factor on X axis
  6320. * @param y defines the scale factor on Y axis
  6321. * @param z defines the scale factor on Z axis
  6322. * @param result defines the target matrix
  6323. */
  6324. Matrix.ScalingToRef = function (x, y, z, result) {
  6325. result.m[0] = x;
  6326. result.m[1] = 0.0;
  6327. result.m[2] = 0.0;
  6328. result.m[3] = 0.0;
  6329. result.m[4] = 0.0;
  6330. result.m[5] = y;
  6331. result.m[6] = 0.0;
  6332. result.m[7] = 0.0;
  6333. result.m[8] = 0.0;
  6334. result.m[9] = 0.0;
  6335. result.m[10] = z;
  6336. result.m[11] = 0.0;
  6337. result.m[12] = 0.0;
  6338. result.m[13] = 0.0;
  6339. result.m[14] = 0.0;
  6340. result.m[15] = 1.0;
  6341. result._markAsUpdated();
  6342. };
  6343. /**
  6344. * Creates a translation matrix
  6345. * @param x defines the translation on X axis
  6346. * @param y defines the translation on Y axis
  6347. * @param z defines the translationon Z axis
  6348. * @returns the new matrix
  6349. */
  6350. Matrix.Translation = function (x, y, z) {
  6351. var result = Matrix.Identity();
  6352. Matrix.TranslationToRef(x, y, z, result);
  6353. return result;
  6354. };
  6355. /**
  6356. * Creates a translation matrix and stores it in a given matrix
  6357. * @param x defines the translation on X axis
  6358. * @param y defines the translation on Y axis
  6359. * @param z defines the translationon Z axis
  6360. * @param result defines the target matrix
  6361. */
  6362. Matrix.TranslationToRef = function (x, y, z, result) {
  6363. 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);
  6364. };
  6365. /**
  6366. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6367. * @param startValue defines the start value
  6368. * @param endValue defines the end value
  6369. * @param gradient defines the gradient factor
  6370. * @returns the new matrix
  6371. */
  6372. Matrix.Lerp = function (startValue, endValue, gradient) {
  6373. var result = Matrix.Zero();
  6374. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6375. return result;
  6376. };
  6377. /**
  6378. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6379. * @param startValue defines the start value
  6380. * @param endValue defines the end value
  6381. * @param gradient defines the gradient factor
  6382. * @param result defines the Matrix object where to store data
  6383. */
  6384. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6385. for (var index = 0; index < 16; index++) {
  6386. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6387. }
  6388. result._markAsUpdated();
  6389. };
  6390. /**
  6391. * Builds a new matrix whose values are computed by:
  6392. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6393. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6394. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6395. * @param startValue defines the first matrix
  6396. * @param endValue defines the second matrix
  6397. * @param gradient defines the gradient between the two matrices
  6398. * @returns the new matrix
  6399. */
  6400. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6401. var result = Matrix.Zero();
  6402. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6403. return result;
  6404. };
  6405. /**
  6406. * Update a matrix to values which are computed by:
  6407. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6408. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6409. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6410. * @param startValue defines the first matrix
  6411. * @param endValue defines the second matrix
  6412. * @param gradient defines the gradient between the two matrices
  6413. * @param result defines the target matrix
  6414. */
  6415. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6416. var startScale = MathTmp.Vector3[0];
  6417. var startRotation = MathTmp.Quaternion[0];
  6418. var startTranslation = MathTmp.Vector3[1];
  6419. startValue.decompose(startScale, startRotation, startTranslation);
  6420. var endScale = MathTmp.Vector3[2];
  6421. var endRotation = MathTmp.Quaternion[1];
  6422. var endTranslation = MathTmp.Vector3[3];
  6423. endValue.decompose(endScale, endRotation, endTranslation);
  6424. var resultScale = MathTmp.Vector3[4];
  6425. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6426. var resultRotation = MathTmp.Quaternion[2];
  6427. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6428. var resultTranslation = MathTmp.Vector3[5];
  6429. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6430. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6431. };
  6432. /**
  6433. * 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"
  6434. * This function works in left handed mode
  6435. * @param eye defines the final position of the entity
  6436. * @param target defines where the entity should look at
  6437. * @param up defines the up vector for the entity
  6438. * @returns the new matrix
  6439. */
  6440. Matrix.LookAtLH = function (eye, target, up) {
  6441. var result = Matrix.Zero();
  6442. Matrix.LookAtLHToRef(eye, target, up, result);
  6443. return result;
  6444. };
  6445. /**
  6446. * 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".
  6447. * This function works in left handed mode
  6448. * @param eye defines the final position of the entity
  6449. * @param target defines where the entity should look at
  6450. * @param up defines the up vector for the entity
  6451. * @param result defines the target matrix
  6452. */
  6453. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6454. // Z axis
  6455. target.subtractToRef(eye, this._zAxis);
  6456. this._zAxis.normalize();
  6457. // X axis
  6458. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6459. if (this._xAxis.lengthSquared() === 0) {
  6460. this._xAxis.x = 1.0;
  6461. }
  6462. else {
  6463. this._xAxis.normalize();
  6464. }
  6465. // Y axis
  6466. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6467. this._yAxis.normalize();
  6468. // Eye angles
  6469. var ex = -Vector3.Dot(this._xAxis, eye);
  6470. var ey = -Vector3.Dot(this._yAxis, eye);
  6471. var ez = -Vector3.Dot(this._zAxis, eye);
  6472. 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);
  6473. };
  6474. /**
  6475. * 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"
  6476. * This function works in right handed mode
  6477. * @param eye defines the final position of the entity
  6478. * @param target defines where the entity should look at
  6479. * @param up defines the up vector for the entity
  6480. * @returns the new matrix
  6481. */
  6482. Matrix.LookAtRH = function (eye, target, up) {
  6483. var result = Matrix.Zero();
  6484. Matrix.LookAtRHToRef(eye, target, up, result);
  6485. return result;
  6486. };
  6487. /**
  6488. * 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".
  6489. * This function works in right handed mode
  6490. * @param eye defines the final position of the entity
  6491. * @param target defines where the entity should look at
  6492. * @param up defines the up vector for the entity
  6493. * @param result defines the target matrix
  6494. */
  6495. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6496. // Z axis
  6497. eye.subtractToRef(target, this._zAxis);
  6498. this._zAxis.normalize();
  6499. // X axis
  6500. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6501. if (this._xAxis.lengthSquared() === 0) {
  6502. this._xAxis.x = 1.0;
  6503. }
  6504. else {
  6505. this._xAxis.normalize();
  6506. }
  6507. // Y axis
  6508. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6509. this._yAxis.normalize();
  6510. // Eye angles
  6511. var ex = -Vector3.Dot(this._xAxis, eye);
  6512. var ey = -Vector3.Dot(this._yAxis, eye);
  6513. var ez = -Vector3.Dot(this._zAxis, eye);
  6514. 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);
  6515. };
  6516. /**
  6517. * Create a left-handed orthographic projection matrix
  6518. * @param width defines the viewport width
  6519. * @param height defines the viewport height
  6520. * @param znear defines the near clip plane
  6521. * @param zfar defines the far clip plane
  6522. * @returns a new matrix as a left-handed orthographic projection matrix
  6523. */
  6524. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6525. var matrix = Matrix.Zero();
  6526. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6527. return matrix;
  6528. };
  6529. /**
  6530. * Store a left-handed orthographic projection to a given matrix
  6531. * @param width defines the viewport width
  6532. * @param height defines the viewport height
  6533. * @param znear defines the near clip plane
  6534. * @param zfar defines the far clip plane
  6535. * @param result defines the target matrix
  6536. */
  6537. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6538. var n = znear;
  6539. var f = zfar;
  6540. var a = 2.0 / width;
  6541. var b = 2.0 / height;
  6542. var c = 2.0 / (f - n);
  6543. var d = -(f + n) / (f - n);
  6544. 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);
  6545. };
  6546. /**
  6547. * Create a left-handed orthographic projection matrix
  6548. * @param left defines the viewport left coordinate
  6549. * @param right defines the viewport right coordinate
  6550. * @param bottom defines the viewport bottom coordinate
  6551. * @param top defines the viewport top coordinate
  6552. * @param znear defines the near clip plane
  6553. * @param zfar defines the far clip plane
  6554. * @returns a new matrix as a left-handed orthographic projection matrix
  6555. */
  6556. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6557. var matrix = Matrix.Zero();
  6558. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6559. return matrix;
  6560. };
  6561. /**
  6562. * Stores a left-handed orthographic projection into a given matrix
  6563. * @param left defines the viewport left coordinate
  6564. * @param right defines the viewport right coordinate
  6565. * @param bottom defines the viewport bottom coordinate
  6566. * @param top defines the viewport top coordinate
  6567. * @param znear defines the near clip plane
  6568. * @param zfar defines the far clip plane
  6569. * @param result defines the target matrix
  6570. */
  6571. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6572. var n = znear;
  6573. var f = zfar;
  6574. var a = 2.0 / (right - left);
  6575. var b = 2.0 / (top - bottom);
  6576. var c = 2.0 / (f - n);
  6577. var d = -(f + n) / (f - n);
  6578. var i0 = (left + right) / (left - right);
  6579. var i1 = (top + bottom) / (bottom - top);
  6580. 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);
  6581. };
  6582. /**
  6583. * Creates a right-handed orthographic projection matrix
  6584. * @param left defines the viewport left coordinate
  6585. * @param right defines the viewport right coordinate
  6586. * @param bottom defines the viewport bottom coordinate
  6587. * @param top defines the viewport top coordinate
  6588. * @param znear defines the near clip plane
  6589. * @param zfar defines the far clip plane
  6590. * @returns a new matrix as a right-handed orthographic projection matrix
  6591. */
  6592. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6593. var matrix = Matrix.Zero();
  6594. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6595. return matrix;
  6596. };
  6597. /**
  6598. * Stores a right-handed orthographic projection into a given matrix
  6599. * @param left defines the viewport left coordinate
  6600. * @param right defines the viewport right coordinate
  6601. * @param bottom defines the viewport bottom coordinate
  6602. * @param top defines the viewport top coordinate
  6603. * @param znear defines the near clip plane
  6604. * @param zfar defines the far clip plane
  6605. * @param result defines the target matrix
  6606. */
  6607. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6608. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6609. result.m[10] *= -1.0;
  6610. };
  6611. /**
  6612. * Creates a left-handed perspective projection matrix
  6613. * @param width defines the viewport width
  6614. * @param height defines the viewport height
  6615. * @param znear defines the near clip plane
  6616. * @param zfar defines the far clip plane
  6617. * @returns a new matrix as a left-handed perspective projection matrix
  6618. */
  6619. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6620. var matrix = Matrix.Zero();
  6621. var n = znear;
  6622. var f = zfar;
  6623. var a = 2.0 * n / width;
  6624. var b = 2.0 * n / height;
  6625. var c = (f + n) / (f - n);
  6626. var d = -2.0 * f * n / (f - n);
  6627. 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);
  6628. return matrix;
  6629. };
  6630. /**
  6631. * Creates a left-handed perspective projection matrix
  6632. * @param fov defines the horizontal field of view
  6633. * @param aspect defines the aspect ratio
  6634. * @param znear defines the near clip plane
  6635. * @param zfar defines the far clip plane
  6636. * @returns a new matrix as a left-handed perspective projection matrix
  6637. */
  6638. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6639. var matrix = Matrix.Zero();
  6640. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6641. return matrix;
  6642. };
  6643. /**
  6644. * Stores a left-handed perspective projection into a given matrix
  6645. * @param fov defines the horizontal field of view
  6646. * @param aspect defines the aspect ratio
  6647. * @param znear defines the near clip plane
  6648. * @param zfar defines the far clip plane
  6649. * @param result defines the target matrix
  6650. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6651. */
  6652. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6653. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6654. var n = znear;
  6655. var f = zfar;
  6656. var t = 1.0 / (Math.tan(fov * 0.5));
  6657. var a = isVerticalFovFixed ? (t / aspect) : t;
  6658. var b = isVerticalFovFixed ? t : (t * aspect);
  6659. var c = (f + n) / (f - n);
  6660. var d = -2.0 * f * n / (f - n);
  6661. 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);
  6662. };
  6663. /**
  6664. * Creates a right-handed perspective projection matrix
  6665. * @param fov defines the horizontal field of view
  6666. * @param aspect defines the aspect ratio
  6667. * @param znear defines the near clip plane
  6668. * @param zfar defines the far clip plane
  6669. * @returns a new matrix as a right-handed perspective projection matrix
  6670. */
  6671. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6672. var matrix = Matrix.Zero();
  6673. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6674. return matrix;
  6675. };
  6676. /**
  6677. * Stores a right-handed perspective projection into a given matrix
  6678. * @param fov defines the horizontal field of view
  6679. * @param aspect defines the aspect ratio
  6680. * @param znear defines the near clip plane
  6681. * @param zfar defines the far clip plane
  6682. * @param result defines the target matrix
  6683. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6684. */
  6685. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6686. //alternatively this could be expressed as:
  6687. // m = PerspectiveFovLHToRef
  6688. // m[10] *= -1.0;
  6689. // m[11] *= -1.0;
  6690. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6691. var n = znear;
  6692. var f = zfar;
  6693. var t = 1.0 / (Math.tan(fov * 0.5));
  6694. var a = isVerticalFovFixed ? (t / aspect) : t;
  6695. var b = isVerticalFovFixed ? t : (t * aspect);
  6696. var c = -(f + n) / (f - n);
  6697. var d = -2 * f * n / (f - n);
  6698. 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);
  6699. };
  6700. /**
  6701. * Stores a perspective projection for WebVR info a given matrix
  6702. * @param fov defines the field of view
  6703. * @param znear defines the near clip plane
  6704. * @param zfar defines the far clip plane
  6705. * @param result defines the target matrix
  6706. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6707. */
  6708. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6709. if (rightHanded === void 0) { rightHanded = false; }
  6710. var rightHandedFactor = rightHanded ? -1 : 1;
  6711. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6712. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6713. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6714. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6715. var xScale = 2.0 / (leftTan + rightTan);
  6716. var yScale = 2.0 / (upTan + downTan);
  6717. result.m[0] = xScale;
  6718. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6719. result.m[5] = yScale;
  6720. result.m[6] = result.m[7] = 0.0;
  6721. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6722. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6723. result.m[10] = -zfar / (znear - zfar);
  6724. result.m[11] = 1.0 * rightHandedFactor;
  6725. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6726. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6727. result._markAsUpdated();
  6728. };
  6729. /**
  6730. * Computes a complete transformation matrix
  6731. * @param viewport defines the viewport to use
  6732. * @param world defines the world matrix
  6733. * @param view defines the view matrix
  6734. * @param projection defines the projection matrix
  6735. * @param zmin defines the near clip plane
  6736. * @param zmax defines the far clip plane
  6737. * @returns the transformation matrix
  6738. */
  6739. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6740. var cw = viewport.width;
  6741. var ch = viewport.height;
  6742. var cx = viewport.x;
  6743. var cy = viewport.y;
  6744. 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);
  6745. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6746. };
  6747. /**
  6748. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6749. * @param matrix defines the matrix to use
  6750. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6751. */
  6752. Matrix.GetAsMatrix2x2 = function (matrix) {
  6753. return new Float32Array([
  6754. matrix.m[0], matrix.m[1],
  6755. matrix.m[4], matrix.m[5]
  6756. ]);
  6757. };
  6758. /**
  6759. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6760. * @param matrix defines the matrix to use
  6761. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6762. */
  6763. Matrix.GetAsMatrix3x3 = function (matrix) {
  6764. return new Float32Array([
  6765. matrix.m[0], matrix.m[1], matrix.m[2],
  6766. matrix.m[4], matrix.m[5], matrix.m[6],
  6767. matrix.m[8], matrix.m[9], matrix.m[10]
  6768. ]);
  6769. };
  6770. /**
  6771. * Compute the transpose of a given matrix
  6772. * @param matrix defines the matrix to transpose
  6773. * @returns the new matrix
  6774. */
  6775. Matrix.Transpose = function (matrix) {
  6776. var result = new Matrix();
  6777. Matrix.TransposeToRef(matrix, result);
  6778. return result;
  6779. };
  6780. /**
  6781. * Compute the transpose of a matrix and store it in a target matrix
  6782. * @param matrix defines the matrix to transpose
  6783. * @param result defines the target matrix
  6784. */
  6785. Matrix.TransposeToRef = function (matrix, result) {
  6786. result.m[0] = matrix.m[0];
  6787. result.m[1] = matrix.m[4];
  6788. result.m[2] = matrix.m[8];
  6789. result.m[3] = matrix.m[12];
  6790. result.m[4] = matrix.m[1];
  6791. result.m[5] = matrix.m[5];
  6792. result.m[6] = matrix.m[9];
  6793. result.m[7] = matrix.m[13];
  6794. result.m[8] = matrix.m[2];
  6795. result.m[9] = matrix.m[6];
  6796. result.m[10] = matrix.m[10];
  6797. result.m[11] = matrix.m[14];
  6798. result.m[12] = matrix.m[3];
  6799. result.m[13] = matrix.m[7];
  6800. result.m[14] = matrix.m[11];
  6801. result.m[15] = matrix.m[15];
  6802. };
  6803. /**
  6804. * Computes a reflection matrix from a plane
  6805. * @param plane defines the reflection plane
  6806. * @returns a new matrix
  6807. */
  6808. Matrix.Reflection = function (plane) {
  6809. var matrix = new Matrix();
  6810. Matrix.ReflectionToRef(plane, matrix);
  6811. return matrix;
  6812. };
  6813. /**
  6814. * Computes a reflection matrix from a plane
  6815. * @param plane defines the reflection plane
  6816. * @param result defines the target matrix
  6817. */
  6818. Matrix.ReflectionToRef = function (plane, result) {
  6819. plane.normalize();
  6820. var x = plane.normal.x;
  6821. var y = plane.normal.y;
  6822. var z = plane.normal.z;
  6823. var temp = -2 * x;
  6824. var temp2 = -2 * y;
  6825. var temp3 = -2 * z;
  6826. result.m[0] = (temp * x) + 1;
  6827. result.m[1] = temp2 * x;
  6828. result.m[2] = temp3 * x;
  6829. result.m[3] = 0.0;
  6830. result.m[4] = temp * y;
  6831. result.m[5] = (temp2 * y) + 1;
  6832. result.m[6] = temp3 * y;
  6833. result.m[7] = 0.0;
  6834. result.m[8] = temp * z;
  6835. result.m[9] = temp2 * z;
  6836. result.m[10] = (temp3 * z) + 1;
  6837. result.m[11] = 0.0;
  6838. result.m[12] = temp * plane.d;
  6839. result.m[13] = temp2 * plane.d;
  6840. result.m[14] = temp3 * plane.d;
  6841. result.m[15] = 1.0;
  6842. result._markAsUpdated();
  6843. };
  6844. /**
  6845. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6846. * @param xaxis defines the value of the 1st axis
  6847. * @param yaxis defines the value of the 2nd axis
  6848. * @param zaxis defines the value of the 3rd axis
  6849. * @param result defines the target matrix
  6850. */
  6851. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6852. result.m[0] = xaxis.x;
  6853. result.m[1] = xaxis.y;
  6854. result.m[2] = xaxis.z;
  6855. result.m[3] = 0.0;
  6856. result.m[4] = yaxis.x;
  6857. result.m[5] = yaxis.y;
  6858. result.m[6] = yaxis.z;
  6859. result.m[7] = 0.0;
  6860. result.m[8] = zaxis.x;
  6861. result.m[9] = zaxis.y;
  6862. result.m[10] = zaxis.z;
  6863. result.m[11] = 0.0;
  6864. result.m[12] = 0.0;
  6865. result.m[13] = 0.0;
  6866. result.m[14] = 0.0;
  6867. result.m[15] = 1.0;
  6868. result._markAsUpdated();
  6869. };
  6870. /**
  6871. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6872. * @param quat defines the quaternion to use
  6873. * @param result defines the target matrix
  6874. */
  6875. Matrix.FromQuaternionToRef = function (quat, result) {
  6876. var xx = quat.x * quat.x;
  6877. var yy = quat.y * quat.y;
  6878. var zz = quat.z * quat.z;
  6879. var xy = quat.x * quat.y;
  6880. var zw = quat.z * quat.w;
  6881. var zx = quat.z * quat.x;
  6882. var yw = quat.y * quat.w;
  6883. var yz = quat.y * quat.z;
  6884. var xw = quat.x * quat.w;
  6885. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6886. result.m[1] = 2.0 * (xy + zw);
  6887. result.m[2] = 2.0 * (zx - yw);
  6888. result.m[3] = 0.0;
  6889. result.m[4] = 2.0 * (xy - zw);
  6890. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6891. result.m[6] = 2.0 * (yz + xw);
  6892. result.m[7] = 0.0;
  6893. result.m[8] = 2.0 * (zx + yw);
  6894. result.m[9] = 2.0 * (yz - xw);
  6895. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6896. result.m[11] = 0.0;
  6897. result.m[12] = 0.0;
  6898. result.m[13] = 0.0;
  6899. result.m[14] = 0.0;
  6900. result.m[15] = 1.0;
  6901. result._markAsUpdated();
  6902. };
  6903. Matrix._tempQuaternion = new Quaternion();
  6904. Matrix._xAxis = Vector3.Zero();
  6905. Matrix._yAxis = Vector3.Zero();
  6906. Matrix._zAxis = Vector3.Zero();
  6907. Matrix._updateFlagSeed = 0;
  6908. Matrix._identityReadOnly = Matrix.Identity();
  6909. return Matrix;
  6910. }());
  6911. BABYLON.Matrix = Matrix;
  6912. /**
  6913. * Represens a plane by the equation ax + by + cz + d = 0
  6914. */
  6915. var Plane = /** @class */ (function () {
  6916. /**
  6917. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6918. * @param a a component of the plane
  6919. * @param b b component of the plane
  6920. * @param c c component of the plane
  6921. * @param d d component of the plane
  6922. */
  6923. function Plane(a, b, c, d) {
  6924. this.normal = new Vector3(a, b, c);
  6925. this.d = d;
  6926. }
  6927. /**
  6928. * @returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6929. */
  6930. Plane.prototype.asArray = function () {
  6931. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6932. };
  6933. // Methods
  6934. /**
  6935. * @returns a new plane copied from the current Plane.
  6936. */
  6937. Plane.prototype.clone = function () {
  6938. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6939. };
  6940. /**
  6941. * @returns the string "Plane".
  6942. */
  6943. Plane.prototype.getClassName = function () {
  6944. return "Plane";
  6945. };
  6946. /**
  6947. * @returns the Plane hash code.
  6948. */
  6949. Plane.prototype.getHashCode = function () {
  6950. var hash = this.normal.getHashCode();
  6951. hash = (hash * 397) ^ (this.d || 0);
  6952. return hash;
  6953. };
  6954. /**
  6955. * Normalize the current Plane in place.
  6956. * @returns the updated Plane.
  6957. */
  6958. Plane.prototype.normalize = function () {
  6959. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6960. var magnitude = 0.0;
  6961. if (norm !== 0) {
  6962. magnitude = 1.0 / norm;
  6963. }
  6964. this.normal.x *= magnitude;
  6965. this.normal.y *= magnitude;
  6966. this.normal.z *= magnitude;
  6967. this.d *= magnitude;
  6968. return this;
  6969. };
  6970. /**
  6971. * Applies a transformation the plane and returns the result
  6972. * @param transformation the transformation matrix to be applied to the plane
  6973. * @returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6974. */
  6975. Plane.prototype.transform = function (transformation) {
  6976. var transposedMatrix = Matrix.Transpose(transformation);
  6977. var x = this.normal.x;
  6978. var y = this.normal.y;
  6979. var z = this.normal.z;
  6980. var d = this.d;
  6981. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6982. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6983. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6984. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6985. return new Plane(normalX, normalY, normalZ, finalD);
  6986. };
  6987. /**
  6988. * Calcualtte the dot product between the point and the plane normal
  6989. * @param point point to calculate the dot product with
  6990. * @returns the dot product (float) of the point coordinates and the plane normal.
  6991. */
  6992. Plane.prototype.dotCoordinate = function (point) {
  6993. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6994. };
  6995. /**
  6996. * Updates the current Plane from the plane defined by the three given points.
  6997. * @param point1 one of the points used to contruct the plane
  6998. * @param point2 one of the points used to contruct the plane
  6999. * @param point3 one of the points used to contruct the plane
  7000. * @returns the updated Plane.
  7001. */
  7002. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  7003. var x1 = point2.x - point1.x;
  7004. var y1 = point2.y - point1.y;
  7005. var z1 = point2.z - point1.z;
  7006. var x2 = point3.x - point1.x;
  7007. var y2 = point3.y - point1.y;
  7008. var z2 = point3.z - point1.z;
  7009. var yz = (y1 * z2) - (z1 * y2);
  7010. var xz = (z1 * x2) - (x1 * z2);
  7011. var xy = (x1 * y2) - (y1 * x2);
  7012. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  7013. var invPyth;
  7014. if (pyth !== 0) {
  7015. invPyth = 1.0 / pyth;
  7016. }
  7017. else {
  7018. invPyth = 0.0;
  7019. }
  7020. this.normal.x = yz * invPyth;
  7021. this.normal.y = xz * invPyth;
  7022. this.normal.z = xy * invPyth;
  7023. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  7024. return this;
  7025. };
  7026. /**
  7027. * Checks if the plane is facing a given direction
  7028. * @param direction the direction to check if the plane is facing
  7029. * @param epsilon value the dot product is compared against (returns true if dot <= epsilon)
  7030. * @returns True is the vector "direction" is the same side than the plane normal.
  7031. */
  7032. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  7033. var dot = Vector3.Dot(this.normal, direction);
  7034. return (dot <= epsilon);
  7035. };
  7036. /**
  7037. * Calculates the distance to a point
  7038. * @param point point to calculate distance to
  7039. * @returns the signed distance (float) from the given point to the Plane.
  7040. */
  7041. Plane.prototype.signedDistanceTo = function (point) {
  7042. return Vector3.Dot(point, this.normal) + this.d;
  7043. };
  7044. // Statics
  7045. /**
  7046. * Creates a plane from an array
  7047. * @param array the array to create a plane from
  7048. * @returns a new Plane from the given array.
  7049. */
  7050. Plane.FromArray = function (array) {
  7051. return new Plane(array[0], array[1], array[2], array[3]);
  7052. };
  7053. /**
  7054. * Creates a plane from three points
  7055. * @param point1 point used to create the plane
  7056. * @param point2 point used to create the plane
  7057. * @param point3 point used to create the plane
  7058. * @returns a new Plane defined by the three given points.
  7059. */
  7060. Plane.FromPoints = function (point1, point2, point3) {
  7061. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  7062. result.copyFromPoints(point1, point2, point3);
  7063. return result;
  7064. };
  7065. /**
  7066. * Creates a plane from an origin point and a normal
  7067. * @param origin origin of the plane to be constructed
  7068. * @param normal normal of the plane to be constructed
  7069. * @returns a new Plane the normal vector to this plane at the given origin point.
  7070. * Note : the vector "normal" is updated because normalized.
  7071. */
  7072. Plane.FromPositionAndNormal = function (origin, normal) {
  7073. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  7074. normal.normalize();
  7075. result.normal = normal;
  7076. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  7077. return result;
  7078. };
  7079. /**
  7080. * Calculates the distance from a plane and a point
  7081. * @param origin origin of the plane to be constructed
  7082. * @param normal normal of the plane to be constructed
  7083. * @param point point to calculate distance to
  7084. * @returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  7085. */
  7086. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  7087. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  7088. return Vector3.Dot(point, normal) + d;
  7089. };
  7090. return Plane;
  7091. }());
  7092. BABYLON.Plane = Plane;
  7093. /**
  7094. * Class used to represent a viewport on screen
  7095. */
  7096. var Viewport = /** @class */ (function () {
  7097. /**
  7098. * Creates a Viewport object located at (x, y) and sized (width, height)
  7099. * @param x defines viewport left coordinate
  7100. * @param y defines viewport top coordinate
  7101. * @param width defines the viewport width
  7102. * @param height defines the viewport height
  7103. */
  7104. function Viewport(
  7105. /** viewport left coordinate */
  7106. x,
  7107. /** viewport top coordinate */
  7108. y,
  7109. /**viewport width */
  7110. width,
  7111. /** viewport height */
  7112. height) {
  7113. this.x = x;
  7114. this.y = y;
  7115. this.width = width;
  7116. this.height = height;
  7117. }
  7118. /**
  7119. * Creates a new viewport using absolute sizing (from 0-> width, 0-> height instead of 0->1)
  7120. * @param renderWidthOrEngine defines either an engine or the rendering width
  7121. * @param renderHeight defines the rendering height
  7122. * @returns a new Viewport
  7123. */
  7124. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  7125. if (renderWidthOrEngine.getRenderWidth) {
  7126. var engine = renderWidthOrEngine;
  7127. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  7128. }
  7129. var renderWidth = renderWidthOrEngine;
  7130. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  7131. };
  7132. /**
  7133. * Returns a new Viewport copied from the current one
  7134. * @returns a new Viewport
  7135. */
  7136. Viewport.prototype.clone = function () {
  7137. return new Viewport(this.x, this.y, this.width, this.height);
  7138. };
  7139. return Viewport;
  7140. }());
  7141. BABYLON.Viewport = Viewport;
  7142. /**
  7143. * Reprasents a camera frustum
  7144. */
  7145. var Frustum = /** @class */ (function () {
  7146. function Frustum() {
  7147. }
  7148. /**
  7149. * Gets the planes representing the frustum
  7150. * @param transform matrix to be applied to the returned planes
  7151. * @returns a new array of 6 Frustum planes computed by the given transformation matrix.
  7152. */
  7153. Frustum.GetPlanes = function (transform) {
  7154. var frustumPlanes = [];
  7155. for (var index = 0; index < 6; index++) {
  7156. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  7157. }
  7158. Frustum.GetPlanesToRef(transform, frustumPlanes);
  7159. return frustumPlanes;
  7160. };
  7161. /**
  7162. * Gets the near frustum plane transformed by the transform matrix
  7163. * @param transform transformation matrix to be applied to the resulting frustum plane
  7164. * @param frustumPlane the resuling frustum plane
  7165. */
  7166. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  7167. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  7168. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  7169. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  7170. frustumPlane.d = transform.m[15] + transform.m[14];
  7171. frustumPlane.normalize();
  7172. };
  7173. /**
  7174. * Gets the far frustum plane transformed by the transform matrix
  7175. * @param transform transformation matrix to be applied to the resulting frustum plane
  7176. * @param frustumPlane the resuling frustum plane
  7177. */
  7178. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  7179. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  7180. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  7181. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  7182. frustumPlane.d = transform.m[15] - transform.m[14];
  7183. frustumPlane.normalize();
  7184. };
  7185. /**
  7186. * Gets the left frustum plane transformed by the transform matrix
  7187. * @param transform transformation matrix to be applied to the resulting frustum plane
  7188. * @param frustumPlane the resuling frustum plane
  7189. */
  7190. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  7191. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  7192. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  7193. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  7194. frustumPlane.d = transform.m[15] + transform.m[12];
  7195. frustumPlane.normalize();
  7196. };
  7197. /**
  7198. * Gets the right frustum plane transformed by the transform matrix
  7199. * @param transform transformation matrix to be applied to the resulting frustum plane
  7200. * @param frustumPlane the resuling frustum plane
  7201. */
  7202. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  7203. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  7204. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  7205. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  7206. frustumPlane.d = transform.m[15] - transform.m[12];
  7207. frustumPlane.normalize();
  7208. };
  7209. /**
  7210. * Gets the top frustum plane transformed by the transform matrix
  7211. * @param transform transformation matrix to be applied to the resulting frustum plane
  7212. * @param frustumPlane the resuling frustum plane
  7213. */
  7214. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  7215. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  7216. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  7217. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  7218. frustumPlane.d = transform.m[15] - transform.m[13];
  7219. frustumPlane.normalize();
  7220. };
  7221. /**
  7222. * Gets the bottom frustum plane transformed by the transform matrix
  7223. * @param transform transformation matrix to be applied to the resulting frustum plane
  7224. * @param frustumPlane the resuling frustum plane
  7225. */
  7226. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  7227. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  7228. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  7229. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  7230. frustumPlane.d = transform.m[15] + transform.m[13];
  7231. frustumPlane.normalize();
  7232. };
  7233. /**
  7234. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  7235. * @param transform transformation matrix to be applied to the resulting frustum planes
  7236. * @param frustumPlanes the resuling frustum planes
  7237. */
  7238. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  7239. // Near
  7240. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  7241. // Far
  7242. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  7243. // Left
  7244. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  7245. // Right
  7246. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  7247. // Top
  7248. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  7249. // Bottom
  7250. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  7251. };
  7252. return Frustum;
  7253. }());
  7254. BABYLON.Frustum = Frustum;
  7255. /** Defines supported spaces */
  7256. var Space;
  7257. (function (Space) {
  7258. /** Local (object) space */
  7259. Space[Space["LOCAL"] = 0] = "LOCAL";
  7260. /** World space */
  7261. Space[Space["WORLD"] = 1] = "WORLD";
  7262. /** Bone space */
  7263. Space[Space["BONE"] = 2] = "BONE";
  7264. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  7265. /** Defines the 3 main axes */
  7266. var Axis = /** @class */ (function () {
  7267. function Axis() {
  7268. }
  7269. /** X axis */
  7270. Axis.X = new Vector3(1.0, 0.0, 0.0);
  7271. /** Y axis */
  7272. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  7273. /** Z axis */
  7274. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  7275. return Axis;
  7276. }());
  7277. BABYLON.Axis = Axis;
  7278. /** Class used to represent a Bezier curve */
  7279. var BezierCurve = /** @class */ (function () {
  7280. function BezierCurve() {
  7281. }
  7282. /**
  7283. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats
  7284. * @param t defines the time
  7285. * @param x1 defines the left coordinate on X axis
  7286. * @param y1 defines the left coordinate on Y axis
  7287. * @param x2 defines the right coordinate on X axis
  7288. * @param y2 defines the right coordinate on Y axis
  7289. * @returns the interpolated value
  7290. */
  7291. BezierCurve.Interpolate = function (t, x1, y1, x2, y2) {
  7292. // Extract X (which is equal to time here)
  7293. var f0 = 1 - 3 * x2 + 3 * x1;
  7294. var f1 = 3 * x2 - 6 * x1;
  7295. var f2 = 3 * x1;
  7296. var refinedT = t;
  7297. for (var i = 0; i < 5; i++) {
  7298. var refinedT2 = refinedT * refinedT;
  7299. var refinedT3 = refinedT2 * refinedT;
  7300. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  7301. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  7302. refinedT -= (x - t) * slope;
  7303. refinedT = Math.min(1, Math.max(0, refinedT));
  7304. }
  7305. // Resolve cubic bezier for the given x
  7306. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  7307. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  7308. Math.pow(refinedT, 3);
  7309. };
  7310. return BezierCurve;
  7311. }());
  7312. BABYLON.BezierCurve = BezierCurve;
  7313. /**
  7314. * Defines potential orientation for back face culling
  7315. */
  7316. var Orientation;
  7317. (function (Orientation) {
  7318. /**
  7319. * Clockwise
  7320. */
  7321. Orientation[Orientation["CW"] = 0] = "CW";
  7322. /** Counter clockwise */
  7323. Orientation[Orientation["CCW"] = 1] = "CCW";
  7324. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  7325. /**
  7326. * Defines angle representation
  7327. */
  7328. var Angle = /** @class */ (function () {
  7329. /**
  7330. * Creates an Angle object of "radians" radians (float).
  7331. */
  7332. function Angle(radians) {
  7333. this._radians = radians;
  7334. if (this._radians < 0.0) {
  7335. this._radians += (2.0 * Math.PI);
  7336. }
  7337. }
  7338. /**
  7339. * Get value in degrees
  7340. * @returns the Angle value in degrees (float)
  7341. */
  7342. Angle.prototype.degrees = function () {
  7343. return this._radians * 180.0 / Math.PI;
  7344. };
  7345. /**
  7346. * Get value in radians
  7347. * @returns the Angle value in radians (float)
  7348. */
  7349. Angle.prototype.radians = function () {
  7350. return this._radians;
  7351. };
  7352. /**
  7353. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  7354. * @param a defines first vector
  7355. * @param b defines second vector
  7356. * @returns a new Angle
  7357. */
  7358. Angle.BetweenTwoPoints = function (a, b) {
  7359. var delta = b.subtract(a);
  7360. var theta = Math.atan2(delta.y, delta.x);
  7361. return new Angle(theta);
  7362. };
  7363. /**
  7364. * Gets a new Angle object from the given float in radians
  7365. * @param radians defines the angle value in radians
  7366. * @returns a new Angle
  7367. */
  7368. Angle.FromRadians = function (radians) {
  7369. return new Angle(radians);
  7370. };
  7371. /**
  7372. * Gets a new Angle object from the given float in degrees
  7373. * @param degrees defines the angle value in degrees
  7374. * @returns a new Angle
  7375. */
  7376. Angle.FromDegrees = function (degrees) {
  7377. return new Angle(degrees * Math.PI / 180.0);
  7378. };
  7379. return Angle;
  7380. }());
  7381. BABYLON.Angle = Angle;
  7382. /**
  7383. * This represents an arc in a 2d space.
  7384. */
  7385. var Arc2 = /** @class */ (function () {
  7386. /**
  7387. * Creates an Arc object from the three given points : start, middle and end.
  7388. * @param startPoint Defines the start point of the arc
  7389. * @param midPoint Defines the midlle point of the arc
  7390. * @param endPoint Defines the end point of the arc
  7391. */
  7392. function Arc2(
  7393. /** Defines the start point of the arc */
  7394. startPoint,
  7395. /** Defines the mid point of the arc */
  7396. midPoint,
  7397. /** Defines the end point of the arc */
  7398. endPoint) {
  7399. this.startPoint = startPoint;
  7400. this.midPoint = midPoint;
  7401. this.endPoint = endPoint;
  7402. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  7403. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  7404. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  7405. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  7406. 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);
  7407. this.radius = this.centerPoint.subtract(this.startPoint).length();
  7408. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  7409. var a1 = this.startAngle.degrees();
  7410. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  7411. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  7412. // angles correction
  7413. if (a2 - a1 > +180.0) {
  7414. a2 -= 360.0;
  7415. }
  7416. if (a2 - a1 < -180.0) {
  7417. a2 += 360.0;
  7418. }
  7419. if (a3 - a2 > +180.0) {
  7420. a3 -= 360.0;
  7421. }
  7422. if (a3 - a2 < -180.0) {
  7423. a3 += 360.0;
  7424. }
  7425. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7426. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7427. }
  7428. return Arc2;
  7429. }());
  7430. BABYLON.Arc2 = Arc2;
  7431. /**
  7432. * Represents a 2D path made up of multiple 2D points
  7433. */
  7434. var Path2 = /** @class */ (function () {
  7435. /**
  7436. * Creates a Path2 object from the starting 2D coordinates x and y.
  7437. * @param x the starting points x value
  7438. * @param y the starting points y value
  7439. */
  7440. function Path2(x, y) {
  7441. this._points = new Array();
  7442. this._length = 0.0;
  7443. /**
  7444. * If the path start and end point are the same
  7445. */
  7446. this.closed = false;
  7447. this._points.push(new Vector2(x, y));
  7448. }
  7449. /**
  7450. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7451. * @param x the added points x value
  7452. * @param y the added points y value
  7453. * @returns the updated Path2.
  7454. */
  7455. Path2.prototype.addLineTo = function (x, y) {
  7456. if (this.closed) {
  7457. return this;
  7458. }
  7459. var newPoint = new Vector2(x, y);
  7460. var previousPoint = this._points[this._points.length - 1];
  7461. this._points.push(newPoint);
  7462. this._length += newPoint.subtract(previousPoint).length();
  7463. return this;
  7464. };
  7465. /**
  7466. * 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.
  7467. * @param midX middle point x value
  7468. * @param midY middle point y value
  7469. * @param endX end point x value
  7470. * @param endY end point y value
  7471. * @param numberOfSegments (default: 36)
  7472. * @returns the updated Path2.
  7473. */
  7474. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7475. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7476. if (this.closed) {
  7477. return this;
  7478. }
  7479. var startPoint = this._points[this._points.length - 1];
  7480. var midPoint = new Vector2(midX, midY);
  7481. var endPoint = new Vector2(endX, endY);
  7482. var arc = new Arc2(startPoint, midPoint, endPoint);
  7483. var increment = arc.angle.radians() / numberOfSegments;
  7484. if (arc.orientation === Orientation.CW) {
  7485. increment *= -1;
  7486. }
  7487. var currentAngle = arc.startAngle.radians() + increment;
  7488. for (var i = 0; i < numberOfSegments; i++) {
  7489. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7490. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7491. this.addLineTo(x, y);
  7492. currentAngle += increment;
  7493. }
  7494. return this;
  7495. };
  7496. /**
  7497. * Closes the Path2.
  7498. * @returns the Path2.
  7499. */
  7500. Path2.prototype.close = function () {
  7501. this.closed = true;
  7502. return this;
  7503. };
  7504. /**
  7505. * Gets the sum of the distance between each sequential point in the path
  7506. * @returns the Path2 total length (float).
  7507. */
  7508. Path2.prototype.length = function () {
  7509. var result = this._length;
  7510. if (!this.closed) {
  7511. var lastPoint = this._points[this._points.length - 1];
  7512. var firstPoint = this._points[0];
  7513. result += (firstPoint.subtract(lastPoint).length());
  7514. }
  7515. return result;
  7516. };
  7517. /**
  7518. * Gets the points which construct the path
  7519. * @returns the Path2 internal array of points.
  7520. */
  7521. Path2.prototype.getPoints = function () {
  7522. return this._points;
  7523. };
  7524. /**
  7525. * Retreives the point at the distance aways from the starting point
  7526. * @param normalizedLengthPosition the length along the path to retreive the point from
  7527. * @returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7528. */
  7529. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7530. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7531. return Vector2.Zero();
  7532. }
  7533. var lengthPosition = normalizedLengthPosition * this.length();
  7534. var previousOffset = 0;
  7535. for (var i = 0; i < this._points.length; i++) {
  7536. var j = (i + 1) % this._points.length;
  7537. var a = this._points[i];
  7538. var b = this._points[j];
  7539. var bToA = b.subtract(a);
  7540. var nextOffset = (bToA.length() + previousOffset);
  7541. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7542. var dir = bToA.normalize();
  7543. var localOffset = lengthPosition - previousOffset;
  7544. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7545. }
  7546. previousOffset = nextOffset;
  7547. }
  7548. return Vector2.Zero();
  7549. };
  7550. /**
  7551. * Creates a new path starting from an x and y position
  7552. * @param x starting x value
  7553. * @param y starting y value
  7554. * @returns a new Path2 starting at the coordinates (x, y).
  7555. */
  7556. Path2.StartingAt = function (x, y) {
  7557. return new Path2(x, y);
  7558. };
  7559. return Path2;
  7560. }());
  7561. BABYLON.Path2 = Path2;
  7562. /**
  7563. * Represents a 3D path made up of multiple 3D points
  7564. */
  7565. var Path3D = /** @class */ (function () {
  7566. /**
  7567. * new Path3D(path, normal, raw)
  7568. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7569. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7570. * @param path an array of Vector3, the curve axis of the Path3D
  7571. * @param normal (options) Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7572. * @param raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7573. */
  7574. function Path3D(
  7575. /**
  7576. * an array of Vector3, the curve axis of the Path3D
  7577. */
  7578. path, firstNormal, raw) {
  7579. if (firstNormal === void 0) { firstNormal = null; }
  7580. this.path = path;
  7581. this._curve = new Array();
  7582. this._distances = new Array();
  7583. this._tangents = new Array();
  7584. this._normals = new Array();
  7585. this._binormals = new Array();
  7586. for (var p = 0; p < path.length; p++) {
  7587. this._curve[p] = path[p].clone(); // hard copy
  7588. }
  7589. this._raw = raw || false;
  7590. this._compute(firstNormal);
  7591. }
  7592. /**
  7593. * Returns the Path3D array of successive Vector3 designing its curve.
  7594. * @returns the Path3D array of successive Vector3 designing its curve.
  7595. */
  7596. Path3D.prototype.getCurve = function () {
  7597. return this._curve;
  7598. };
  7599. /**
  7600. * Returns an array populated with tangent vectors on each Path3D curve point.
  7601. * @returns an array populated with tangent vectors on each Path3D curve point.
  7602. */
  7603. Path3D.prototype.getTangents = function () {
  7604. return this._tangents;
  7605. };
  7606. /**
  7607. * Returns an array populated with normal vectors on each Path3D curve point.
  7608. * @returns an array populated with normal vectors on each Path3D curve point.
  7609. */
  7610. Path3D.prototype.getNormals = function () {
  7611. return this._normals;
  7612. };
  7613. /**
  7614. * Returns an array populated with binormal vectors on each Path3D curve point.
  7615. * @returns an array populated with binormal vectors on each Path3D curve point.
  7616. */
  7617. Path3D.prototype.getBinormals = function () {
  7618. return this._binormals;
  7619. };
  7620. /**
  7621. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7622. * @returns an array populated with distances (float) of the i-th point from the first curve point.
  7623. */
  7624. Path3D.prototype.getDistances = function () {
  7625. return this._distances;
  7626. };
  7627. /**
  7628. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7629. * @param path path which all values are copied into the curves points
  7630. * @param firstNormal which should be projected onto the curve
  7631. * @returns the same object updated.
  7632. */
  7633. Path3D.prototype.update = function (path, firstNormal) {
  7634. if (firstNormal === void 0) { firstNormal = null; }
  7635. for (var p = 0; p < path.length; p++) {
  7636. this._curve[p].x = path[p].x;
  7637. this._curve[p].y = path[p].y;
  7638. this._curve[p].z = path[p].z;
  7639. }
  7640. this._compute(firstNormal);
  7641. return this;
  7642. };
  7643. // private function compute() : computes tangents, normals and binormals
  7644. Path3D.prototype._compute = function (firstNormal) {
  7645. var l = this._curve.length;
  7646. // first and last tangents
  7647. this._tangents[0] = this._getFirstNonNullVector(0);
  7648. if (!this._raw) {
  7649. this._tangents[0].normalize();
  7650. }
  7651. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7652. if (!this._raw) {
  7653. this._tangents[l - 1].normalize();
  7654. }
  7655. // normals and binormals at first point : arbitrary vector with _normalVector()
  7656. var tg0 = this._tangents[0];
  7657. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7658. this._normals[0] = pp0;
  7659. if (!this._raw) {
  7660. this._normals[0].normalize();
  7661. }
  7662. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7663. if (!this._raw) {
  7664. this._binormals[0].normalize();
  7665. }
  7666. this._distances[0] = 0.0;
  7667. // normals and binormals : next points
  7668. var prev; // previous vector (segment)
  7669. var cur; // current vector (segment)
  7670. var curTang; // current tangent
  7671. // previous normal
  7672. var prevBinor; // previous binormal
  7673. for (var i = 1; i < l; i++) {
  7674. // tangents
  7675. prev = this._getLastNonNullVector(i);
  7676. if (i < l - 1) {
  7677. cur = this._getFirstNonNullVector(i);
  7678. this._tangents[i] = prev.add(cur);
  7679. this._tangents[i].normalize();
  7680. }
  7681. this._distances[i] = this._distances[i - 1] + prev.length();
  7682. // normals and binormals
  7683. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7684. curTang = this._tangents[i];
  7685. prevBinor = this._binormals[i - 1];
  7686. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7687. if (!this._raw) {
  7688. this._normals[i].normalize();
  7689. }
  7690. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7691. if (!this._raw) {
  7692. this._binormals[i].normalize();
  7693. }
  7694. }
  7695. };
  7696. // private function getFirstNonNullVector(index)
  7697. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7698. Path3D.prototype._getFirstNonNullVector = function (index) {
  7699. var i = 1;
  7700. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7701. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7702. i++;
  7703. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7704. }
  7705. return nNVector;
  7706. };
  7707. // private function getLastNonNullVector(index)
  7708. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7709. Path3D.prototype._getLastNonNullVector = function (index) {
  7710. var i = 1;
  7711. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7712. while (nLVector.length() === 0 && index > i + 1) {
  7713. i++;
  7714. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7715. }
  7716. return nLVector;
  7717. };
  7718. // private function normalVector(v0, vt, va) :
  7719. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7720. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7721. Path3D.prototype._normalVector = function (v0, vt, va) {
  7722. var normal0;
  7723. var tgl = vt.length();
  7724. if (tgl === 0.0) {
  7725. tgl = 1.0;
  7726. }
  7727. if (va === undefined || va === null) {
  7728. var point;
  7729. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7730. point = new Vector3(0.0, -1.0, 0.0);
  7731. }
  7732. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7733. point = new Vector3(1.0, 0.0, 0.0);
  7734. }
  7735. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7736. point = new Vector3(0.0, 0.0, 1.0);
  7737. }
  7738. else {
  7739. point = Vector3.Zero();
  7740. }
  7741. normal0 = Vector3.Cross(vt, point);
  7742. }
  7743. else {
  7744. normal0 = Vector3.Cross(vt, va);
  7745. Vector3.CrossToRef(normal0, vt, normal0);
  7746. }
  7747. normal0.normalize();
  7748. return normal0;
  7749. };
  7750. return Path3D;
  7751. }());
  7752. BABYLON.Path3D = Path3D;
  7753. /**
  7754. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7755. * A Curve3 is designed from a series of successive Vector3.
  7756. * @see https://doc.babylonjs.com/how_to/how_to_use_curve3
  7757. */
  7758. var Curve3 = /** @class */ (function () {
  7759. /**
  7760. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7761. * A Curve3 is designed from a series of successive Vector3.
  7762. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7763. * @param points points which make up the curve
  7764. */
  7765. function Curve3(points) {
  7766. this._length = 0.0;
  7767. this._points = points;
  7768. this._length = this._computeLength(points);
  7769. }
  7770. /**
  7771. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7772. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7773. * @param v1 (Vector3) the control point
  7774. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7775. * @param nbPoints (integer) the wanted number of points in the curve
  7776. * @returns the created Curve3
  7777. */
  7778. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7779. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7780. var bez = new Array();
  7781. var equation = function (t, val0, val1, val2) {
  7782. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7783. return res;
  7784. };
  7785. for (var i = 0; i <= nbPoints; i++) {
  7786. 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)));
  7787. }
  7788. return new Curve3(bez);
  7789. };
  7790. /**
  7791. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7792. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7793. * @param v1 (Vector3) the first control point
  7794. * @param v2 (Vector3) the second control point
  7795. * @param v3 (Vector3) the end point of the Cubic Bezier
  7796. * @param nbPoints (integer) the wanted number of points in the curve
  7797. * @returns the created Curve3
  7798. */
  7799. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7800. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7801. var bez = new Array();
  7802. var equation = function (t, val0, val1, val2, val3) {
  7803. 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;
  7804. return res;
  7805. };
  7806. for (var i = 0; i <= nbPoints; i++) {
  7807. 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)));
  7808. }
  7809. return new Curve3(bez);
  7810. };
  7811. /**
  7812. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7813. * @param p1 (Vector3) the origin point of the Hermite Spline
  7814. * @param t1 (Vector3) the tangent vector at the origin point
  7815. * @param p2 (Vector3) the end point of the Hermite Spline
  7816. * @param t2 (Vector3) the tangent vector at the end point
  7817. * @param nbPoints (integer) the wanted number of points in the curve
  7818. * @returns the created Curve3
  7819. */
  7820. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7821. var hermite = new Array();
  7822. var step = 1.0 / nbPoints;
  7823. for (var i = 0; i <= nbPoints; i++) {
  7824. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7825. }
  7826. return new Curve3(hermite);
  7827. };
  7828. /**
  7829. * Returns a Curve3 object along a CatmullRom Spline curve :
  7830. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7831. * @param nbPoints (integer) the wanted number of points between each curve control points
  7832. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7833. * @returns the created Curve3
  7834. */
  7835. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7836. var catmullRom = new Array();
  7837. var step = 1.0 / nbPoints;
  7838. var amount = 0.0;
  7839. if (closed) {
  7840. var pointsCount = points.length;
  7841. for (var i = 0; i < pointsCount; i++) {
  7842. amount = 0;
  7843. for (var c = 0; c < nbPoints; c++) {
  7844. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7845. amount += step;
  7846. }
  7847. }
  7848. catmullRom.push(catmullRom[0]);
  7849. }
  7850. else {
  7851. var totalPoints = new Array();
  7852. totalPoints.push(points[0].clone());
  7853. Array.prototype.push.apply(totalPoints, points);
  7854. totalPoints.push(points[points.length - 1].clone());
  7855. for (var i = 0; i < totalPoints.length - 3; i++) {
  7856. amount = 0;
  7857. for (var c = 0; c < nbPoints; c++) {
  7858. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7859. amount += step;
  7860. }
  7861. }
  7862. i--;
  7863. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7864. }
  7865. return new Curve3(catmullRom);
  7866. };
  7867. /**
  7868. * @returns the Curve3 stored array of successive Vector3
  7869. */
  7870. Curve3.prototype.getPoints = function () {
  7871. return this._points;
  7872. };
  7873. /**
  7874. * @returns the computed length (float) of the curve.
  7875. */
  7876. Curve3.prototype.length = function () {
  7877. return this._length;
  7878. };
  7879. /**
  7880. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7881. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7882. * curveA and curveB keep unchanged.
  7883. * @param curve the curve to continue from this curve
  7884. * @returns the newly constructed curve
  7885. */
  7886. Curve3.prototype.continue = function (curve) {
  7887. var lastPoint = this._points[this._points.length - 1];
  7888. var continuedPoints = this._points.slice();
  7889. var curvePoints = curve.getPoints();
  7890. for (var i = 1; i < curvePoints.length; i++) {
  7891. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7892. }
  7893. var continuedCurve = new Curve3(continuedPoints);
  7894. return continuedCurve;
  7895. };
  7896. Curve3.prototype._computeLength = function (path) {
  7897. var l = 0;
  7898. for (var i = 1; i < path.length; i++) {
  7899. l += (path[i].subtract(path[i - 1])).length();
  7900. }
  7901. return l;
  7902. };
  7903. return Curve3;
  7904. }());
  7905. BABYLON.Curve3 = Curve3;
  7906. // Vertex formats
  7907. /**
  7908. * Contains position and normal vectors for a vertex
  7909. */
  7910. var PositionNormalVertex = /** @class */ (function () {
  7911. /**
  7912. * Creates a PositionNormalVertex
  7913. * @param position the position of the vertex (defaut: 0,0,0)
  7914. * @param normal the normal of the vertex (defaut: 0,1,0)
  7915. */
  7916. function PositionNormalVertex(
  7917. /** the position of the vertex (defaut: 0,0,0) */
  7918. position,
  7919. /** the normal of the vertex (defaut: 0,1,0) */
  7920. normal) {
  7921. if (position === void 0) { position = Vector3.Zero(); }
  7922. if (normal === void 0) { normal = Vector3.Up(); }
  7923. this.position = position;
  7924. this.normal = normal;
  7925. }
  7926. /**
  7927. * Clones the PositionNormalVertex
  7928. * @returns the cloned PositionNormalVertex
  7929. */
  7930. PositionNormalVertex.prototype.clone = function () {
  7931. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7932. };
  7933. return PositionNormalVertex;
  7934. }());
  7935. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7936. /**
  7937. * Contains position, normal and uv vectors for a vertex
  7938. */
  7939. var PositionNormalTextureVertex = /** @class */ (function () {
  7940. /**
  7941. * Creates a PositionNormalTextureVertex
  7942. * @param position the position of the vertex (defaut: 0,0,0)
  7943. * @param normal the normal of the vertex (defaut: 0,1,0)
  7944. * @param uv the uv of the vertex (default: 0,0)
  7945. */
  7946. function PositionNormalTextureVertex(
  7947. /** the position of the vertex (defaut: 0,0,0) */
  7948. position,
  7949. /** the normal of the vertex (defaut: 0,1,0) */
  7950. normal,
  7951. /** the uv of the vertex (default: 0,0) */
  7952. uv) {
  7953. if (position === void 0) { position = Vector3.Zero(); }
  7954. if (normal === void 0) { normal = Vector3.Up(); }
  7955. if (uv === void 0) { uv = Vector2.Zero(); }
  7956. this.position = position;
  7957. this.normal = normal;
  7958. this.uv = uv;
  7959. }
  7960. /**
  7961. * Clones the PositionNormalTextureVertex
  7962. * @returns the cloned PositionNormalTextureVertex
  7963. */
  7964. PositionNormalTextureVertex.prototype.clone = function () {
  7965. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7966. };
  7967. return PositionNormalTextureVertex;
  7968. }());
  7969. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7970. // Temporary pre-allocated objects for engine internal use
  7971. // usage in any internal function :
  7972. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7973. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7974. /**
  7975. * @hidden
  7976. */
  7977. var Tmp = /** @class */ (function () {
  7978. function Tmp() {
  7979. }
  7980. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7981. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7982. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7983. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7984. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7985. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7986. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7987. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7988. Matrix.Zero(), Matrix.Zero(),
  7989. Matrix.Zero(), Matrix.Zero(),
  7990. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7991. return Tmp;
  7992. }());
  7993. BABYLON.Tmp = Tmp;
  7994. /**
  7995. * @hidden
  7996. * Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7997. */
  7998. var MathTmp = /** @class */ (function () {
  7999. function MathTmp() {
  8000. }
  8001. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  8002. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  8003. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  8004. return MathTmp;
  8005. }());
  8006. })(BABYLON || (BABYLON = {}));
  8007. //# sourceMappingURL=babylon.math.js.map
  8008. var BABYLON;
  8009. (function (BABYLON) {
  8010. /**
  8011. * Scalar computation library
  8012. */
  8013. var Scalar = /** @class */ (function () {
  8014. function Scalar() {
  8015. }
  8016. /**
  8017. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  8018. * @param a number
  8019. * @param b number
  8020. * @param epsilon (default = 1.401298E-45)
  8021. * @returns true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  8022. */
  8023. Scalar.WithinEpsilon = function (a, b, epsilon) {
  8024. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  8025. var num = a - b;
  8026. return -epsilon <= num && num <= epsilon;
  8027. };
  8028. /**
  8029. * Returns a string : the upper case translation of the number i to hexadecimal.
  8030. * @param i number
  8031. * @returns the upper case translation of the number i to hexadecimal.
  8032. */
  8033. Scalar.ToHex = function (i) {
  8034. var str = i.toString(16);
  8035. if (i <= 15) {
  8036. return ("0" + str).toUpperCase();
  8037. }
  8038. return str.toUpperCase();
  8039. };
  8040. /**
  8041. * Returns -1 if value is negative and +1 is value is positive.
  8042. * @param value the value
  8043. * @returns the value itself if it's equal to zero.
  8044. */
  8045. Scalar.Sign = function (value) {
  8046. value = +value; // convert to a number
  8047. if (value === 0 || isNaN(value)) {
  8048. return value;
  8049. }
  8050. return value > 0 ? 1 : -1;
  8051. };
  8052. /**
  8053. * Returns the value itself if it's between min and max.
  8054. * Returns min if the value is lower than min.
  8055. * Returns max if the value is greater than max.
  8056. * @param value the value to clmap
  8057. * @param min the min value to clamp to (default: 0)
  8058. * @param max the max value to clamp to (default: 1)
  8059. * @returns the clamped value
  8060. */
  8061. Scalar.Clamp = function (value, min, max) {
  8062. if (min === void 0) { min = 0; }
  8063. if (max === void 0) { max = 1; }
  8064. return Math.min(max, Math.max(min, value));
  8065. };
  8066. /**
  8067. * the log2 of value.
  8068. * @param value the value to compute log2 of
  8069. * @returns the log2 of value.
  8070. */
  8071. Scalar.Log2 = function (value) {
  8072. return Math.log(value) * Math.LOG2E;
  8073. };
  8074. /**
  8075. * Loops the value, so that it is never larger than length and never smaller than 0.
  8076. *
  8077. * This is similar to the modulo operator but it works with floating point numbers.
  8078. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  8079. * With t = 5 and length = 2.5, the result would be 0.0.
  8080. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  8081. * @param value the value
  8082. * @param length the length
  8083. * @returns the looped value
  8084. */
  8085. Scalar.Repeat = function (value, length) {
  8086. return value - Math.floor(value / length) * length;
  8087. };
  8088. /**
  8089. * Normalize the value between 0.0 and 1.0 using min and max values
  8090. * @param value value to normalize
  8091. * @param min max to normalize between
  8092. * @param max min to normalize between
  8093. * @returns the normalized value
  8094. */
  8095. Scalar.Normalize = function (value, min, max) {
  8096. return (value - min) / (max - min);
  8097. };
  8098. /**
  8099. * Denormalize the value from 0.0 and 1.0 using min and max values
  8100. * @param normalized value to denormalize
  8101. * @param min max to denormalize between
  8102. * @param max min to denormalize between
  8103. * @returns the denormalized value
  8104. */
  8105. Scalar.Denormalize = function (normalized, min, max) {
  8106. return (normalized * (max - min) + min);
  8107. };
  8108. /**
  8109. * Calculates the shortest difference between two given angles given in degrees.
  8110. * @param current current angle in degrees
  8111. * @param target target angle in degrees
  8112. * @returns the delta
  8113. */
  8114. Scalar.DeltaAngle = function (current, target) {
  8115. var num = Scalar.Repeat(target - current, 360.0);
  8116. if (num > 180.0) {
  8117. num -= 360.0;
  8118. }
  8119. return num;
  8120. };
  8121. /**
  8122. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  8123. * @param tx value
  8124. * @param length length
  8125. * @returns The returned value will move back and forth between 0 and length
  8126. */
  8127. Scalar.PingPong = function (tx, length) {
  8128. var t = Scalar.Repeat(tx, length * 2.0);
  8129. return length - Math.abs(t - length);
  8130. };
  8131. /**
  8132. * Interpolates between min and max with smoothing at the limits.
  8133. *
  8134. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  8135. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  8136. * @param from from
  8137. * @param to to
  8138. * @param tx value
  8139. * @returns the smooth stepped value
  8140. */
  8141. Scalar.SmoothStep = function (from, to, tx) {
  8142. var t = Scalar.Clamp(tx);
  8143. t = -2.0 * t * t * t + 3.0 * t * t;
  8144. return to * t + from * (1.0 - t);
  8145. };
  8146. /**
  8147. * Moves a value current towards target.
  8148. *
  8149. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  8150. * Negative values of maxDelta pushes the value away from target.
  8151. * @param current current value
  8152. * @param target target value
  8153. * @param maxDelta max distance to move
  8154. * @returns resulting value
  8155. */
  8156. Scalar.MoveTowards = function (current, target, maxDelta) {
  8157. var result = 0;
  8158. if (Math.abs(target - current) <= maxDelta) {
  8159. result = target;
  8160. }
  8161. else {
  8162. result = current + Scalar.Sign(target - current) * maxDelta;
  8163. }
  8164. return result;
  8165. };
  8166. /**
  8167. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  8168. *
  8169. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  8170. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  8171. * @param current current value
  8172. * @param target target value
  8173. * @param maxDelta max distance to move
  8174. * @returns resulting angle
  8175. */
  8176. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  8177. var num = Scalar.DeltaAngle(current, target);
  8178. var result = 0;
  8179. if (-maxDelta < num && num < maxDelta) {
  8180. result = target;
  8181. }
  8182. else {
  8183. target = current + num;
  8184. result = Scalar.MoveTowards(current, target, maxDelta);
  8185. }
  8186. return result;
  8187. };
  8188. /**
  8189. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  8190. * @param start start value
  8191. * @param end target value
  8192. * @param amount amount to lerp between
  8193. * @returns the lerped value
  8194. */
  8195. Scalar.Lerp = function (start, end, amount) {
  8196. return start + ((end - start) * amount);
  8197. };
  8198. /**
  8199. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  8200. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  8201. * @param start start value
  8202. * @param end target value
  8203. * @param amount amount to lerp between
  8204. * @returns the lerped value
  8205. */
  8206. Scalar.LerpAngle = function (start, end, amount) {
  8207. var num = Scalar.Repeat(end - start, 360.0);
  8208. if (num > 180.0) {
  8209. num -= 360.0;
  8210. }
  8211. return start + num * Scalar.Clamp(amount);
  8212. };
  8213. /**
  8214. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  8215. * @param a start value
  8216. * @param b target value
  8217. * @param value value between a and b
  8218. * @returns the inverseLerp value
  8219. */
  8220. Scalar.InverseLerp = function (a, b, value) {
  8221. var result = 0;
  8222. if (a != b) {
  8223. result = Scalar.Clamp((value - a) / (b - a));
  8224. }
  8225. else {
  8226. result = 0.0;
  8227. }
  8228. return result;
  8229. };
  8230. /**
  8231. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  8232. * @see http://mathworld.wolfram.com/HermitePolynomial.html
  8233. * @param value1 spline value
  8234. * @param tangent1 spline value
  8235. * @param value2 spline value
  8236. * @param tangent2 spline value
  8237. * @param amount input value
  8238. * @returns hermite result
  8239. */
  8240. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  8241. var squared = amount * amount;
  8242. var cubed = amount * squared;
  8243. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  8244. var part2 = (-2.0 * cubed) + (3.0 * squared);
  8245. var part3 = (cubed - (2.0 * squared)) + amount;
  8246. var part4 = cubed - squared;
  8247. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  8248. };
  8249. /**
  8250. * Returns a random float number between and min and max values
  8251. * @param min min value of random
  8252. * @param max max value of random
  8253. * @returns random value
  8254. */
  8255. Scalar.RandomRange = function (min, max) {
  8256. if (min === max) {
  8257. return min;
  8258. }
  8259. return ((Math.random() * (max - min)) + min);
  8260. };
  8261. /**
  8262. * This function returns percentage of a number in a given range.
  8263. *
  8264. * RangeToPercent(40,20,60) will return 0.5 (50%)
  8265. * RangeToPercent(34,0,100) will return 0.34 (34%)
  8266. * @param number to convert to percentage
  8267. * @param min min range
  8268. * @param max max range
  8269. * @returns the percentage
  8270. */
  8271. Scalar.RangeToPercent = function (number, min, max) {
  8272. return ((number - min) / (max - min));
  8273. };
  8274. /**
  8275. * This function returns number that corresponds to the percentage in a given range.
  8276. *
  8277. * PercentToRange(0.34,0,100) will return 34.
  8278. * @param percent to convert to number
  8279. * @param min min range
  8280. * @param max max range
  8281. * @returns the number
  8282. */
  8283. Scalar.PercentToRange = function (percent, min, max) {
  8284. return ((max - min) * percent + min);
  8285. };
  8286. /**
  8287. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  8288. * @param angle The angle to normalize in radian.
  8289. * @return The converted angle.
  8290. */
  8291. Scalar.NormalizeRadians = function (angle) {
  8292. // More precise but slower version kept for reference.
  8293. // angle = angle % Tools.TwoPi;
  8294. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  8295. //if (angle > Math.PI) {
  8296. // angle -= Tools.TwoPi;
  8297. //}
  8298. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  8299. return angle;
  8300. };
  8301. /**
  8302. * Two pi constants convenient for computation.
  8303. */
  8304. Scalar.TwoPi = Math.PI * 2;
  8305. return Scalar;
  8306. }());
  8307. BABYLON.Scalar = Scalar;
  8308. })(BABYLON || (BABYLON = {}));
  8309. //# sourceMappingURL=babylon.math.scalar.js.map
  8310. //# sourceMappingURL=babylon.mixins.js.map
  8311. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  8312. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  8313. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  8314. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  8315. //# sourceMappingURL=babylon.webgl2.js.map
  8316. var BABYLON;
  8317. (function (BABYLON) {
  8318. var __decoratorInitialStore = {};
  8319. var __mergedStore = {};
  8320. var _copySource = function (creationFunction, source, instanciate) {
  8321. var destination = creationFunction();
  8322. // Tags
  8323. if (BABYLON.Tags) {
  8324. BABYLON.Tags.AddTagsTo(destination, source.tags);
  8325. }
  8326. var classStore = getMergedStore(destination);
  8327. // Properties
  8328. for (var property in classStore) {
  8329. var propertyDescriptor = classStore[property];
  8330. var sourceProperty = source[property];
  8331. var propertyType = propertyDescriptor.type;
  8332. if (sourceProperty !== undefined && sourceProperty !== null) {
  8333. switch (propertyType) {
  8334. case 0: // Value
  8335. case 6: // Mesh reference
  8336. case 11: // Camera reference
  8337. destination[property] = sourceProperty;
  8338. break;
  8339. case 1: // Texture
  8340. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  8341. break;
  8342. case 2: // Color3
  8343. case 3: // FresnelParameters
  8344. case 4: // Vector2
  8345. case 5: // Vector3
  8346. case 7: // Color Curves
  8347. case 10: // Quaternion
  8348. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  8349. break;
  8350. }
  8351. }
  8352. }
  8353. return destination;
  8354. };
  8355. function getDirectStore(target) {
  8356. var classKey = target.getClassName();
  8357. if (!__decoratorInitialStore[classKey]) {
  8358. __decoratorInitialStore[classKey] = {};
  8359. }
  8360. return __decoratorInitialStore[classKey];
  8361. }
  8362. /**
  8363. * Return the list of properties flagged as serializable
  8364. * @param target: host object
  8365. */
  8366. function getMergedStore(target) {
  8367. var classKey = target.getClassName();
  8368. if (__mergedStore[classKey]) {
  8369. return __mergedStore[classKey];
  8370. }
  8371. __mergedStore[classKey] = {};
  8372. var store = __mergedStore[classKey];
  8373. var currentTarget = target;
  8374. var currentKey = classKey;
  8375. while (currentKey) {
  8376. var initialStore = __decoratorInitialStore[currentKey];
  8377. for (var property in initialStore) {
  8378. store[property] = initialStore[property];
  8379. }
  8380. var parent_1 = void 0;
  8381. var done = false;
  8382. do {
  8383. parent_1 = Object.getPrototypeOf(currentTarget);
  8384. if (!parent_1.getClassName) {
  8385. done = true;
  8386. break;
  8387. }
  8388. if (parent_1.getClassName() !== currentKey) {
  8389. break;
  8390. }
  8391. currentTarget = parent_1;
  8392. } while (parent_1);
  8393. if (done) {
  8394. break;
  8395. }
  8396. currentKey = parent_1.getClassName();
  8397. currentTarget = parent_1;
  8398. }
  8399. return store;
  8400. }
  8401. function generateSerializableMember(type, sourceName) {
  8402. return function (target, propertyKey) {
  8403. var classStore = getDirectStore(target);
  8404. if (!classStore[propertyKey]) {
  8405. classStore[propertyKey] = { type: type, sourceName: sourceName };
  8406. }
  8407. };
  8408. }
  8409. function generateExpandMember(setCallback, targetKey) {
  8410. if (targetKey === void 0) { targetKey = null; }
  8411. return function (target, propertyKey) {
  8412. var key = targetKey || ("_" + propertyKey);
  8413. Object.defineProperty(target, propertyKey, {
  8414. get: function () {
  8415. return this[key];
  8416. },
  8417. set: function (value) {
  8418. if (this[key] === value) {
  8419. return;
  8420. }
  8421. this[key] = value;
  8422. target[setCallback].apply(this);
  8423. },
  8424. enumerable: true,
  8425. configurable: true
  8426. });
  8427. };
  8428. }
  8429. function expandToProperty(callback, targetKey) {
  8430. if (targetKey === void 0) { targetKey = null; }
  8431. return generateExpandMember(callback, targetKey);
  8432. }
  8433. BABYLON.expandToProperty = expandToProperty;
  8434. function serialize(sourceName) {
  8435. return generateSerializableMember(0, sourceName); // value member
  8436. }
  8437. BABYLON.serialize = serialize;
  8438. function serializeAsTexture(sourceName) {
  8439. return generateSerializableMember(1, sourceName); // texture member
  8440. }
  8441. BABYLON.serializeAsTexture = serializeAsTexture;
  8442. function serializeAsColor3(sourceName) {
  8443. return generateSerializableMember(2, sourceName); // color3 member
  8444. }
  8445. BABYLON.serializeAsColor3 = serializeAsColor3;
  8446. function serializeAsFresnelParameters(sourceName) {
  8447. return generateSerializableMember(3, sourceName); // fresnel parameters member
  8448. }
  8449. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  8450. function serializeAsVector2(sourceName) {
  8451. return generateSerializableMember(4, sourceName); // vector2 member
  8452. }
  8453. BABYLON.serializeAsVector2 = serializeAsVector2;
  8454. function serializeAsVector3(sourceName) {
  8455. return generateSerializableMember(5, sourceName); // vector3 member
  8456. }
  8457. BABYLON.serializeAsVector3 = serializeAsVector3;
  8458. function serializeAsMeshReference(sourceName) {
  8459. return generateSerializableMember(6, sourceName); // mesh reference member
  8460. }
  8461. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  8462. function serializeAsColorCurves(sourceName) {
  8463. return generateSerializableMember(7, sourceName); // color curves
  8464. }
  8465. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  8466. function serializeAsColor4(sourceName) {
  8467. return generateSerializableMember(8, sourceName); // color 4
  8468. }
  8469. BABYLON.serializeAsColor4 = serializeAsColor4;
  8470. function serializeAsImageProcessingConfiguration(sourceName) {
  8471. return generateSerializableMember(9, sourceName); // image processing
  8472. }
  8473. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  8474. function serializeAsQuaternion(sourceName) {
  8475. return generateSerializableMember(10, sourceName); // quaternion member
  8476. }
  8477. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  8478. /**
  8479. * Decorator used to define property that can be serialized as reference to a camera
  8480. * @param sourceName defines the name of the property to decorate
  8481. */
  8482. function serializeAsCameraReference(sourceName) {
  8483. return generateSerializableMember(11, sourceName); // camera reference member
  8484. }
  8485. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  8486. /**
  8487. * Class used to help serialization objects
  8488. */
  8489. var SerializationHelper = /** @class */ (function () {
  8490. function SerializationHelper() {
  8491. }
  8492. /**
  8493. * Static function used to serialized a specific entity
  8494. * @param entity defines the entity to serialize
  8495. * @param serializationObject defines the optional target obecjt where serialization data will be stored
  8496. * @returns a JSON compatible object representing the serialization of the entity
  8497. */
  8498. SerializationHelper.Serialize = function (entity, serializationObject) {
  8499. if (!serializationObject) {
  8500. serializationObject = {};
  8501. }
  8502. // Tags
  8503. if (BABYLON.Tags) {
  8504. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  8505. }
  8506. var serializedProperties = getMergedStore(entity);
  8507. // Properties
  8508. for (var property in serializedProperties) {
  8509. var propertyDescriptor = serializedProperties[property];
  8510. var targetPropertyName = propertyDescriptor.sourceName || property;
  8511. var propertyType = propertyDescriptor.type;
  8512. var sourceProperty = entity[property];
  8513. if (sourceProperty !== undefined && sourceProperty !== null) {
  8514. switch (propertyType) {
  8515. case 0: // Value
  8516. serializationObject[targetPropertyName] = sourceProperty;
  8517. break;
  8518. case 1: // Texture
  8519. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8520. break;
  8521. case 2: // Color3
  8522. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8523. break;
  8524. case 3: // FresnelParameters
  8525. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8526. break;
  8527. case 4: // Vector2
  8528. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8529. break;
  8530. case 5: // Vector3
  8531. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8532. break;
  8533. case 6: // Mesh reference
  8534. serializationObject[targetPropertyName] = sourceProperty.id;
  8535. break;
  8536. case 7: // Color Curves
  8537. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8538. break;
  8539. case 8: // Color 4
  8540. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8541. break;
  8542. case 9: // Image Processing
  8543. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8544. break;
  8545. case 10: // Quaternion
  8546. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8547. break;
  8548. case 11: // Camera reference
  8549. serializationObject[targetPropertyName] = sourceProperty.id;
  8550. break;
  8551. }
  8552. }
  8553. }
  8554. return serializationObject;
  8555. };
  8556. /**
  8557. * Creates a new entity from a serialization data object
  8558. * @param creationFunction defines a function used to instanciated the new entity
  8559. * @param source defines the source serialization data
  8560. * @param scene defines the hosting scene
  8561. * @param rootUrl defines the root url for resources
  8562. * @returns a new entity
  8563. */
  8564. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  8565. if (rootUrl === void 0) { rootUrl = null; }
  8566. var destination = creationFunction();
  8567. if (!rootUrl) {
  8568. rootUrl = "";
  8569. }
  8570. // Tags
  8571. if (BABYLON.Tags) {
  8572. BABYLON.Tags.AddTagsTo(destination, source.tags);
  8573. }
  8574. var classStore = getMergedStore(destination);
  8575. // Properties
  8576. for (var property in classStore) {
  8577. var propertyDescriptor = classStore[property];
  8578. var sourceProperty = source[propertyDescriptor.sourceName || property];
  8579. var propertyType = propertyDescriptor.type;
  8580. if (sourceProperty !== undefined && sourceProperty !== null) {
  8581. var dest = destination;
  8582. switch (propertyType) {
  8583. case 0: // Value
  8584. dest[property] = sourceProperty;
  8585. break;
  8586. case 1: // Texture
  8587. if (scene) {
  8588. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  8589. }
  8590. break;
  8591. case 2: // Color3
  8592. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  8593. break;
  8594. case 3: // FresnelParameters
  8595. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  8596. break;
  8597. case 4: // Vector2
  8598. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  8599. break;
  8600. case 5: // Vector3
  8601. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  8602. break;
  8603. case 6: // Mesh reference
  8604. if (scene) {
  8605. dest[property] = scene.getLastMeshByID(sourceProperty);
  8606. }
  8607. break;
  8608. case 7: // Color Curves
  8609. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8610. break;
  8611. case 8: // Color 4
  8612. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8613. break;
  8614. case 9: // Image Processing
  8615. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8616. break;
  8617. case 10: // Quaternion
  8618. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8619. break;
  8620. case 11: // Camera reference
  8621. if (scene) {
  8622. dest[property] = scene.getCameraByID(sourceProperty);
  8623. }
  8624. break;
  8625. }
  8626. }
  8627. }
  8628. return destination;
  8629. };
  8630. /**
  8631. * Clones an object
  8632. * @param creationFunction defines the function used to instanciate the new object
  8633. * @param source defines the source object
  8634. * @returns the cloned object
  8635. */
  8636. SerializationHelper.Clone = function (creationFunction, source) {
  8637. return _copySource(creationFunction, source, false);
  8638. };
  8639. /**
  8640. * Instanciates a new object based on a source one (some data will be shared between both object)
  8641. * @param creationFunction defines the function used to instanciate the new object
  8642. * @param source defines the source object
  8643. * @returns the new object
  8644. */
  8645. SerializationHelper.Instanciate = function (creationFunction, source) {
  8646. return _copySource(creationFunction, source, true);
  8647. };
  8648. return SerializationHelper;
  8649. }());
  8650. BABYLON.SerializationHelper = SerializationHelper;
  8651. })(BABYLON || (BABYLON = {}));
  8652. //# sourceMappingURL=babylon.decorators.js.map
  8653. var BABYLON;
  8654. (function (BABYLON) {
  8655. /**
  8656. * Wrapper class for promise with external resolve and reject.
  8657. */
  8658. var Deferred = /** @class */ (function () {
  8659. /**
  8660. * Constructor for this deferred object.
  8661. */
  8662. function Deferred() {
  8663. var _this = this;
  8664. this.promise = new Promise(function (resolve, reject) {
  8665. _this._resolve = resolve;
  8666. _this._reject = reject;
  8667. });
  8668. }
  8669. Object.defineProperty(Deferred.prototype, "resolve", {
  8670. /**
  8671. * The resolve method of the promise associated with this deferred object.
  8672. */
  8673. get: function () {
  8674. return this._resolve;
  8675. },
  8676. enumerable: true,
  8677. configurable: true
  8678. });
  8679. Object.defineProperty(Deferred.prototype, "reject", {
  8680. /**
  8681. * The reject method of the promise associated with this deferred object.
  8682. */
  8683. get: function () {
  8684. return this._reject;
  8685. },
  8686. enumerable: true,
  8687. configurable: true
  8688. });
  8689. return Deferred;
  8690. }());
  8691. BABYLON.Deferred = Deferred;
  8692. })(BABYLON || (BABYLON = {}));
  8693. //# sourceMappingURL=babylon.deferred.js.map
  8694. var BABYLON;
  8695. (function (BABYLON) {
  8696. /**
  8697. * A class serves as a medium between the observable and its observers
  8698. */
  8699. var EventState = /** @class */ (function () {
  8700. /**
  8701. * Create a new EventState
  8702. * @param mask defines the mask associated with this state
  8703. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8704. * @param target defines the original target of the state
  8705. * @param currentTarget defines the current target of the state
  8706. */
  8707. function EventState(mask, skipNextObservers, target, currentTarget) {
  8708. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8709. this.initalize(mask, skipNextObservers, target, currentTarget);
  8710. }
  8711. /**
  8712. * Initialize the current event state
  8713. * @param mask defines the mask associated with this state
  8714. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8715. * @param target defines the original target of the state
  8716. * @param currentTarget defines the current target of the state
  8717. * @returns the current event state
  8718. */
  8719. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8720. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8721. this.mask = mask;
  8722. this.skipNextObservers = skipNextObservers;
  8723. this.target = target;
  8724. this.currentTarget = currentTarget;
  8725. return this;
  8726. };
  8727. return EventState;
  8728. }());
  8729. BABYLON.EventState = EventState;
  8730. /**
  8731. * Represent an Observer registered to a given Observable object.
  8732. */
  8733. var Observer = /** @class */ (function () {
  8734. /**
  8735. * Creates a new observer
  8736. * @param callback defines the callback to call when the observer is notified
  8737. * @param mask defines the mask of the observer (used to filter notifications)
  8738. * @param scope defines the current scope used to restore the JS context
  8739. */
  8740. function Observer(
  8741. /**
  8742. * Defines the callback to call when the observer is notified
  8743. */
  8744. callback,
  8745. /**
  8746. * Defines the mask of the observer (used to filter notifications)
  8747. */
  8748. mask,
  8749. /**
  8750. * Defines the current scope used to restore the JS context
  8751. */
  8752. scope) {
  8753. if (scope === void 0) { scope = null; }
  8754. this.callback = callback;
  8755. this.mask = mask;
  8756. this.scope = scope;
  8757. /** @hidden */
  8758. this._willBeUnregistered = false;
  8759. /**
  8760. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8761. */
  8762. this.unregisterOnNextCall = false;
  8763. }
  8764. return Observer;
  8765. }());
  8766. BABYLON.Observer = Observer;
  8767. /**
  8768. * Represent a list of observers registered to multiple Observables object.
  8769. */
  8770. var MultiObserver = /** @class */ (function () {
  8771. function MultiObserver() {
  8772. }
  8773. /**
  8774. * Release associated resources
  8775. */
  8776. MultiObserver.prototype.dispose = function () {
  8777. if (this._observers && this._observables) {
  8778. for (var index = 0; index < this._observers.length; index++) {
  8779. this._observables[index].remove(this._observers[index]);
  8780. }
  8781. }
  8782. this._observers = null;
  8783. this._observables = null;
  8784. };
  8785. /**
  8786. * Raise a callback when one of the observable will notify
  8787. * @param observables defines a list of observables to watch
  8788. * @param callback defines the callback to call on notification
  8789. * @param mask defines the mask used to filter notifications
  8790. * @param scope defines the current scope used to restore the JS context
  8791. * @returns the new MultiObserver
  8792. */
  8793. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8794. if (mask === void 0) { mask = -1; }
  8795. if (scope === void 0) { scope = null; }
  8796. var result = new MultiObserver();
  8797. result._observers = new Array();
  8798. result._observables = observables;
  8799. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8800. var observable = observables_1[_i];
  8801. var observer = observable.add(callback, mask, false, scope);
  8802. if (observer) {
  8803. result._observers.push(observer);
  8804. }
  8805. }
  8806. return result;
  8807. };
  8808. return MultiObserver;
  8809. }());
  8810. BABYLON.MultiObserver = MultiObserver;
  8811. /**
  8812. * The Observable class is a simple implementation of the Observable pattern.
  8813. *
  8814. * 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.
  8815. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8816. * 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).
  8817. * 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.
  8818. */
  8819. var Observable = /** @class */ (function () {
  8820. /**
  8821. * Creates a new observable
  8822. * @param onObserverAdded defines a callback to call when a new observer is added
  8823. */
  8824. function Observable(onObserverAdded) {
  8825. this._observers = new Array();
  8826. this._eventState = new EventState(0);
  8827. if (onObserverAdded) {
  8828. this._onObserverAdded = onObserverAdded;
  8829. }
  8830. }
  8831. /**
  8832. * Create a new Observer with the specified callback
  8833. * @param callback the callback that will be executed for that Observer
  8834. * @param mask the mask used to filter observers
  8835. * @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.
  8836. * @param scope optional scope for the callback to be called from
  8837. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8838. * @returns the new observer created for the callback
  8839. */
  8840. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8841. if (mask === void 0) { mask = -1; }
  8842. if (insertFirst === void 0) { insertFirst = false; }
  8843. if (scope === void 0) { scope = null; }
  8844. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8845. if (!callback) {
  8846. return null;
  8847. }
  8848. var observer = new Observer(callback, mask, scope);
  8849. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8850. if (insertFirst) {
  8851. this._observers.unshift(observer);
  8852. }
  8853. else {
  8854. this._observers.push(observer);
  8855. }
  8856. if (this._onObserverAdded) {
  8857. this._onObserverAdded(observer);
  8858. }
  8859. return observer;
  8860. };
  8861. /**
  8862. * Create a new Observer with the specified callback and unregisters after the next notification
  8863. * @param callback the callback that will be executed for that Observer
  8864. * @returns the new observer created for the callback
  8865. */
  8866. Observable.prototype.addOnce = function (callback) {
  8867. return this.add(callback, undefined, undefined, undefined, true);
  8868. };
  8869. /**
  8870. * Remove an Observer from the Observable object
  8871. * @param observer the instance of the Observer to remove
  8872. * @returns false if it doesn't belong to this Observable
  8873. */
  8874. Observable.prototype.remove = function (observer) {
  8875. if (!observer) {
  8876. return false;
  8877. }
  8878. var index = this._observers.indexOf(observer);
  8879. if (index !== -1) {
  8880. this._deferUnregister(observer);
  8881. return true;
  8882. }
  8883. return false;
  8884. };
  8885. /**
  8886. * Remove a callback from the Observable object
  8887. * @param callback the callback to remove
  8888. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8889. * @returns false if it doesn't belong to this Observable
  8890. */
  8891. Observable.prototype.removeCallback = function (callback, scope) {
  8892. for (var index = 0; index < this._observers.length; index++) {
  8893. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8894. this._deferUnregister(this._observers[index]);
  8895. return true;
  8896. }
  8897. }
  8898. return false;
  8899. };
  8900. Observable.prototype._deferUnregister = function (observer) {
  8901. var _this = this;
  8902. observer.unregisterOnNextCall = false;
  8903. observer._willBeUnregistered = true;
  8904. BABYLON.Tools.SetImmediate(function () {
  8905. _this._remove(observer);
  8906. });
  8907. };
  8908. // This should only be called when not iterating over _observers to avoid callback skipping.
  8909. // Removes an observer from the _observer Array.
  8910. Observable.prototype._remove = function (observer) {
  8911. if (!observer) {
  8912. return false;
  8913. }
  8914. var index = this._observers.indexOf(observer);
  8915. if (index !== -1) {
  8916. this._observers.splice(index, 1);
  8917. return true;
  8918. }
  8919. return false;
  8920. };
  8921. /**
  8922. * Notify all Observers by calling their respective callback with the given data
  8923. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8924. * @param eventData defines the data to send to all observers
  8925. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8926. * @param target defines the original target of the state
  8927. * @param currentTarget defines the current target of the state
  8928. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8929. */
  8930. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8931. if (mask === void 0) { mask = -1; }
  8932. if (!this._observers.length) {
  8933. return true;
  8934. }
  8935. var state = this._eventState;
  8936. state.mask = mask;
  8937. state.target = target;
  8938. state.currentTarget = currentTarget;
  8939. state.skipNextObservers = false;
  8940. state.lastReturnValue = eventData;
  8941. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8942. var obs = _a[_i];
  8943. if (obs._willBeUnregistered) {
  8944. continue;
  8945. }
  8946. if (obs.mask & mask) {
  8947. if (obs.scope) {
  8948. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8949. }
  8950. else {
  8951. state.lastReturnValue = obs.callback(eventData, state);
  8952. }
  8953. if (obs.unregisterOnNextCall) {
  8954. this._deferUnregister(obs);
  8955. }
  8956. }
  8957. if (state.skipNextObservers) {
  8958. return false;
  8959. }
  8960. }
  8961. return true;
  8962. };
  8963. /**
  8964. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8965. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8966. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8967. * and it is crucial that all callbacks will be executed.
  8968. * The order of the callbacks is kept, callbacks are not executed parallel.
  8969. *
  8970. * @param eventData The data to be sent to each callback
  8971. * @param mask is used to filter observers defaults to -1
  8972. * @param target defines the callback target (see EventState)
  8973. * @param currentTarget defines he current object in the bubbling phase
  8974. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8975. */
  8976. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8977. var _this = this;
  8978. if (mask === void 0) { mask = -1; }
  8979. // create an empty promise
  8980. var p = Promise.resolve(eventData);
  8981. // no observers? return this promise.
  8982. if (!this._observers.length) {
  8983. return p;
  8984. }
  8985. var state = this._eventState;
  8986. state.mask = mask;
  8987. state.target = target;
  8988. state.currentTarget = currentTarget;
  8989. state.skipNextObservers = false;
  8990. // execute one callback after another (not using Promise.all, the order is important)
  8991. this._observers.forEach(function (obs) {
  8992. if (state.skipNextObservers) {
  8993. return;
  8994. }
  8995. if (obs._willBeUnregistered) {
  8996. return;
  8997. }
  8998. if (obs.mask & mask) {
  8999. if (obs.scope) {
  9000. p = p.then(function (lastReturnedValue) {
  9001. state.lastReturnValue = lastReturnedValue;
  9002. return obs.callback.apply(obs.scope, [eventData, state]);
  9003. });
  9004. }
  9005. else {
  9006. p = p.then(function (lastReturnedValue) {
  9007. state.lastReturnValue = lastReturnedValue;
  9008. return obs.callback(eventData, state);
  9009. });
  9010. }
  9011. if (obs.unregisterOnNextCall) {
  9012. _this._deferUnregister(obs);
  9013. }
  9014. }
  9015. });
  9016. // return the eventData
  9017. return p.then(function () { return eventData; });
  9018. };
  9019. /**
  9020. * Notify a specific observer
  9021. * @param observer defines the observer to notify
  9022. * @param eventData defines the data to be sent to each callback
  9023. * @param mask is used to filter observers defaults to -1
  9024. */
  9025. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  9026. if (mask === void 0) { mask = -1; }
  9027. var state = this._eventState;
  9028. state.mask = mask;
  9029. state.skipNextObservers = false;
  9030. observer.callback(eventData, state);
  9031. };
  9032. /**
  9033. * Gets a boolean indicating if the observable has at least one observer
  9034. * @returns true is the Observable has at least one Observer registered
  9035. */
  9036. Observable.prototype.hasObservers = function () {
  9037. return this._observers.length > 0;
  9038. };
  9039. /**
  9040. * Clear the list of observers
  9041. */
  9042. Observable.prototype.clear = function () {
  9043. this._observers = new Array();
  9044. this._onObserverAdded = null;
  9045. };
  9046. /**
  9047. * Clone the current observable
  9048. * @returns a new observable
  9049. */
  9050. Observable.prototype.clone = function () {
  9051. var result = new Observable();
  9052. result._observers = this._observers.slice(0);
  9053. return result;
  9054. };
  9055. /**
  9056. * Does this observable handles observer registered with a given mask
  9057. * @param mask defines the mask to be tested
  9058. * @return whether or not one observer registered with the given mask is handeled
  9059. **/
  9060. Observable.prototype.hasSpecificMask = function (mask) {
  9061. if (mask === void 0) { mask = -1; }
  9062. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  9063. var obs = _a[_i];
  9064. if (obs.mask & mask || obs.mask === mask) {
  9065. return true;
  9066. }
  9067. }
  9068. return false;
  9069. };
  9070. return Observable;
  9071. }());
  9072. BABYLON.Observable = Observable;
  9073. })(BABYLON || (BABYLON = {}));
  9074. //# sourceMappingURL=babylon.observable.js.map
  9075. var BABYLON;
  9076. (function (BABYLON) {
  9077. /**
  9078. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  9079. */
  9080. var SmartArray = /** @class */ (function () {
  9081. /**
  9082. * Instantiates a Smart Array.
  9083. * @param capacity defines the default capacity of the array.
  9084. */
  9085. function SmartArray(capacity) {
  9086. /**
  9087. * The active length of the array.
  9088. */
  9089. this.length = 0;
  9090. this.data = new Array(capacity);
  9091. this._id = SmartArray._GlobalId++;
  9092. }
  9093. /**
  9094. * Pushes a value at the end of the active data.
  9095. * @param value defines the object to push in the array.
  9096. */
  9097. SmartArray.prototype.push = function (value) {
  9098. this.data[this.length++] = value;
  9099. if (this.length > this.data.length) {
  9100. this.data.length *= 2;
  9101. }
  9102. };
  9103. /**
  9104. * Iterates over the active data and apply the lambda to them.
  9105. * @param func defines the action to apply on each value.
  9106. */
  9107. SmartArray.prototype.forEach = function (func) {
  9108. for (var index = 0; index < this.length; index++) {
  9109. func(this.data[index]);
  9110. }
  9111. };
  9112. /**
  9113. * Sorts the full sets of data.
  9114. * @param compareFn defines the comparison function to apply.
  9115. */
  9116. SmartArray.prototype.sort = function (compareFn) {
  9117. this.data.sort(compareFn);
  9118. };
  9119. /**
  9120. * Resets the active data to an empty array.
  9121. */
  9122. SmartArray.prototype.reset = function () {
  9123. this.length = 0;
  9124. };
  9125. /**
  9126. * Releases all the data from the array as well as the array.
  9127. */
  9128. SmartArray.prototype.dispose = function () {
  9129. this.reset();
  9130. if (this.data) {
  9131. this.data.length = 0;
  9132. this.data = [];
  9133. }
  9134. };
  9135. /**
  9136. * Concats the active data with a given array.
  9137. * @param array defines the data to concatenate with.
  9138. */
  9139. SmartArray.prototype.concat = function (array) {
  9140. if (array.length === 0) {
  9141. return;
  9142. }
  9143. if (this.length + array.length > this.data.length) {
  9144. this.data.length = (this.length + array.length) * 2;
  9145. }
  9146. for (var index = 0; index < array.length; index++) {
  9147. this.data[this.length++] = (array.data || array)[index];
  9148. }
  9149. };
  9150. /**
  9151. * Returns the position of a value in the active data.
  9152. * @param value defines the value to find the index for
  9153. * @returns the index if found in the active data otherwise -1
  9154. */
  9155. SmartArray.prototype.indexOf = function (value) {
  9156. var position = this.data.indexOf(value);
  9157. if (position >= this.length) {
  9158. return -1;
  9159. }
  9160. return position;
  9161. };
  9162. /**
  9163. * Returns whether an element is part of the active data.
  9164. * @param value defines the value to look for
  9165. * @returns true if found in the active data otherwise false
  9166. */
  9167. SmartArray.prototype.contains = function (value) {
  9168. return this.indexOf(value) !== -1;
  9169. };
  9170. // Statics
  9171. SmartArray._GlobalId = 0;
  9172. return SmartArray;
  9173. }());
  9174. BABYLON.SmartArray = SmartArray;
  9175. /**
  9176. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  9177. * The data in this array can only be present once
  9178. */
  9179. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  9180. __extends(SmartArrayNoDuplicate, _super);
  9181. function SmartArrayNoDuplicate() {
  9182. var _this = _super !== null && _super.apply(this, arguments) || this;
  9183. _this._duplicateId = 0;
  9184. return _this;
  9185. }
  9186. /**
  9187. * Pushes a value at the end of the active data.
  9188. * THIS DOES NOT PREVENT DUPPLICATE DATA
  9189. * @param value defines the object to push in the array.
  9190. */
  9191. SmartArrayNoDuplicate.prototype.push = function (value) {
  9192. _super.prototype.push.call(this, value);
  9193. if (!value.__smartArrayFlags) {
  9194. value.__smartArrayFlags = {};
  9195. }
  9196. value.__smartArrayFlags[this._id] = this._duplicateId;
  9197. };
  9198. /**
  9199. * Pushes a value at the end of the active data.
  9200. * If the data is already present, it won t be added again
  9201. * @param value defines the object to push in the array.
  9202. * @returns true if added false if it was already present
  9203. */
  9204. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  9205. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  9206. return false;
  9207. }
  9208. this.push(value);
  9209. return true;
  9210. };
  9211. /**
  9212. * Resets the active data to an empty array.
  9213. */
  9214. SmartArrayNoDuplicate.prototype.reset = function () {
  9215. _super.prototype.reset.call(this);
  9216. this._duplicateId++;
  9217. };
  9218. /**
  9219. * Concats the active data with a given array.
  9220. * This ensures no dupplicate will be present in the result.
  9221. * @param array defines the data to concatenate with.
  9222. */
  9223. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  9224. if (array.length === 0) {
  9225. return;
  9226. }
  9227. if (this.length + array.length > this.data.length) {
  9228. this.data.length = (this.length + array.length) * 2;
  9229. }
  9230. for (var index = 0; index < array.length; index++) {
  9231. var item = (array.data || array)[index];
  9232. this.pushNoDuplicate(item);
  9233. }
  9234. };
  9235. return SmartArrayNoDuplicate;
  9236. }(SmartArray));
  9237. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  9238. })(BABYLON || (BABYLON = {}));
  9239. //# sourceMappingURL=babylon.smartArray.js.map
  9240. var BABYLON;
  9241. (function (BABYLON) {
  9242. /** Class used to store color4 gradient */
  9243. var ColorGradient = /** @class */ (function () {
  9244. function ColorGradient() {
  9245. }
  9246. /**
  9247. * Will get a color picked randomly between color1 and color2.
  9248. * If color2 is undefined then color1 will be used
  9249. * @param result defines the target Color4 to store the result in
  9250. */
  9251. ColorGradient.prototype.getColorToRef = function (result) {
  9252. if (!this.color2) {
  9253. result.copyFrom(this.color1);
  9254. return;
  9255. }
  9256. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  9257. };
  9258. return ColorGradient;
  9259. }());
  9260. BABYLON.ColorGradient = ColorGradient;
  9261. /** Class used to store color 3 gradient */
  9262. var Color3Gradient = /** @class */ (function () {
  9263. function Color3Gradient() {
  9264. }
  9265. return Color3Gradient;
  9266. }());
  9267. BABYLON.Color3Gradient = Color3Gradient;
  9268. /** Class used to store factor gradient */
  9269. var FactorGradient = /** @class */ (function () {
  9270. function FactorGradient() {
  9271. }
  9272. /**
  9273. * Will get a number picked randomly between factor1 and factor2.
  9274. * If factor2 is undefined then factor1 will be used
  9275. * @returns the picked number
  9276. */
  9277. FactorGradient.prototype.getFactor = function () {
  9278. if (this.factor2 === undefined) {
  9279. return this.factor1;
  9280. }
  9281. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  9282. };
  9283. return FactorGradient;
  9284. }());
  9285. BABYLON.FactorGradient = FactorGradient;
  9286. /**
  9287. * @ignore
  9288. * Application error to support additional information when loading a file
  9289. */
  9290. var LoadFileError = /** @class */ (function (_super) {
  9291. __extends(LoadFileError, _super);
  9292. /**
  9293. * Creates a new LoadFileError
  9294. * @param message defines the message of the error
  9295. * @param request defines the optional XHR request
  9296. */
  9297. function LoadFileError(message,
  9298. /** defines the optional XHR request */
  9299. request) {
  9300. var _this = _super.call(this, message) || this;
  9301. _this.request = request;
  9302. _this.name = "LoadFileError";
  9303. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  9304. return _this;
  9305. }
  9306. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  9307. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  9308. // Polyfill for Object.setPrototypeOf if necessary.
  9309. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  9310. return LoadFileError;
  9311. }(Error));
  9312. BABYLON.LoadFileError = LoadFileError;
  9313. /**
  9314. * Class used to define a retry strategy when error happens while loading assets
  9315. */
  9316. var RetryStrategy = /** @class */ (function () {
  9317. function RetryStrategy() {
  9318. }
  9319. /**
  9320. * Function used to defines an exponential back off strategy
  9321. * @param maxRetries defines the maximum number of retries (3 by default)
  9322. * @param baseInterval defines the interval between retries
  9323. * @returns the strategy function to use
  9324. */
  9325. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  9326. if (maxRetries === void 0) { maxRetries = 3; }
  9327. if (baseInterval === void 0) { baseInterval = 500; }
  9328. return function (url, request, retryIndex) {
  9329. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  9330. return -1;
  9331. }
  9332. return Math.pow(2, retryIndex) * baseInterval;
  9333. };
  9334. };
  9335. return RetryStrategy;
  9336. }());
  9337. BABYLON.RetryStrategy = RetryStrategy;
  9338. // Screenshots
  9339. var screenshotCanvas;
  9340. var cloneValue = function (source, destinationObject) {
  9341. if (!source) {
  9342. return null;
  9343. }
  9344. if (source instanceof BABYLON.Mesh) {
  9345. return null;
  9346. }
  9347. if (source instanceof BABYLON.SubMesh) {
  9348. return source.clone(destinationObject);
  9349. }
  9350. else if (source.clone) {
  9351. return source.clone();
  9352. }
  9353. return null;
  9354. };
  9355. /**
  9356. * Class containing a set of static utilities functions
  9357. */
  9358. var Tools = /** @class */ (function () {
  9359. function Tools() {
  9360. }
  9361. /**
  9362. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  9363. * @param u defines the coordinate on X axis
  9364. * @param v defines the coordinate on Y axis
  9365. * @param width defines the width of the source data
  9366. * @param height defines the height of the source data
  9367. * @param pixels defines the source byte array
  9368. * @param color defines the output color
  9369. */
  9370. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  9371. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  9372. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  9373. var position = (wrappedU + wrappedV * width) * 4;
  9374. color.r = pixels[position] / 255;
  9375. color.g = pixels[position + 1] / 255;
  9376. color.b = pixels[position + 2] / 255;
  9377. color.a = pixels[position + 3] / 255;
  9378. };
  9379. /**
  9380. * Interpolates between a and b via alpha
  9381. * @param a The lower value (returned when alpha = 0)
  9382. * @param b The upper value (returned when alpha = 1)
  9383. * @param alpha The interpolation-factor
  9384. * @return The mixed value
  9385. */
  9386. Tools.Mix = function (a, b, alpha) {
  9387. return a * (1 - alpha) + b * alpha;
  9388. };
  9389. /**
  9390. * Tries to instantiate a new object from a given class name
  9391. * @param className defines the class name to instantiate
  9392. * @returns the new object or null if the system was not able to do the instantiation
  9393. */
  9394. Tools.Instantiate = function (className) {
  9395. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  9396. return Tools.RegisteredExternalClasses[className];
  9397. }
  9398. var arr = className.split(".");
  9399. var fn = (window || this);
  9400. for (var i = 0, len = arr.length; i < len; i++) {
  9401. fn = fn[arr[i]];
  9402. }
  9403. if (typeof fn !== "function") {
  9404. return null;
  9405. }
  9406. return fn;
  9407. };
  9408. /**
  9409. * Provides a slice function that will work even on IE
  9410. * @param data defines the array to slice
  9411. * @param start defines the start of the data (optional)
  9412. * @param end defines the end of the data (optional)
  9413. * @returns the new sliced array
  9414. */
  9415. Tools.Slice = function (data, start, end) {
  9416. if (data.slice) {
  9417. return data.slice(start, end);
  9418. }
  9419. return Array.prototype.slice.call(data, start, end);
  9420. };
  9421. /**
  9422. * Polyfill for setImmediate
  9423. * @param action defines the action to execute after the current execution block
  9424. */
  9425. Tools.SetImmediate = function (action) {
  9426. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  9427. window.setImmediate(action);
  9428. }
  9429. else {
  9430. setTimeout(action, 1);
  9431. }
  9432. };
  9433. /**
  9434. * Function indicating if a number is an exponent of 2
  9435. * @param value defines the value to test
  9436. * @returns true if the value is an exponent of 2
  9437. */
  9438. Tools.IsExponentOfTwo = function (value) {
  9439. var count = 1;
  9440. do {
  9441. count *= 2;
  9442. } while (count < value);
  9443. return count === value;
  9444. };
  9445. /**
  9446. * Returns the nearest 32-bit single precision float representation of a Number
  9447. * @param value A Number. If the parameter is of a different type, it will get converted
  9448. * to a number or to NaN if it cannot be converted
  9449. * @returns number
  9450. */
  9451. Tools.FloatRound = function (value) {
  9452. if (Math.fround) {
  9453. return Math.fround(value);
  9454. }
  9455. return (Tools._tmpFloatArray[0] = value);
  9456. };
  9457. /**
  9458. * Find the next highest power of two.
  9459. * @param x Number to start search from.
  9460. * @return Next highest power of two.
  9461. */
  9462. Tools.CeilingPOT = function (x) {
  9463. x--;
  9464. x |= x >> 1;
  9465. x |= x >> 2;
  9466. x |= x >> 4;
  9467. x |= x >> 8;
  9468. x |= x >> 16;
  9469. x++;
  9470. return x;
  9471. };
  9472. /**
  9473. * Find the next lowest power of two.
  9474. * @param x Number to start search from.
  9475. * @return Next lowest power of two.
  9476. */
  9477. Tools.FloorPOT = function (x) {
  9478. x = x | (x >> 1);
  9479. x = x | (x >> 2);
  9480. x = x | (x >> 4);
  9481. x = x | (x >> 8);
  9482. x = x | (x >> 16);
  9483. return x - (x >> 1);
  9484. };
  9485. /**
  9486. * Find the nearest power of two.
  9487. * @param x Number to start search from.
  9488. * @return Next nearest power of two.
  9489. */
  9490. Tools.NearestPOT = function (x) {
  9491. var c = Tools.CeilingPOT(x);
  9492. var f = Tools.FloorPOT(x);
  9493. return (c - x) > (x - f) ? f : c;
  9494. };
  9495. /**
  9496. * Get the closest exponent of two
  9497. * @param value defines the value to approximate
  9498. * @param max defines the maximum value to return
  9499. * @param mode defines how to define the closest value
  9500. * @returns closest exponent of two of the given value
  9501. */
  9502. Tools.GetExponentOfTwo = function (value, max, mode) {
  9503. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  9504. var pot;
  9505. switch (mode) {
  9506. case BABYLON.Engine.SCALEMODE_FLOOR:
  9507. pot = Tools.FloorPOT(value);
  9508. break;
  9509. case BABYLON.Engine.SCALEMODE_NEAREST:
  9510. pot = Tools.NearestPOT(value);
  9511. break;
  9512. case BABYLON.Engine.SCALEMODE_CEILING:
  9513. default:
  9514. pot = Tools.CeilingPOT(value);
  9515. break;
  9516. }
  9517. return Math.min(pot, max);
  9518. };
  9519. /**
  9520. * Extracts the filename from a path
  9521. * @param path defines the path to use
  9522. * @returns the filename
  9523. */
  9524. Tools.GetFilename = function (path) {
  9525. var index = path.lastIndexOf("/");
  9526. if (index < 0) {
  9527. return path;
  9528. }
  9529. return path.substring(index + 1);
  9530. };
  9531. /**
  9532. * Extracts the "folder" part of a path (everything before the filename).
  9533. * @param uri The URI to extract the info from
  9534. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  9535. * @returns The "folder" part of the path
  9536. */
  9537. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  9538. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  9539. var index = uri.lastIndexOf("/");
  9540. if (index < 0) {
  9541. if (returnUnchangedIfNoSlash) {
  9542. return uri;
  9543. }
  9544. return "";
  9545. }
  9546. return uri.substring(0, index + 1);
  9547. };
  9548. /**
  9549. * Extracts text content from a DOM element hierarchy
  9550. * @param element defines the root element
  9551. * @returns a string
  9552. */
  9553. Tools.GetDOMTextContent = function (element) {
  9554. var result = "";
  9555. var child = element.firstChild;
  9556. while (child) {
  9557. if (child.nodeType === 3) {
  9558. result += child.textContent;
  9559. }
  9560. child = child.nextSibling;
  9561. }
  9562. return result;
  9563. };
  9564. /**
  9565. * Convert an angle in radians to degrees
  9566. * @param angle defines the angle to convert
  9567. * @returns the angle in degrees
  9568. */
  9569. Tools.ToDegrees = function (angle) {
  9570. return angle * 180 / Math.PI;
  9571. };
  9572. /**
  9573. * Convert an angle in degrees to radians
  9574. * @param angle defines the angle to convert
  9575. * @returns the angle in radians
  9576. */
  9577. Tools.ToRadians = function (angle) {
  9578. return angle * Math.PI / 180;
  9579. };
  9580. /**
  9581. * Encode a buffer to a base64 string
  9582. * @param buffer defines the buffer to encode
  9583. * @returns the encoded string
  9584. */
  9585. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  9586. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  9587. var output = "";
  9588. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  9589. var i = 0;
  9590. var bytes = new Uint8Array(buffer);
  9591. while (i < bytes.length) {
  9592. chr1 = bytes[i++];
  9593. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  9594. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  9595. enc1 = chr1 >> 2;
  9596. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  9597. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  9598. enc4 = chr3 & 63;
  9599. if (isNaN(chr2)) {
  9600. enc3 = enc4 = 64;
  9601. }
  9602. else if (isNaN(chr3)) {
  9603. enc4 = 64;
  9604. }
  9605. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  9606. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  9607. }
  9608. return "data:image/png;base64," + output;
  9609. };
  9610. /**
  9611. * Extracts minimum and maximum values from a list of indexed positions
  9612. * @param positions defines the positions to use
  9613. * @param indices defines the indices to the positions
  9614. * @param indexStart defines the start index
  9615. * @param indexCount defines the end index
  9616. * @param bias defines bias value to add to the result
  9617. * @return minimum and maximum values
  9618. */
  9619. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  9620. if (bias === void 0) { bias = null; }
  9621. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9622. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9623. for (var index = indexStart; index < indexStart + indexCount; index++) {
  9624. var offset = indices[index] * 3;
  9625. var x = positions[offset];
  9626. var y = positions[offset + 1];
  9627. var z = positions[offset + 2];
  9628. minimum.minimizeInPlaceFromFloats(x, y, z);
  9629. maximum.maximizeInPlaceFromFloats(x, y, z);
  9630. }
  9631. if (bias) {
  9632. minimum.x -= minimum.x * bias.x + bias.y;
  9633. minimum.y -= minimum.y * bias.x + bias.y;
  9634. minimum.z -= minimum.z * bias.x + bias.y;
  9635. maximum.x += maximum.x * bias.x + bias.y;
  9636. maximum.y += maximum.y * bias.x + bias.y;
  9637. maximum.z += maximum.z * bias.x + bias.y;
  9638. }
  9639. return {
  9640. minimum: minimum,
  9641. maximum: maximum
  9642. };
  9643. };
  9644. /**
  9645. * Extracts minimum and maximum values from a list of positions
  9646. * @param positions defines the positions to use
  9647. * @param start defines the start index in the positions array
  9648. * @param count defines the number of positions to handle
  9649. * @param bias defines bias value to add to the result
  9650. * @param stride defines the stride size to use (distance between two positions in the positions array)
  9651. * @return minimum and maximum values
  9652. */
  9653. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  9654. if (bias === void 0) { bias = null; }
  9655. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9656. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9657. if (!stride) {
  9658. stride = 3;
  9659. }
  9660. for (var index = start, offset = start * stride; index < start + count; index++, offset += stride) {
  9661. var x = positions[offset];
  9662. var y = positions[offset + 1];
  9663. var z = positions[offset + 2];
  9664. minimum.minimizeInPlaceFromFloats(x, y, z);
  9665. maximum.maximizeInPlaceFromFloats(x, y, z);
  9666. }
  9667. if (bias) {
  9668. minimum.x -= minimum.x * bias.x + bias.y;
  9669. minimum.y -= minimum.y * bias.x + bias.y;
  9670. minimum.z -= minimum.z * bias.x + bias.y;
  9671. maximum.x += maximum.x * bias.x + bias.y;
  9672. maximum.y += maximum.y * bias.x + bias.y;
  9673. maximum.z += maximum.z * bias.x + bias.y;
  9674. }
  9675. return {
  9676. minimum: minimum,
  9677. maximum: maximum
  9678. };
  9679. };
  9680. /**
  9681. * Returns an array if obj is not an array
  9682. * @param obj defines the object to evaluate as an array
  9683. * @param allowsNullUndefined defines a boolean indicating if obj is allowed to be null or undefined
  9684. * @returns either obj directly if obj is an array or a new array containing obj
  9685. */
  9686. Tools.MakeArray = function (obj, allowsNullUndefined) {
  9687. if (allowsNullUndefined !== true && (obj === undefined || obj == null)) {
  9688. return null;
  9689. }
  9690. return Array.isArray(obj) ? obj : [obj];
  9691. };
  9692. /**
  9693. * Gets the pointer prefix to use
  9694. * @returns "pointer" if touch is enabled. Else returns "mouse"
  9695. */
  9696. Tools.GetPointerPrefix = function () {
  9697. var eventPrefix = "pointer";
  9698. // Check if pointer events are supported
  9699. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  9700. eventPrefix = "mouse";
  9701. }
  9702. return eventPrefix;
  9703. };
  9704. /**
  9705. * Queue a new function into the requested animation frame pool (ie. this function will be executed byt the browser for the next frame)
  9706. * @param func - the function to be called
  9707. * @param requester - the object that will request the next frame. Falls back to window.
  9708. * @returns frame number
  9709. */
  9710. Tools.QueueNewFrame = function (func, requester) {
  9711. if (!Tools.IsWindowObjectExist()) {
  9712. return setTimeout(func, 16);
  9713. }
  9714. if (!requester) {
  9715. requester = window;
  9716. }
  9717. if (requester.requestAnimationFrame) {
  9718. return requester.requestAnimationFrame(func);
  9719. }
  9720. else if (requester.msRequestAnimationFrame) {
  9721. return requester.msRequestAnimationFrame(func);
  9722. }
  9723. else if (requester.webkitRequestAnimationFrame) {
  9724. return requester.webkitRequestAnimationFrame(func);
  9725. }
  9726. else if (requester.mozRequestAnimationFrame) {
  9727. return requester.mozRequestAnimationFrame(func);
  9728. }
  9729. else if (requester.oRequestAnimationFrame) {
  9730. return requester.oRequestAnimationFrame(func);
  9731. }
  9732. else {
  9733. return window.setTimeout(func, 16);
  9734. }
  9735. };
  9736. /**
  9737. * Ask the browser to promote the current element to fullscreen rendering mode
  9738. * @param element defines the DOM element to promote
  9739. */
  9740. Tools.RequestFullscreen = function (element) {
  9741. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  9742. if (!requestFunction) {
  9743. return;
  9744. }
  9745. requestFunction.call(element);
  9746. };
  9747. /**
  9748. * Asks the browser to exit fullscreen mode
  9749. */
  9750. Tools.ExitFullscreen = function () {
  9751. if (document.exitFullscreen) {
  9752. document.exitFullscreen();
  9753. }
  9754. else if (document.mozCancelFullScreen) {
  9755. document.mozCancelFullScreen();
  9756. }
  9757. else if (document.webkitCancelFullScreen) {
  9758. document.webkitCancelFullScreen();
  9759. }
  9760. else if (document.msCancelFullScreen) {
  9761. document.msCancelFullScreen();
  9762. }
  9763. };
  9764. /**
  9765. * Sets the cors behavior on a dom element. This will add the required Tools.CorsBehavior to the element.
  9766. * @param url define the url we are trying
  9767. * @param element define the dom element where to configure the cors policy
  9768. */
  9769. Tools.SetCorsBehavior = function (url, element) {
  9770. if (url && url.indexOf("data:") === 0) {
  9771. return;
  9772. }
  9773. if (Tools.CorsBehavior) {
  9774. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  9775. element.crossOrigin = Tools.CorsBehavior;
  9776. }
  9777. else {
  9778. var result = Tools.CorsBehavior(url);
  9779. if (result) {
  9780. element.crossOrigin = result;
  9781. }
  9782. }
  9783. }
  9784. };
  9785. // External files
  9786. /**
  9787. * Removes unwanted characters from an url
  9788. * @param url defines the url to clean
  9789. * @returns the cleaned url
  9790. */
  9791. Tools.CleanUrl = function (url) {
  9792. url = url.replace(/#/mg, "%23");
  9793. return url;
  9794. };
  9795. /**
  9796. * Loads an image as an HTMLImageElement.
  9797. * @param input url string, ArrayBuffer, or Blob to load
  9798. * @param onLoad callback called when the image successfully loads
  9799. * @param onError callback called when the image fails to load
  9800. * @param database database for caching
  9801. * @returns the HTMLImageElement of the loaded image
  9802. */
  9803. Tools.LoadImage = function (input, onLoad, onError, database) {
  9804. var url;
  9805. var usingObjectURL = false;
  9806. if (input instanceof ArrayBuffer) {
  9807. url = URL.createObjectURL(new Blob([input]));
  9808. usingObjectURL = true;
  9809. }
  9810. else if (input instanceof Blob) {
  9811. url = URL.createObjectURL(input);
  9812. usingObjectURL = true;
  9813. }
  9814. else {
  9815. url = Tools.CleanUrl(input);
  9816. url = Tools.PreprocessUrl(input);
  9817. }
  9818. var img = new Image();
  9819. Tools.SetCorsBehavior(url, img);
  9820. var loadHandler = function () {
  9821. if (usingObjectURL && img.src) {
  9822. URL.revokeObjectURL(img.src);
  9823. }
  9824. img.removeEventListener("load", loadHandler);
  9825. img.removeEventListener("error", errorHandler);
  9826. onLoad(img);
  9827. };
  9828. var errorHandler = function (err) {
  9829. if (usingObjectURL && img.src) {
  9830. URL.revokeObjectURL(img.src);
  9831. }
  9832. img.removeEventListener("load", loadHandler);
  9833. img.removeEventListener("error", errorHandler);
  9834. Tools.Error("Error while trying to load image: " + input);
  9835. if (onError) {
  9836. onError("Error while trying to load image: " + input, err);
  9837. }
  9838. };
  9839. img.addEventListener("load", loadHandler);
  9840. img.addEventListener("error", errorHandler);
  9841. var noIndexedDB = function () {
  9842. img.src = url;
  9843. };
  9844. var loadFromIndexedDB = function () {
  9845. if (database) {
  9846. database.loadImageFromDB(url, img);
  9847. }
  9848. };
  9849. //ANY database to do!
  9850. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9851. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9852. }
  9853. else {
  9854. if (url.indexOf("file:") !== -1) {
  9855. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9856. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9857. try {
  9858. var blobURL;
  9859. try {
  9860. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9861. }
  9862. catch (ex) {
  9863. // Chrome doesn't support oneTimeOnly parameter
  9864. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9865. }
  9866. img.src = blobURL;
  9867. usingObjectURL = true;
  9868. }
  9869. catch (e) {
  9870. img.src = "";
  9871. }
  9872. return img;
  9873. }
  9874. }
  9875. noIndexedDB();
  9876. }
  9877. return img;
  9878. };
  9879. /**
  9880. * Loads a file
  9881. * @param url url string, ArrayBuffer, or Blob to load
  9882. * @param onSuccess callback called when the file successfully loads
  9883. * @param onProgress callback called while file is loading (if the server supports this mode)
  9884. * @param database database for caching
  9885. * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer
  9886. * @param onError callback called when the file fails to load
  9887. * @returns a file request object
  9888. */
  9889. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9890. url = Tools.CleanUrl(url);
  9891. url = Tools.PreprocessUrl(url);
  9892. // If file and file input are set
  9893. if (url.indexOf("file:") !== -1) {
  9894. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9895. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9896. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9897. }
  9898. }
  9899. var loadUrl = Tools.BaseUrl + url;
  9900. var aborted = false;
  9901. var fileRequest = {
  9902. onCompleteObservable: new BABYLON.Observable(),
  9903. abort: function () { return aborted = true; },
  9904. };
  9905. var requestFile = function () {
  9906. var request = new XMLHttpRequest();
  9907. var retryHandle = null;
  9908. fileRequest.abort = function () {
  9909. aborted = true;
  9910. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9911. request.abort();
  9912. }
  9913. if (retryHandle !== null) {
  9914. clearTimeout(retryHandle);
  9915. retryHandle = null;
  9916. }
  9917. };
  9918. var retryLoop = function (retryIndex) {
  9919. request.open('GET', loadUrl, true);
  9920. if (useArrayBuffer) {
  9921. request.responseType = "arraybuffer";
  9922. }
  9923. if (onProgress) {
  9924. request.addEventListener("progress", onProgress);
  9925. }
  9926. var onLoadEnd = function () {
  9927. request.removeEventListener("loadend", onLoadEnd);
  9928. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9929. fileRequest.onCompleteObservable.clear();
  9930. };
  9931. request.addEventListener("loadend", onLoadEnd);
  9932. var onReadyStateChange = function () {
  9933. if (aborted) {
  9934. return;
  9935. }
  9936. // In case of undefined state in some browsers.
  9937. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9938. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9939. request.removeEventListener("readystatechange", onReadyStateChange);
  9940. if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!Tools.IsWindowObjectExist() || Tools.IsFileURL()))) {
  9941. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9942. return;
  9943. }
  9944. var retryStrategy = Tools.DefaultRetryStrategy;
  9945. if (retryStrategy) {
  9946. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9947. if (waitTime !== -1) {
  9948. // Prevent the request from completing for retry.
  9949. request.removeEventListener("loadend", onLoadEnd);
  9950. request = new XMLHttpRequest();
  9951. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9952. return;
  9953. }
  9954. }
  9955. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9956. if (onError) {
  9957. onError(request, e);
  9958. }
  9959. else {
  9960. throw e;
  9961. }
  9962. }
  9963. };
  9964. request.addEventListener("readystatechange", onReadyStateChange);
  9965. request.send();
  9966. };
  9967. retryLoop(0);
  9968. };
  9969. // Caching all files
  9970. if (database && database.enableSceneOffline) {
  9971. var noIndexedDB_1 = function (request) {
  9972. if (request && request.status > 400) {
  9973. if (onError) {
  9974. onError(request);
  9975. }
  9976. }
  9977. else {
  9978. if (!aborted) {
  9979. requestFile();
  9980. }
  9981. }
  9982. };
  9983. var loadFromIndexedDB = function () {
  9984. // TODO: database needs to support aborting and should return a IFileRequest
  9985. if (aborted) {
  9986. return;
  9987. }
  9988. if (database) {
  9989. database.loadFileFromDB(url, function (data) {
  9990. if (!aborted) {
  9991. onSuccess(data);
  9992. }
  9993. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9994. }, onProgress ? function (event) {
  9995. if (!aborted) {
  9996. onProgress(event);
  9997. }
  9998. } : undefined, noIndexedDB_1, useArrayBuffer);
  9999. }
  10000. };
  10001. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  10002. }
  10003. else {
  10004. requestFile();
  10005. }
  10006. return fileRequest;
  10007. };
  10008. /**
  10009. * Load a script (identified by an url). When the url returns, the
  10010. * content of this file is added into a new script element, attached to the DOM (body element)
  10011. * @param scriptUrl defines the url of the script to laod
  10012. * @param onSuccess defines the callback called when the script is loaded
  10013. * @param onError defines the callback to call if an error occurs
  10014. */
  10015. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  10016. if (!Tools.IsWindowObjectExist()) {
  10017. return;
  10018. }
  10019. var head = document.getElementsByTagName('head')[0];
  10020. var script = document.createElement('script');
  10021. script.type = 'text/javascript';
  10022. script.src = scriptUrl;
  10023. script.onload = function () {
  10024. if (onSuccess) {
  10025. onSuccess();
  10026. }
  10027. };
  10028. script.onerror = function (e) {
  10029. if (onError) {
  10030. onError("Unable to load script '" + scriptUrl + "'", e);
  10031. }
  10032. };
  10033. head.appendChild(script);
  10034. };
  10035. /**
  10036. * Loads a file from a blob
  10037. * @param fileToLoad defines the blob to use
  10038. * @param callback defines the callback to call when data is loaded
  10039. * @param progressCallback defines the callback to call during loading process
  10040. * @returns a file request object
  10041. */
  10042. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  10043. var reader = new FileReader();
  10044. var request = {
  10045. onCompleteObservable: new BABYLON.Observable(),
  10046. abort: function () { return reader.abort(); },
  10047. };
  10048. reader.onloadend = function (e) {
  10049. request.onCompleteObservable.notifyObservers(request);
  10050. };
  10051. reader.onload = function (e) {
  10052. //target doesn't have result from ts 1.3
  10053. callback(e.target['result']);
  10054. };
  10055. reader.onprogress = progressCallback;
  10056. reader.readAsDataURL(fileToLoad);
  10057. return request;
  10058. };
  10059. /**
  10060. * Loads a file
  10061. * @param fileToLoad defines the file to load
  10062. * @param callback defines the callback to call when data is loaded
  10063. * @param progressCallBack defines the callback to call during loading process
  10064. * @param useArrayBuffer defines a boolean indicating that data must be returned as an ArrayBuffer
  10065. * @returns a file request object
  10066. */
  10067. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  10068. var reader = new FileReader();
  10069. var request = {
  10070. onCompleteObservable: new BABYLON.Observable(),
  10071. abort: function () { return reader.abort(); },
  10072. };
  10073. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  10074. reader.onerror = function (e) {
  10075. Tools.Log("Error while reading file: " + fileToLoad.name);
  10076. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  10077. };
  10078. reader.onload = function (e) {
  10079. //target doesn't have result from ts 1.3
  10080. callback(e.target['result']);
  10081. };
  10082. if (progressCallBack) {
  10083. reader.onprogress = progressCallBack;
  10084. }
  10085. if (!useArrayBuffer) {
  10086. // Asynchronous read
  10087. reader.readAsText(fileToLoad);
  10088. }
  10089. else {
  10090. reader.readAsArrayBuffer(fileToLoad);
  10091. }
  10092. return request;
  10093. };
  10094. /**
  10095. * Creates a data url from a given string content
  10096. * @param content defines the content to convert
  10097. * @returns the new data url link
  10098. */
  10099. Tools.FileAsURL = function (content) {
  10100. var fileBlob = new Blob([content]);
  10101. var url = window.URL || window.webkitURL;
  10102. var link = url.createObjectURL(fileBlob);
  10103. return link;
  10104. };
  10105. /**
  10106. * Format the given number to a specific decimal format
  10107. * @param value defines the number to format
  10108. * @param decimals defines the number of decimals to use
  10109. * @returns the formatted string
  10110. */
  10111. Tools.Format = function (value, decimals) {
  10112. if (decimals === void 0) { decimals = 2; }
  10113. return value.toFixed(decimals);
  10114. };
  10115. /**
  10116. * Checks if a given vector is inside a specific range
  10117. * @param v defines the vector to test
  10118. * @param min defines the minimum range
  10119. * @param max defines the maximum range
  10120. */
  10121. Tools.CheckExtends = function (v, min, max) {
  10122. if (v.x < min.x) {
  10123. min.x = v.x;
  10124. }
  10125. if (v.y < min.y) {
  10126. min.y = v.y;
  10127. }
  10128. if (v.z < min.z) {
  10129. min.z = v.z;
  10130. }
  10131. if (v.x > max.x) {
  10132. max.x = v.x;
  10133. }
  10134. if (v.y > max.y) {
  10135. max.y = v.y;
  10136. }
  10137. if (v.z > max.z) {
  10138. max.z = v.z;
  10139. }
  10140. };
  10141. /**
  10142. * Tries to copy an object by duplicating every property
  10143. * @param source defines the source object
  10144. * @param destination defines the target object
  10145. * @param doNotCopyList defines a list of properties to avoid
  10146. * @param mustCopyList defines a list of properties to copy (even if they start with _)
  10147. */
  10148. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  10149. for (var prop in source) {
  10150. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  10151. continue;
  10152. }
  10153. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  10154. continue;
  10155. }
  10156. var sourceValue = source[prop];
  10157. var typeOfSourceValue = typeof sourceValue;
  10158. if (typeOfSourceValue === "function") {
  10159. continue;
  10160. }
  10161. try {
  10162. if (typeOfSourceValue === "object") {
  10163. if (sourceValue instanceof Array) {
  10164. destination[prop] = [];
  10165. if (sourceValue.length > 0) {
  10166. if (typeof sourceValue[0] == "object") {
  10167. for (var index = 0; index < sourceValue.length; index++) {
  10168. var clonedValue = cloneValue(sourceValue[index], destination);
  10169. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  10170. destination[prop].push(clonedValue);
  10171. }
  10172. }
  10173. }
  10174. else {
  10175. destination[prop] = sourceValue.slice(0);
  10176. }
  10177. }
  10178. }
  10179. else {
  10180. destination[prop] = cloneValue(sourceValue, destination);
  10181. }
  10182. }
  10183. else {
  10184. destination[prop] = sourceValue;
  10185. }
  10186. }
  10187. catch (e) {
  10188. // Just ignore error (it could be because of a read-only property)
  10189. }
  10190. }
  10191. };
  10192. /**
  10193. * Gets a boolean indicating if the given object has no own property
  10194. * @param obj defines the object to test
  10195. * @returns true if object has no own property
  10196. */
  10197. Tools.IsEmpty = function (obj) {
  10198. for (var i in obj) {
  10199. if (obj.hasOwnProperty(i)) {
  10200. return false;
  10201. }
  10202. }
  10203. return true;
  10204. };
  10205. /**
  10206. * Function used to register events at window level
  10207. * @param events defines the events to register
  10208. */
  10209. Tools.RegisterTopRootEvents = function (events) {
  10210. for (var index = 0; index < events.length; index++) {
  10211. var event = events[index];
  10212. window.addEventListener(event.name, event.handler, false);
  10213. try {
  10214. if (window.parent) {
  10215. window.parent.addEventListener(event.name, event.handler, false);
  10216. }
  10217. }
  10218. catch (e) {
  10219. // Silently fails...
  10220. }
  10221. }
  10222. };
  10223. /**
  10224. * Function used to unregister events from window level
  10225. * @param events defines the events to unregister
  10226. */
  10227. Tools.UnregisterTopRootEvents = function (events) {
  10228. for (var index = 0; index < events.length; index++) {
  10229. var event = events[index];
  10230. window.removeEventListener(event.name, event.handler);
  10231. try {
  10232. if (window.parent) {
  10233. window.parent.removeEventListener(event.name, event.handler);
  10234. }
  10235. }
  10236. catch (e) {
  10237. // Silently fails...
  10238. }
  10239. }
  10240. };
  10241. /**
  10242. * Dumps the current bound framebuffer
  10243. * @param width defines the rendering width
  10244. * @param height defines the rendering height
  10245. * @param engine defines the hosting engine
  10246. * @param successCallback defines the callback triggered once the data are available
  10247. * @param mimeType defines the mime type of the result
  10248. * @param fileName defines the filename to download. If present, the result will automatically be downloaded
  10249. */
  10250. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  10251. if (mimeType === void 0) { mimeType = "image/png"; }
  10252. // Read the contents of the framebuffer
  10253. var numberOfChannelsByLine = width * 4;
  10254. var halfHeight = height / 2;
  10255. //Reading datas from WebGL
  10256. var data = engine.readPixels(0, 0, width, height);
  10257. //To flip image on Y axis.
  10258. for (var i = 0; i < halfHeight; i++) {
  10259. for (var j = 0; j < numberOfChannelsByLine; j++) {
  10260. var currentCell = j + i * numberOfChannelsByLine;
  10261. var targetLine = height - i - 1;
  10262. var targetCell = j + targetLine * numberOfChannelsByLine;
  10263. var temp = data[currentCell];
  10264. data[currentCell] = data[targetCell];
  10265. data[targetCell] = temp;
  10266. }
  10267. }
  10268. // Create a 2D canvas to store the result
  10269. if (!screenshotCanvas) {
  10270. screenshotCanvas = document.createElement('canvas');
  10271. }
  10272. screenshotCanvas.width = width;
  10273. screenshotCanvas.height = height;
  10274. var context = screenshotCanvas.getContext('2d');
  10275. if (context) {
  10276. // Copy the pixels to a 2D canvas
  10277. var imageData = context.createImageData(width, height);
  10278. var castData = (imageData.data);
  10279. castData.set(data);
  10280. context.putImageData(imageData, 0, 0);
  10281. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  10282. }
  10283. };
  10284. /**
  10285. * Converts the canvas data to blob.
  10286. * This acts as a polyfill for browsers not supporting the to blob function.
  10287. * @param canvas Defines the canvas to extract the data from
  10288. * @param successCallback Defines the callback triggered once the data are available
  10289. * @param mimeType Defines the mime type of the result
  10290. */
  10291. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  10292. if (mimeType === void 0) { mimeType = "image/png"; }
  10293. // We need HTMLCanvasElement.toBlob for HD screenshots
  10294. if (!canvas.toBlob) {
  10295. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  10296. canvas.toBlob = function (callback, type, quality) {
  10297. var _this = this;
  10298. setTimeout(function () {
  10299. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  10300. for (var i = 0; i < len; i++) {
  10301. arr[i] = binStr.charCodeAt(i);
  10302. }
  10303. callback(new Blob([arr]));
  10304. });
  10305. };
  10306. }
  10307. canvas.toBlob(function (blob) {
  10308. successCallback(blob);
  10309. }, mimeType);
  10310. };
  10311. /**
  10312. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  10313. * @param successCallback defines the callback triggered once the data are available
  10314. * @param mimeType defines the mime type of the result
  10315. * @param fileName defines he filename to download. If present, the result will automatically be downloaded
  10316. */
  10317. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  10318. if (mimeType === void 0) { mimeType = "image/png"; }
  10319. if (successCallback) {
  10320. var base64Image = screenshotCanvas.toDataURL(mimeType);
  10321. successCallback(base64Image);
  10322. }
  10323. else {
  10324. this.ToBlob(screenshotCanvas, function (blob) {
  10325. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  10326. if (("download" in document.createElement("a"))) {
  10327. if (!fileName) {
  10328. var date = new Date();
  10329. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  10330. fileName = "screenshot_" + stringDate + ".png";
  10331. }
  10332. Tools.Download(blob, fileName);
  10333. }
  10334. else {
  10335. var url = URL.createObjectURL(blob);
  10336. var newWindow = window.open("");
  10337. if (!newWindow) {
  10338. return;
  10339. }
  10340. var img = newWindow.document.createElement("img");
  10341. img.onload = function () {
  10342. // no longer need to read the blob so it's revoked
  10343. URL.revokeObjectURL(url);
  10344. };
  10345. img.src = url;
  10346. newWindow.document.body.appendChild(img);
  10347. }
  10348. }, mimeType);
  10349. }
  10350. };
  10351. /**
  10352. * Downloads a blob in the browser
  10353. * @param blob defines the blob to download
  10354. * @param fileName defines the name of the downloaded file
  10355. */
  10356. Tools.Download = function (blob, fileName) {
  10357. if (navigator && navigator.msSaveBlob) {
  10358. navigator.msSaveBlob(blob, fileName);
  10359. return;
  10360. }
  10361. var url = window.URL.createObjectURL(blob);
  10362. var a = document.createElement("a");
  10363. document.body.appendChild(a);
  10364. a.style.display = "none";
  10365. a.href = url;
  10366. a.download = fileName;
  10367. a.addEventListener("click", function () {
  10368. if (a.parentElement) {
  10369. a.parentElement.removeChild(a);
  10370. }
  10371. });
  10372. a.click();
  10373. window.URL.revokeObjectURL(url);
  10374. };
  10375. /**
  10376. * Captures a screenshot of the current rendering
  10377. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  10378. * @param engine defines the rendering engine
  10379. * @param camera defines the source camera
  10380. * @param size This parameter can be set to a single number or to an object with the
  10381. * following (optional) properties: precision, width, height. If a single number is passed,
  10382. * it will be used for both width and height. If an object is passed, the screenshot size
  10383. * will be derived from the parameters. The precision property is a multiplier allowing
  10384. * rendering at a higher or lower resolution
  10385. * @param successCallback defines the callback receives a single parameter which contains the
  10386. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  10387. * src parameter of an <img> to display it
  10388. * @param mimeType defines the MIME type of the screenshot image (default: image/png).
  10389. * Check your browser for supported MIME types
  10390. */
  10391. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  10392. if (mimeType === void 0) { mimeType = "image/png"; }
  10393. var width;
  10394. var height;
  10395. // If a precision value is specified
  10396. if (size.precision) {
  10397. width = Math.round(engine.getRenderWidth() * size.precision);
  10398. height = Math.round(width / engine.getAspectRatio(camera));
  10399. }
  10400. else if (size.width && size.height) {
  10401. width = size.width;
  10402. height = size.height;
  10403. }
  10404. //If passing only width, computing height to keep display canvas ratio.
  10405. else if (size.width && !size.height) {
  10406. width = size.width;
  10407. height = Math.round(width / engine.getAspectRatio(camera));
  10408. }
  10409. //If passing only height, computing width to keep display canvas ratio.
  10410. else if (size.height && !size.width) {
  10411. height = size.height;
  10412. width = Math.round(height * engine.getAspectRatio(camera));
  10413. }
  10414. //Assuming here that "size" parameter is a number
  10415. else if (!isNaN(size)) {
  10416. height = size;
  10417. width = size;
  10418. }
  10419. else {
  10420. Tools.Error("Invalid 'size' parameter !");
  10421. return;
  10422. }
  10423. if (!screenshotCanvas) {
  10424. screenshotCanvas = document.createElement('canvas');
  10425. }
  10426. screenshotCanvas.width = width;
  10427. screenshotCanvas.height = height;
  10428. var renderContext = screenshotCanvas.getContext("2d");
  10429. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  10430. var newWidth = width;
  10431. var newHeight = newWidth / ratio;
  10432. if (newHeight > height) {
  10433. newHeight = height;
  10434. newWidth = newHeight * ratio;
  10435. }
  10436. var offsetX = Math.max(0, width - newWidth) / 2;
  10437. var offsetY = Math.max(0, height - newHeight) / 2;
  10438. var renderingCanvas = engine.getRenderingCanvas();
  10439. if (renderContext && renderingCanvas) {
  10440. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  10441. }
  10442. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  10443. };
  10444. /**
  10445. * Generates an image screenshot from the specified camera.
  10446. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  10447. * @param engine The engine to use for rendering
  10448. * @param camera The camera to use for rendering
  10449. * @param size This parameter can be set to a single number or to an object with the
  10450. * following (optional) properties: precision, width, height. If a single number is passed,
  10451. * it will be used for both width and height. If an object is passed, the screenshot size
  10452. * will be derived from the parameters. The precision property is a multiplier allowing
  10453. * rendering at a higher or lower resolution
  10454. * @param successCallback The callback receives a single parameter which contains the
  10455. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  10456. * src parameter of an <img> to display it
  10457. * @param mimeType The MIME type of the screenshot image (default: image/png).
  10458. * Check your browser for supported MIME types
  10459. * @param samples Texture samples (default: 1)
  10460. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  10461. * @param fileName A name for for the downloaded file.
  10462. */
  10463. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  10464. if (mimeType === void 0) { mimeType = "image/png"; }
  10465. if (samples === void 0) { samples = 1; }
  10466. if (antialiasing === void 0) { antialiasing = false; }
  10467. var width;
  10468. var height;
  10469. //If a precision value is specified
  10470. if (size.precision) {
  10471. width = Math.round(engine.getRenderWidth() * size.precision);
  10472. height = Math.round(width / engine.getAspectRatio(camera));
  10473. size = { width: width, height: height };
  10474. }
  10475. else if (size.width && size.height) {
  10476. width = size.width;
  10477. height = size.height;
  10478. }
  10479. //If passing only width, computing height to keep display canvas ratio.
  10480. else if (size.width && !size.height) {
  10481. width = size.width;
  10482. height = Math.round(width / engine.getAspectRatio(camera));
  10483. size = { width: width, height: height };
  10484. }
  10485. //If passing only height, computing width to keep display canvas ratio.
  10486. else if (size.height && !size.width) {
  10487. height = size.height;
  10488. width = Math.round(height * engine.getAspectRatio(camera));
  10489. size = { width: width, height: height };
  10490. }
  10491. //Assuming here that "size" parameter is a number
  10492. else if (!isNaN(size)) {
  10493. height = size;
  10494. width = size;
  10495. }
  10496. else {
  10497. Tools.Error("Invalid 'size' parameter !");
  10498. return;
  10499. }
  10500. var scene = camera.getScene();
  10501. var previousCamera = null;
  10502. if (scene.activeCamera !== camera) {
  10503. previousCamera = scene.activeCamera;
  10504. scene.activeCamera = camera;
  10505. }
  10506. // At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  10507. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10508. texture.renderList = null;
  10509. texture.samples = samples;
  10510. if (antialiasing) {
  10511. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  10512. }
  10513. texture.onAfterRenderObservable.add(function () {
  10514. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  10515. });
  10516. scene.incrementRenderId();
  10517. scene.resetCachedMaterial();
  10518. texture.render(true);
  10519. texture.dispose();
  10520. if (previousCamera) {
  10521. scene.activeCamera = previousCamera;
  10522. }
  10523. camera.getProjectionMatrix(true); // Force cache refresh;
  10524. };
  10525. /**
  10526. * Validates if xhr data is correct
  10527. * @param xhr defines the request to validate
  10528. * @param dataType defines the expected data type
  10529. * @returns true if data is correct
  10530. */
  10531. Tools.ValidateXHRData = function (xhr, dataType) {
  10532. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  10533. if (dataType === void 0) { dataType = 7; }
  10534. try {
  10535. if (dataType & 1) {
  10536. if (xhr.responseText && xhr.responseText.length > 0) {
  10537. return true;
  10538. }
  10539. else if (dataType === 1) {
  10540. return false;
  10541. }
  10542. }
  10543. if (dataType & 2) {
  10544. // Check header width and height since there is no "TGA" magic number
  10545. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  10546. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  10547. return true;
  10548. }
  10549. else if (dataType === 2) {
  10550. return false;
  10551. }
  10552. }
  10553. if (dataType & 4) {
  10554. // Check for the "DDS" magic number
  10555. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  10556. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  10557. return true;
  10558. }
  10559. else {
  10560. return false;
  10561. }
  10562. }
  10563. }
  10564. catch (e) {
  10565. // Global protection
  10566. }
  10567. return false;
  10568. };
  10569. /**
  10570. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  10571. * Be aware Math.random() could cause collisions, but:
  10572. * "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"
  10573. * @returns a pseudo random id
  10574. */
  10575. Tools.RandomId = function () {
  10576. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  10577. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  10578. return v.toString(16);
  10579. });
  10580. };
  10581. /**
  10582. * Test if the given uri is a base64 string
  10583. * @param uri The uri to test
  10584. * @return True if the uri is a base64 string or false otherwise
  10585. */
  10586. Tools.IsBase64 = function (uri) {
  10587. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  10588. };
  10589. /**
  10590. * Decode the given base64 uri.
  10591. * @param uri The uri to decode
  10592. * @return The decoded base64 data.
  10593. */
  10594. Tools.DecodeBase64 = function (uri) {
  10595. var decodedString = atob(uri.split(",")[1]);
  10596. var bufferLength = decodedString.length;
  10597. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  10598. for (var i = 0; i < bufferLength; i++) {
  10599. bufferView[i] = decodedString.charCodeAt(i);
  10600. }
  10601. return bufferView.buffer;
  10602. };
  10603. Tools._AddLogEntry = function (entry) {
  10604. Tools._LogCache = entry + Tools._LogCache;
  10605. if (Tools.OnNewCacheEntry) {
  10606. Tools.OnNewCacheEntry(entry);
  10607. }
  10608. };
  10609. Tools._FormatMessage = function (message) {
  10610. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  10611. var date = new Date();
  10612. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  10613. };
  10614. Tools._LogDisabled = function (message) {
  10615. // nothing to do
  10616. };
  10617. Tools._LogEnabled = function (message) {
  10618. var formattedMessage = Tools._FormatMessage(message);
  10619. console.log("BJS - " + formattedMessage);
  10620. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  10621. Tools._AddLogEntry(entry);
  10622. };
  10623. Tools._WarnDisabled = function (message) {
  10624. // nothing to do
  10625. };
  10626. Tools._WarnEnabled = function (message) {
  10627. var formattedMessage = Tools._FormatMessage(message);
  10628. console.warn("BJS - " + formattedMessage);
  10629. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  10630. Tools._AddLogEntry(entry);
  10631. };
  10632. Tools._ErrorDisabled = function (message) {
  10633. // nothing to do
  10634. };
  10635. Tools._ErrorEnabled = function (message) {
  10636. Tools.errorsCount++;
  10637. var formattedMessage = Tools._FormatMessage(message);
  10638. console.error("BJS - " + formattedMessage);
  10639. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  10640. Tools._AddLogEntry(entry);
  10641. };
  10642. Object.defineProperty(Tools, "LogCache", {
  10643. /**
  10644. * Gets current log cache (list of logs)
  10645. */
  10646. get: function () {
  10647. return Tools._LogCache;
  10648. },
  10649. enumerable: true,
  10650. configurable: true
  10651. });
  10652. /**
  10653. * Clears the log cache
  10654. */
  10655. Tools.ClearLogCache = function () {
  10656. Tools._LogCache = "";
  10657. Tools.errorsCount = 0;
  10658. };
  10659. Object.defineProperty(Tools, "LogLevels", {
  10660. /**
  10661. * Sets the current log level (MessageLogLevel / WarningLogLevel / ErrorLogLevel)
  10662. */
  10663. set: function (level) {
  10664. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  10665. Tools.Log = Tools._LogEnabled;
  10666. }
  10667. else {
  10668. Tools.Log = Tools._LogDisabled;
  10669. }
  10670. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  10671. Tools.Warn = Tools._WarnEnabled;
  10672. }
  10673. else {
  10674. Tools.Warn = Tools._WarnDisabled;
  10675. }
  10676. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  10677. Tools.Error = Tools._ErrorEnabled;
  10678. }
  10679. else {
  10680. Tools.Error = Tools._ErrorDisabled;
  10681. }
  10682. },
  10683. enumerable: true,
  10684. configurable: true
  10685. });
  10686. /**
  10687. * Checks if the loaded document was accessed via `file:`-Protocol.
  10688. * @returns boolean
  10689. */
  10690. Tools.IsFileURL = function () {
  10691. return location.protocol === "file:";
  10692. };
  10693. /**
  10694. * Checks if the window object exists
  10695. * @returns true if the window object exists
  10696. */
  10697. Tools.IsWindowObjectExist = function () {
  10698. return (typeof window) !== "undefined";
  10699. };
  10700. Object.defineProperty(Tools, "PerformanceLogLevel", {
  10701. /**
  10702. * Sets the current performance log level
  10703. */
  10704. set: function (level) {
  10705. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  10706. Tools.StartPerformanceCounter = Tools._StartUserMark;
  10707. Tools.EndPerformanceCounter = Tools._EndUserMark;
  10708. return;
  10709. }
  10710. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  10711. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  10712. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  10713. return;
  10714. }
  10715. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10716. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10717. },
  10718. enumerable: true,
  10719. configurable: true
  10720. });
  10721. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  10722. };
  10723. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  10724. };
  10725. Tools._StartUserMark = function (counterName, condition) {
  10726. if (condition === void 0) { condition = true; }
  10727. if (!Tools._performance) {
  10728. if (!Tools.IsWindowObjectExist()) {
  10729. return;
  10730. }
  10731. Tools._performance = window.performance;
  10732. }
  10733. if (!condition || !Tools._performance.mark) {
  10734. return;
  10735. }
  10736. Tools._performance.mark(counterName + "-Begin");
  10737. };
  10738. Tools._EndUserMark = function (counterName, condition) {
  10739. if (condition === void 0) { condition = true; }
  10740. if (!condition || !Tools._performance.mark) {
  10741. return;
  10742. }
  10743. Tools._performance.mark(counterName + "-End");
  10744. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  10745. };
  10746. Tools._StartPerformanceConsole = function (counterName, condition) {
  10747. if (condition === void 0) { condition = true; }
  10748. if (!condition) {
  10749. return;
  10750. }
  10751. Tools._StartUserMark(counterName, condition);
  10752. if (console.time) {
  10753. console.time(counterName);
  10754. }
  10755. };
  10756. Tools._EndPerformanceConsole = function (counterName, condition) {
  10757. if (condition === void 0) { condition = true; }
  10758. if (!condition) {
  10759. return;
  10760. }
  10761. Tools._EndUserMark(counterName, condition);
  10762. if (console.time) {
  10763. console.timeEnd(counterName);
  10764. }
  10765. };
  10766. Object.defineProperty(Tools, "Now", {
  10767. /**
  10768. * Gets either window.performance.now() if supported or Date.now() else
  10769. */
  10770. get: function () {
  10771. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  10772. return window.performance.now();
  10773. }
  10774. return Date.now();
  10775. },
  10776. enumerable: true,
  10777. configurable: true
  10778. });
  10779. /**
  10780. * This method will return the name of the class used to create the instance of the given object.
  10781. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  10782. * @param object the object to get the class name from
  10783. * @param isType defines if the object is actually a type
  10784. * @returns the name of the class, will be "object" for a custom data type not using the @className decorator
  10785. */
  10786. Tools.GetClassName = function (object, isType) {
  10787. if (isType === void 0) { isType = false; }
  10788. var name = null;
  10789. if (!isType && object.getClassName) {
  10790. name = object.getClassName();
  10791. }
  10792. else {
  10793. if (object instanceof Object) {
  10794. var classObj = isType ? object : Object.getPrototypeOf(object);
  10795. name = classObj.constructor["__bjsclassName__"];
  10796. }
  10797. if (!name) {
  10798. name = typeof object;
  10799. }
  10800. }
  10801. return name;
  10802. };
  10803. /**
  10804. * Gets the first element of an array satisfying a given predicate
  10805. * @param array defines the array to browse
  10806. * @param predicate defines the predicate to use
  10807. * @returns null if not found or the element
  10808. */
  10809. Tools.First = function (array, predicate) {
  10810. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  10811. var el = array_1[_i];
  10812. if (predicate(el)) {
  10813. return el;
  10814. }
  10815. }
  10816. return null;
  10817. };
  10818. /**
  10819. * This method will return the name of the full name of the class, including its owning module (if any).
  10820. * 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).
  10821. * @param object the object to get the class name from
  10822. * @param isType defines if the object is actually a type
  10823. * @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.
  10824. * @ignorenaming
  10825. */
  10826. Tools.getFullClassName = function (object, isType) {
  10827. if (isType === void 0) { isType = false; }
  10828. var className = null;
  10829. var moduleName = null;
  10830. if (!isType && object.getClassName) {
  10831. className = object.getClassName();
  10832. }
  10833. else {
  10834. if (object instanceof Object) {
  10835. var classObj = isType ? object : Object.getPrototypeOf(object);
  10836. className = classObj.constructor["__bjsclassName__"];
  10837. moduleName = classObj.constructor["__bjsmoduleName__"];
  10838. }
  10839. if (!className) {
  10840. className = typeof object;
  10841. }
  10842. }
  10843. if (!className) {
  10844. return null;
  10845. }
  10846. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  10847. };
  10848. /**
  10849. * Returns a promise that resolves after the given amount of time.
  10850. * @param delay Number of milliseconds to delay
  10851. * @returns Promise that resolves after the given amount of time
  10852. */
  10853. Tools.DelayAsync = function (delay) {
  10854. return new Promise(function (resolve) {
  10855. setTimeout(function () {
  10856. resolve();
  10857. }, delay);
  10858. });
  10859. };
  10860. /**
  10861. * Gets the current gradient from an array of IValueGradient
  10862. * @param ratio defines the current ratio to get
  10863. * @param gradients defines the array of IValueGradient
  10864. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  10865. */
  10866. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  10867. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  10868. var currentGradient = gradients[gradientIndex];
  10869. var nextGradient = gradients[gradientIndex + 1];
  10870. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  10871. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  10872. updateFunc(currentGradient, nextGradient, scale);
  10873. return;
  10874. }
  10875. }
  10876. // Use last index if over
  10877. var lastIndex = gradients.length - 1;
  10878. updateFunc(gradients[lastIndex], gradients[lastIndex], 1.0);
  10879. };
  10880. /**
  10881. * Gets or sets the base URL to use to load assets
  10882. */
  10883. Tools.BaseUrl = "";
  10884. /**
  10885. * Gets or sets the retry strategy to apply when an error happens while loading an asset
  10886. */
  10887. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10888. /**
  10889. * Default behaviour for cors in the application.
  10890. * It can be a string if the expected behavior is identical in the entire app.
  10891. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10892. */
  10893. Tools.CorsBehavior = "anonymous";
  10894. /**
  10895. * Gets or sets a global variable indicating if fallback texture must be used when a texture cannot be loaded
  10896. * @ignorenaming
  10897. */
  10898. Tools.UseFallbackTexture = true;
  10899. /**
  10900. * Use this object to register external classes like custom textures or material
  10901. * to allow the laoders to instantiate them
  10902. */
  10903. Tools.RegisteredExternalClasses = {};
  10904. /**
  10905. * Texture content used if a texture cannot loaded
  10906. * @ignorenaming
  10907. */
  10908. 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";
  10909. Tools._tmpFloatArray = new Float32Array(1);
  10910. /**
  10911. * Gets or sets a function used to pre-process url before using them to load assets
  10912. */
  10913. Tools.PreprocessUrl = function (url) {
  10914. return url;
  10915. };
  10916. // Logs
  10917. /**
  10918. * No log
  10919. */
  10920. Tools.NoneLogLevel = 0;
  10921. /**
  10922. * Only message logs
  10923. */
  10924. Tools.MessageLogLevel = 1;
  10925. /**
  10926. * Only warning logs
  10927. */
  10928. Tools.WarningLogLevel = 2;
  10929. /**
  10930. * Only error logs
  10931. */
  10932. Tools.ErrorLogLevel = 4;
  10933. /**
  10934. * All logs
  10935. */
  10936. Tools.AllLogLevel = 7;
  10937. Tools._LogCache = "";
  10938. /**
  10939. * Gets a value indicating the number of loading errors
  10940. * @ignorenaming
  10941. */
  10942. Tools.errorsCount = 0;
  10943. /**
  10944. * Log a message to the console
  10945. */
  10946. Tools.Log = Tools._LogEnabled;
  10947. /**
  10948. * Write a warning message to the console
  10949. */
  10950. Tools.Warn = Tools._WarnEnabled;
  10951. /**
  10952. * Write an error message to the console
  10953. */
  10954. Tools.Error = Tools._ErrorEnabled;
  10955. // Performances
  10956. /**
  10957. * No performance log
  10958. */
  10959. Tools.PerformanceNoneLogLevel = 0;
  10960. /**
  10961. * Use user marks to log performance
  10962. */
  10963. Tools.PerformanceUserMarkLogLevel = 1;
  10964. /**
  10965. * Log performance to the console
  10966. */
  10967. Tools.PerformanceConsoleLogLevel = 2;
  10968. /**
  10969. * Starts a performance counter
  10970. */
  10971. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10972. /**
  10973. * Ends a specific performance coutner
  10974. */
  10975. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10976. return Tools;
  10977. }());
  10978. BABYLON.Tools = Tools;
  10979. /**
  10980. * This class is used to track a performance counter which is number based.
  10981. * The user has access to many properties which give statistics of different nature.
  10982. *
  10983. * The implementer can track two kinds of Performance Counter: time and count.
  10984. * 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.
  10985. * 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.
  10986. */
  10987. var PerfCounter = /** @class */ (function () {
  10988. /**
  10989. * Creates a new counter
  10990. */
  10991. function PerfCounter() {
  10992. this._startMonitoringTime = 0;
  10993. this._min = 0;
  10994. this._max = 0;
  10995. this._average = 0;
  10996. this._lastSecAverage = 0;
  10997. this._current = 0;
  10998. this._totalValueCount = 0;
  10999. this._totalAccumulated = 0;
  11000. this._lastSecAccumulated = 0;
  11001. this._lastSecTime = 0;
  11002. this._lastSecValueCount = 0;
  11003. }
  11004. Object.defineProperty(PerfCounter.prototype, "min", {
  11005. /**
  11006. * Returns the smallest value ever
  11007. */
  11008. get: function () {
  11009. return this._min;
  11010. },
  11011. enumerable: true,
  11012. configurable: true
  11013. });
  11014. Object.defineProperty(PerfCounter.prototype, "max", {
  11015. /**
  11016. * Returns the biggest value ever
  11017. */
  11018. get: function () {
  11019. return this._max;
  11020. },
  11021. enumerable: true,
  11022. configurable: true
  11023. });
  11024. Object.defineProperty(PerfCounter.prototype, "average", {
  11025. /**
  11026. * Returns the average value since the performance counter is running
  11027. */
  11028. get: function () {
  11029. return this._average;
  11030. },
  11031. enumerable: true,
  11032. configurable: true
  11033. });
  11034. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  11035. /**
  11036. * Returns the average value of the last second the counter was monitored
  11037. */
  11038. get: function () {
  11039. return this._lastSecAverage;
  11040. },
  11041. enumerable: true,
  11042. configurable: true
  11043. });
  11044. Object.defineProperty(PerfCounter.prototype, "current", {
  11045. /**
  11046. * Returns the current value
  11047. */
  11048. get: function () {
  11049. return this._current;
  11050. },
  11051. enumerable: true,
  11052. configurable: true
  11053. });
  11054. Object.defineProperty(PerfCounter.prototype, "total", {
  11055. /**
  11056. * Gets the accumulated total
  11057. */
  11058. get: function () {
  11059. return this._totalAccumulated;
  11060. },
  11061. enumerable: true,
  11062. configurable: true
  11063. });
  11064. Object.defineProperty(PerfCounter.prototype, "count", {
  11065. /**
  11066. * Gets the total value count
  11067. */
  11068. get: function () {
  11069. return this._totalValueCount;
  11070. },
  11071. enumerable: true,
  11072. configurable: true
  11073. });
  11074. /**
  11075. * Call this method to start monitoring a new frame.
  11076. * 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.
  11077. */
  11078. PerfCounter.prototype.fetchNewFrame = function () {
  11079. this._totalValueCount++;
  11080. this._current = 0;
  11081. this._lastSecValueCount++;
  11082. };
  11083. /**
  11084. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  11085. * @param newCount the count value to add to the monitored count
  11086. * @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.
  11087. */
  11088. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  11089. if (!PerfCounter.Enabled) {
  11090. return;
  11091. }
  11092. this._current += newCount;
  11093. if (fetchResult) {
  11094. this._fetchResult();
  11095. }
  11096. };
  11097. /**
  11098. * Start monitoring this performance counter
  11099. */
  11100. PerfCounter.prototype.beginMonitoring = function () {
  11101. if (!PerfCounter.Enabled) {
  11102. return;
  11103. }
  11104. this._startMonitoringTime = Tools.Now;
  11105. };
  11106. /**
  11107. * Compute the time lapsed since the previous beginMonitoring() call.
  11108. * @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
  11109. */
  11110. PerfCounter.prototype.endMonitoring = function (newFrame) {
  11111. if (newFrame === void 0) { newFrame = true; }
  11112. if (!PerfCounter.Enabled) {
  11113. return;
  11114. }
  11115. if (newFrame) {
  11116. this.fetchNewFrame();
  11117. }
  11118. var currentTime = Tools.Now;
  11119. this._current = currentTime - this._startMonitoringTime;
  11120. if (newFrame) {
  11121. this._fetchResult();
  11122. }
  11123. };
  11124. PerfCounter.prototype._fetchResult = function () {
  11125. this._totalAccumulated += this._current;
  11126. this._lastSecAccumulated += this._current;
  11127. // Min/Max update
  11128. this._min = Math.min(this._min, this._current);
  11129. this._max = Math.max(this._max, this._current);
  11130. this._average = this._totalAccumulated / this._totalValueCount;
  11131. // Reset last sec?
  11132. var now = Tools.Now;
  11133. if ((now - this._lastSecTime) > 1000) {
  11134. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  11135. this._lastSecTime = now;
  11136. this._lastSecAccumulated = 0;
  11137. this._lastSecValueCount = 0;
  11138. }
  11139. };
  11140. /**
  11141. * Gets or sets a global boolean to turn on and off all the counters
  11142. */
  11143. PerfCounter.Enabled = true;
  11144. return PerfCounter;
  11145. }());
  11146. BABYLON.PerfCounter = PerfCounter;
  11147. /**
  11148. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  11149. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  11150. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  11151. * @param name The name of the class, case should be preserved
  11152. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  11153. */
  11154. function className(name, module) {
  11155. return function (target) {
  11156. target["__bjsclassName__"] = name;
  11157. target["__bjsmoduleName__"] = (module != null) ? module : null;
  11158. };
  11159. }
  11160. BABYLON.className = className;
  11161. /**
  11162. * An implementation of a loop for asynchronous functions.
  11163. */
  11164. var AsyncLoop = /** @class */ (function () {
  11165. /**
  11166. * Constructor.
  11167. * @param iterations the number of iterations.
  11168. * @param func the function to run each iteration
  11169. * @param successCallback the callback that will be called upon succesful execution
  11170. * @param offset starting offset.
  11171. */
  11172. function AsyncLoop(
  11173. /**
  11174. * Defines the number of iterations for the loop
  11175. */
  11176. iterations, func, successCallback, offset) {
  11177. if (offset === void 0) { offset = 0; }
  11178. this.iterations = iterations;
  11179. this.index = offset - 1;
  11180. this._done = false;
  11181. this._fn = func;
  11182. this._successCallback = successCallback;
  11183. }
  11184. /**
  11185. * Execute the next iteration. Must be called after the last iteration was finished.
  11186. */
  11187. AsyncLoop.prototype.executeNext = function () {
  11188. if (!this._done) {
  11189. if (this.index + 1 < this.iterations) {
  11190. ++this.index;
  11191. this._fn(this);
  11192. }
  11193. else {
  11194. this.breakLoop();
  11195. }
  11196. }
  11197. };
  11198. /**
  11199. * Break the loop and run the success callback.
  11200. */
  11201. AsyncLoop.prototype.breakLoop = function () {
  11202. this._done = true;
  11203. this._successCallback();
  11204. };
  11205. /**
  11206. * Create and run an async loop.
  11207. * @param iterations the number of iterations.
  11208. * @param fn the function to run each iteration
  11209. * @param successCallback the callback that will be called upon succesful execution
  11210. * @param offset starting offset.
  11211. * @returns the created async loop object
  11212. */
  11213. AsyncLoop.Run = function (iterations, fn, successCallback, offset) {
  11214. if (offset === void 0) { offset = 0; }
  11215. var loop = new AsyncLoop(iterations, fn, successCallback, offset);
  11216. loop.executeNext();
  11217. return loop;
  11218. };
  11219. /**
  11220. * A for-loop that will run a given number of iterations synchronous and the rest async.
  11221. * @param iterations total number of iterations
  11222. * @param syncedIterations number of synchronous iterations in each async iteration.
  11223. * @param fn the function to call each iteration.
  11224. * @param callback a success call back that will be called when iterating stops.
  11225. * @param breakFunction a break condition (optional)
  11226. * @param timeout timeout settings for the setTimeout function. default - 0.
  11227. * @returns the created async loop object
  11228. */
  11229. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  11230. if (timeout === void 0) { timeout = 0; }
  11231. return AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  11232. if (breakFunction && breakFunction()) {
  11233. loop.breakLoop();
  11234. }
  11235. else {
  11236. setTimeout(function () {
  11237. for (var i = 0; i < syncedIterations; ++i) {
  11238. var iteration = (loop.index * syncedIterations) + i;
  11239. if (iteration >= iterations) {
  11240. break;
  11241. }
  11242. fn(iteration);
  11243. if (breakFunction && breakFunction()) {
  11244. loop.breakLoop();
  11245. break;
  11246. }
  11247. }
  11248. loop.executeNext();
  11249. }, timeout);
  11250. }
  11251. }, callback);
  11252. };
  11253. return AsyncLoop;
  11254. }());
  11255. BABYLON.AsyncLoop = AsyncLoop;
  11256. })(BABYLON || (BABYLON = {}));
  11257. //# sourceMappingURL=babylon.tools.js.map
  11258. var BABYLON;
  11259. (function (BABYLON) {
  11260. var PromiseStates;
  11261. (function (PromiseStates) {
  11262. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  11263. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  11264. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  11265. })(PromiseStates || (PromiseStates = {}));
  11266. var FulFillmentAgregator = /** @class */ (function () {
  11267. function FulFillmentAgregator() {
  11268. this.count = 0;
  11269. this.target = 0;
  11270. this.results = [];
  11271. }
  11272. return FulFillmentAgregator;
  11273. }());
  11274. var InternalPromise = /** @class */ (function () {
  11275. function InternalPromise(resolver) {
  11276. var _this = this;
  11277. this._state = PromiseStates.Pending;
  11278. this._children = new Array();
  11279. this._rejectWasConsumed = false;
  11280. if (!resolver) {
  11281. return;
  11282. }
  11283. try {
  11284. resolver(function (value) {
  11285. _this._resolve(value);
  11286. }, function (reason) {
  11287. _this._reject(reason);
  11288. });
  11289. }
  11290. catch (e) {
  11291. this._reject(e);
  11292. }
  11293. }
  11294. Object.defineProperty(InternalPromise.prototype, "_result", {
  11295. get: function () {
  11296. return this._resultValue;
  11297. },
  11298. set: function (value) {
  11299. this._resultValue = value;
  11300. if (this._parent && this._parent._result === undefined) {
  11301. this._parent._result = value;
  11302. }
  11303. },
  11304. enumerable: true,
  11305. configurable: true
  11306. });
  11307. InternalPromise.prototype.catch = function (onRejected) {
  11308. return this.then(undefined, onRejected);
  11309. };
  11310. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  11311. var _this = this;
  11312. var newPromise = new InternalPromise();
  11313. newPromise._onFulfilled = onFulfilled;
  11314. newPromise._onRejected = onRejected;
  11315. // Composition
  11316. this._children.push(newPromise);
  11317. newPromise._parent = this;
  11318. if (this._state !== PromiseStates.Pending) {
  11319. BABYLON.Tools.SetImmediate(function () {
  11320. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  11321. var returnedValue = newPromise._resolve(_this._result);
  11322. if (returnedValue !== undefined && returnedValue !== null) {
  11323. if (returnedValue._state !== undefined) {
  11324. var returnedPromise = returnedValue;
  11325. newPromise._children.push(returnedPromise);
  11326. returnedPromise._parent = newPromise;
  11327. newPromise = returnedPromise;
  11328. }
  11329. else {
  11330. newPromise._result = returnedValue;
  11331. }
  11332. }
  11333. }
  11334. else {
  11335. newPromise._reject(_this._reason);
  11336. }
  11337. });
  11338. }
  11339. return newPromise;
  11340. };
  11341. InternalPromise.prototype._moveChildren = function (children) {
  11342. var _this = this;
  11343. var _a;
  11344. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  11345. this._children.forEach(function (child) {
  11346. child._parent = _this;
  11347. });
  11348. if (this._state === PromiseStates.Fulfilled) {
  11349. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  11350. var child = _b[_i];
  11351. child._resolve(this._result);
  11352. }
  11353. }
  11354. else if (this._state === PromiseStates.Rejected) {
  11355. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  11356. var child = _d[_c];
  11357. child._reject(this._reason);
  11358. }
  11359. }
  11360. };
  11361. InternalPromise.prototype._resolve = function (value) {
  11362. try {
  11363. this._state = PromiseStates.Fulfilled;
  11364. var returnedValue = null;
  11365. if (this._onFulfilled) {
  11366. returnedValue = this._onFulfilled(value);
  11367. }
  11368. if (returnedValue !== undefined && returnedValue !== null) {
  11369. if (returnedValue._state !== undefined) {
  11370. // Transmit children
  11371. var returnedPromise = returnedValue;
  11372. returnedPromise._parent = this;
  11373. returnedPromise._moveChildren(this._children);
  11374. value = returnedPromise._result;
  11375. }
  11376. else {
  11377. value = returnedValue;
  11378. }
  11379. }
  11380. this._result = value;
  11381. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  11382. var child = _a[_i];
  11383. child._resolve(value);
  11384. }
  11385. this._children.length = 0;
  11386. delete this._onFulfilled;
  11387. delete this._onRejected;
  11388. }
  11389. catch (e) {
  11390. this._reject(e, true);
  11391. }
  11392. };
  11393. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  11394. if (onLocalThrow === void 0) { onLocalThrow = false; }
  11395. this._state = PromiseStates.Rejected;
  11396. this._reason = reason;
  11397. if (this._onRejected && !onLocalThrow) {
  11398. try {
  11399. this._onRejected(reason);
  11400. this._rejectWasConsumed = true;
  11401. }
  11402. catch (e) {
  11403. reason = e;
  11404. }
  11405. }
  11406. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  11407. var child = _a[_i];
  11408. if (this._rejectWasConsumed) {
  11409. child._resolve(null);
  11410. }
  11411. else {
  11412. child._reject(reason);
  11413. }
  11414. }
  11415. this._children.length = 0;
  11416. delete this._onFulfilled;
  11417. delete this._onRejected;
  11418. };
  11419. InternalPromise.resolve = function (value) {
  11420. var newPromise = new InternalPromise();
  11421. newPromise._resolve(value);
  11422. return newPromise;
  11423. };
  11424. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  11425. promise.then(function (value) {
  11426. agregator.results[index] = value;
  11427. agregator.count++;
  11428. if (agregator.count === agregator.target) {
  11429. agregator.rootPromise._resolve(agregator.results);
  11430. }
  11431. return null;
  11432. }, function (reason) {
  11433. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  11434. agregator.rootPromise._reject(reason);
  11435. }
  11436. });
  11437. };
  11438. InternalPromise.all = function (promises) {
  11439. var newPromise = new InternalPromise();
  11440. var agregator = new FulFillmentAgregator();
  11441. agregator.target = promises.length;
  11442. agregator.rootPromise = newPromise;
  11443. if (promises.length) {
  11444. for (var index = 0; index < promises.length; index++) {
  11445. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  11446. }
  11447. }
  11448. else {
  11449. newPromise._resolve([]);
  11450. }
  11451. return newPromise;
  11452. };
  11453. InternalPromise.race = function (promises) {
  11454. var newPromise = new InternalPromise();
  11455. if (promises.length) {
  11456. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  11457. var promise = promises_1[_i];
  11458. promise.then(function (value) {
  11459. if (newPromise) {
  11460. newPromise._resolve(value);
  11461. newPromise = null;
  11462. }
  11463. return null;
  11464. }, function (reason) {
  11465. if (newPromise) {
  11466. newPromise._reject(reason);
  11467. newPromise = null;
  11468. }
  11469. });
  11470. }
  11471. }
  11472. return newPromise;
  11473. };
  11474. return InternalPromise;
  11475. }());
  11476. /**
  11477. * Helper class that provides a small promise polyfill
  11478. */
  11479. var PromisePolyfill = /** @class */ (function () {
  11480. function PromisePolyfill() {
  11481. }
  11482. /**
  11483. * Static function used to check if the polyfill is required
  11484. * If this is the case then the function will inject the polyfill to window.Promise
  11485. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  11486. */
  11487. PromisePolyfill.Apply = function (force) {
  11488. if (force === void 0) { force = false; }
  11489. if (force || typeof Promise === 'undefined') {
  11490. var root = window;
  11491. root.Promise = InternalPromise;
  11492. }
  11493. };
  11494. return PromisePolyfill;
  11495. }());
  11496. BABYLON.PromisePolyfill = PromisePolyfill;
  11497. })(BABYLON || (BABYLON = {}));
  11498. //# sourceMappingURL=babylon.promise.js.map
  11499. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  11500. var BABYLON;
  11501. (function (BABYLON) {
  11502. /**
  11503. * Helper class to push actions to a pool of workers.
  11504. */
  11505. var WorkerPool = /** @class */ (function () {
  11506. /**
  11507. * Constructor
  11508. * @param workers Array of workers to use for actions
  11509. */
  11510. function WorkerPool(workers) {
  11511. this._pendingActions = new Array();
  11512. this._workerInfos = workers.map(function (worker) { return ({
  11513. worker: worker,
  11514. active: false
  11515. }); });
  11516. }
  11517. /**
  11518. * Terminates all workers and clears any pending actions.
  11519. */
  11520. WorkerPool.prototype.dispose = function () {
  11521. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  11522. var workerInfo = _a[_i];
  11523. workerInfo.worker.terminate();
  11524. }
  11525. delete this._workerInfos;
  11526. delete this._pendingActions;
  11527. };
  11528. /**
  11529. * Pushes an action to the worker pool. If all the workers are active, the action will be
  11530. * pended until a worker has completed its action.
  11531. * @param action The action to perform. Call onComplete when the action is complete.
  11532. */
  11533. WorkerPool.prototype.push = function (action) {
  11534. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  11535. var workerInfo = _a[_i];
  11536. if (!workerInfo.active) {
  11537. this._execute(workerInfo, action);
  11538. return;
  11539. }
  11540. }
  11541. this._pendingActions.push(action);
  11542. };
  11543. WorkerPool.prototype._execute = function (workerInfo, action) {
  11544. var _this = this;
  11545. workerInfo.active = true;
  11546. action(workerInfo.worker, function () {
  11547. workerInfo.active = false;
  11548. var nextAction = _this._pendingActions.shift();
  11549. if (nextAction) {
  11550. _this._execute(workerInfo, nextAction);
  11551. }
  11552. });
  11553. };
  11554. return WorkerPool;
  11555. }());
  11556. BABYLON.WorkerPool = WorkerPool;
  11557. })(BABYLON || (BABYLON = {}));
  11558. //# sourceMappingURL=babylon.workerPool.js.map
  11559. var BABYLON;
  11560. (function (BABYLON) {
  11561. /**
  11562. * @hidden
  11563. **/
  11564. var _AlphaState = /** @class */ (function () {
  11565. /**
  11566. * Initializes the state.
  11567. */
  11568. function _AlphaState() {
  11569. this._isAlphaBlendDirty = false;
  11570. this._isBlendFunctionParametersDirty = false;
  11571. this._isBlendEquationParametersDirty = false;
  11572. this._isBlendConstantsDirty = false;
  11573. this._alphaBlend = false;
  11574. this._blendFunctionParameters = new Array(4);
  11575. this._blendEquationParameters = new Array(2);
  11576. this._blendConstants = new Array(4);
  11577. this.reset();
  11578. }
  11579. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  11580. get: function () {
  11581. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  11582. },
  11583. enumerable: true,
  11584. configurable: true
  11585. });
  11586. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  11587. get: function () {
  11588. return this._alphaBlend;
  11589. },
  11590. set: function (value) {
  11591. if (this._alphaBlend === value) {
  11592. return;
  11593. }
  11594. this._alphaBlend = value;
  11595. this._isAlphaBlendDirty = true;
  11596. },
  11597. enumerable: true,
  11598. configurable: true
  11599. });
  11600. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  11601. if (this._blendConstants[0] === r &&
  11602. this._blendConstants[1] === g &&
  11603. this._blendConstants[2] === b &&
  11604. this._blendConstants[3] === a) {
  11605. return;
  11606. }
  11607. this._blendConstants[0] = r;
  11608. this._blendConstants[1] = g;
  11609. this._blendConstants[2] = b;
  11610. this._blendConstants[3] = a;
  11611. this._isBlendConstantsDirty = true;
  11612. };
  11613. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  11614. if (this._blendFunctionParameters[0] === value0 &&
  11615. this._blendFunctionParameters[1] === value1 &&
  11616. this._blendFunctionParameters[2] === value2 &&
  11617. this._blendFunctionParameters[3] === value3) {
  11618. return;
  11619. }
  11620. this._blendFunctionParameters[0] = value0;
  11621. this._blendFunctionParameters[1] = value1;
  11622. this._blendFunctionParameters[2] = value2;
  11623. this._blendFunctionParameters[3] = value3;
  11624. this._isBlendFunctionParametersDirty = true;
  11625. };
  11626. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  11627. if (this._blendEquationParameters[0] === rgb &&
  11628. this._blendEquationParameters[1] === alpha) {
  11629. return;
  11630. }
  11631. this._blendEquationParameters[0] = rgb;
  11632. this._blendEquationParameters[1] = alpha;
  11633. this._isBlendEquationParametersDirty = true;
  11634. };
  11635. _AlphaState.prototype.reset = function () {
  11636. this._alphaBlend = false;
  11637. this._blendFunctionParameters[0] = null;
  11638. this._blendFunctionParameters[1] = null;
  11639. this._blendFunctionParameters[2] = null;
  11640. this._blendFunctionParameters[3] = null;
  11641. this._blendEquationParameters[0] = null;
  11642. this._blendEquationParameters[1] = null;
  11643. this._blendConstants[0] = null;
  11644. this._blendConstants[1] = null;
  11645. this._blendConstants[2] = null;
  11646. this._blendConstants[3] = null;
  11647. this._isAlphaBlendDirty = true;
  11648. this._isBlendFunctionParametersDirty = false;
  11649. this._isBlendEquationParametersDirty = false;
  11650. this._isBlendConstantsDirty = false;
  11651. };
  11652. _AlphaState.prototype.apply = function (gl) {
  11653. if (!this.isDirty) {
  11654. return;
  11655. }
  11656. // Alpha blend
  11657. if (this._isAlphaBlendDirty) {
  11658. if (this._alphaBlend) {
  11659. gl.enable(gl.BLEND);
  11660. }
  11661. else {
  11662. gl.disable(gl.BLEND);
  11663. }
  11664. this._isAlphaBlendDirty = false;
  11665. }
  11666. // Alpha function
  11667. if (this._isBlendFunctionParametersDirty) {
  11668. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  11669. this._isBlendFunctionParametersDirty = false;
  11670. }
  11671. // Alpha equation
  11672. if (this._isBlendEquationParametersDirty) {
  11673. gl.blendEquationSeparate(this._blendEquationParameters[0], this._blendEquationParameters[1]);
  11674. this._isBlendEquationParametersDirty = false;
  11675. }
  11676. // Constants
  11677. if (this._isBlendConstantsDirty) {
  11678. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  11679. this._isBlendConstantsDirty = false;
  11680. }
  11681. };
  11682. return _AlphaState;
  11683. }());
  11684. BABYLON._AlphaState = _AlphaState;
  11685. })(BABYLON || (BABYLON = {}));
  11686. //# sourceMappingURL=babylon.alphaCullingState.js.map
  11687. var BABYLON;
  11688. (function (BABYLON) {
  11689. /**
  11690. * @hidden
  11691. **/
  11692. var _DepthCullingState = /** @class */ (function () {
  11693. /**
  11694. * Initializes the state.
  11695. */
  11696. function _DepthCullingState() {
  11697. this._isDepthTestDirty = false;
  11698. this._isDepthMaskDirty = false;
  11699. this._isDepthFuncDirty = false;
  11700. this._isCullFaceDirty = false;
  11701. this._isCullDirty = false;
  11702. this._isZOffsetDirty = false;
  11703. this._isFrontFaceDirty = false;
  11704. this.reset();
  11705. }
  11706. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  11707. get: function () {
  11708. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  11709. },
  11710. enumerable: true,
  11711. configurable: true
  11712. });
  11713. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  11714. get: function () {
  11715. return this._zOffset;
  11716. },
  11717. set: function (value) {
  11718. if (this._zOffset === value) {
  11719. return;
  11720. }
  11721. this._zOffset = value;
  11722. this._isZOffsetDirty = true;
  11723. },
  11724. enumerable: true,
  11725. configurable: true
  11726. });
  11727. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  11728. get: function () {
  11729. return this._cullFace;
  11730. },
  11731. set: function (value) {
  11732. if (this._cullFace === value) {
  11733. return;
  11734. }
  11735. this._cullFace = value;
  11736. this._isCullFaceDirty = true;
  11737. },
  11738. enumerable: true,
  11739. configurable: true
  11740. });
  11741. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  11742. get: function () {
  11743. return this._cull;
  11744. },
  11745. set: function (value) {
  11746. if (this._cull === value) {
  11747. return;
  11748. }
  11749. this._cull = value;
  11750. this._isCullDirty = true;
  11751. },
  11752. enumerable: true,
  11753. configurable: true
  11754. });
  11755. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  11756. get: function () {
  11757. return this._depthFunc;
  11758. },
  11759. set: function (value) {
  11760. if (this._depthFunc === value) {
  11761. return;
  11762. }
  11763. this._depthFunc = value;
  11764. this._isDepthFuncDirty = true;
  11765. },
  11766. enumerable: true,
  11767. configurable: true
  11768. });
  11769. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  11770. get: function () {
  11771. return this._depthMask;
  11772. },
  11773. set: function (value) {
  11774. if (this._depthMask === value) {
  11775. return;
  11776. }
  11777. this._depthMask = value;
  11778. this._isDepthMaskDirty = true;
  11779. },
  11780. enumerable: true,
  11781. configurable: true
  11782. });
  11783. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  11784. get: function () {
  11785. return this._depthTest;
  11786. },
  11787. set: function (value) {
  11788. if (this._depthTest === value) {
  11789. return;
  11790. }
  11791. this._depthTest = value;
  11792. this._isDepthTestDirty = true;
  11793. },
  11794. enumerable: true,
  11795. configurable: true
  11796. });
  11797. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  11798. get: function () {
  11799. return this._frontFace;
  11800. },
  11801. set: function (value) {
  11802. if (this._frontFace === value) {
  11803. return;
  11804. }
  11805. this._frontFace = value;
  11806. this._isFrontFaceDirty = true;
  11807. },
  11808. enumerable: true,
  11809. configurable: true
  11810. });
  11811. _DepthCullingState.prototype.reset = function () {
  11812. this._depthMask = true;
  11813. this._depthTest = true;
  11814. this._depthFunc = null;
  11815. this._cullFace = null;
  11816. this._cull = null;
  11817. this._zOffset = 0;
  11818. this._frontFace = null;
  11819. this._isDepthTestDirty = true;
  11820. this._isDepthMaskDirty = true;
  11821. this._isDepthFuncDirty = false;
  11822. this._isCullFaceDirty = false;
  11823. this._isCullDirty = false;
  11824. this._isZOffsetDirty = false;
  11825. this._isFrontFaceDirty = false;
  11826. };
  11827. _DepthCullingState.prototype.apply = function (gl) {
  11828. if (!this.isDirty) {
  11829. return;
  11830. }
  11831. // Cull
  11832. if (this._isCullDirty) {
  11833. if (this.cull) {
  11834. gl.enable(gl.CULL_FACE);
  11835. }
  11836. else {
  11837. gl.disable(gl.CULL_FACE);
  11838. }
  11839. this._isCullDirty = false;
  11840. }
  11841. // Cull face
  11842. if (this._isCullFaceDirty) {
  11843. gl.cullFace(this.cullFace);
  11844. this._isCullFaceDirty = false;
  11845. }
  11846. // Depth mask
  11847. if (this._isDepthMaskDirty) {
  11848. gl.depthMask(this.depthMask);
  11849. this._isDepthMaskDirty = false;
  11850. }
  11851. // Depth test
  11852. if (this._isDepthTestDirty) {
  11853. if (this.depthTest) {
  11854. gl.enable(gl.DEPTH_TEST);
  11855. }
  11856. else {
  11857. gl.disable(gl.DEPTH_TEST);
  11858. }
  11859. this._isDepthTestDirty = false;
  11860. }
  11861. // Depth func
  11862. if (this._isDepthFuncDirty) {
  11863. gl.depthFunc(this.depthFunc);
  11864. this._isDepthFuncDirty = false;
  11865. }
  11866. // zOffset
  11867. if (this._isZOffsetDirty) {
  11868. if (this.zOffset) {
  11869. gl.enable(gl.POLYGON_OFFSET_FILL);
  11870. gl.polygonOffset(this.zOffset, 0);
  11871. }
  11872. else {
  11873. gl.disable(gl.POLYGON_OFFSET_FILL);
  11874. }
  11875. this._isZOffsetDirty = false;
  11876. }
  11877. // Front face
  11878. if (this._isFrontFaceDirty) {
  11879. gl.frontFace(this.frontFace);
  11880. this._isFrontFaceDirty = false;
  11881. }
  11882. };
  11883. return _DepthCullingState;
  11884. }());
  11885. BABYLON._DepthCullingState = _DepthCullingState;
  11886. })(BABYLON || (BABYLON = {}));
  11887. //# sourceMappingURL=babylon.depthCullingState.js.map
  11888. var BABYLON;
  11889. (function (BABYLON) {
  11890. /**
  11891. * @hidden
  11892. **/
  11893. var _StencilState = /** @class */ (function () {
  11894. function _StencilState() {
  11895. this._isStencilTestDirty = false;
  11896. this._isStencilMaskDirty = false;
  11897. this._isStencilFuncDirty = false;
  11898. this._isStencilOpDirty = false;
  11899. this.reset();
  11900. }
  11901. Object.defineProperty(_StencilState.prototype, "isDirty", {
  11902. get: function () {
  11903. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  11904. },
  11905. enumerable: true,
  11906. configurable: true
  11907. });
  11908. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  11909. get: function () {
  11910. return this._stencilFunc;
  11911. },
  11912. set: function (value) {
  11913. if (this._stencilFunc === value) {
  11914. return;
  11915. }
  11916. this._stencilFunc = value;
  11917. this._isStencilFuncDirty = true;
  11918. },
  11919. enumerable: true,
  11920. configurable: true
  11921. });
  11922. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  11923. get: function () {
  11924. return this._stencilFuncRef;
  11925. },
  11926. set: function (value) {
  11927. if (this._stencilFuncRef === value) {
  11928. return;
  11929. }
  11930. this._stencilFuncRef = value;
  11931. this._isStencilFuncDirty = true;
  11932. },
  11933. enumerable: true,
  11934. configurable: true
  11935. });
  11936. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11937. get: function () {
  11938. return this._stencilFuncMask;
  11939. },
  11940. set: function (value) {
  11941. if (this._stencilFuncMask === value) {
  11942. return;
  11943. }
  11944. this._stencilFuncMask = value;
  11945. this._isStencilFuncDirty = true;
  11946. },
  11947. enumerable: true,
  11948. configurable: true
  11949. });
  11950. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11951. get: function () {
  11952. return this._stencilOpStencilFail;
  11953. },
  11954. set: function (value) {
  11955. if (this._stencilOpStencilFail === value) {
  11956. return;
  11957. }
  11958. this._stencilOpStencilFail = value;
  11959. this._isStencilOpDirty = true;
  11960. },
  11961. enumerable: true,
  11962. configurable: true
  11963. });
  11964. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11965. get: function () {
  11966. return this._stencilOpDepthFail;
  11967. },
  11968. set: function (value) {
  11969. if (this._stencilOpDepthFail === value) {
  11970. return;
  11971. }
  11972. this._stencilOpDepthFail = value;
  11973. this._isStencilOpDirty = true;
  11974. },
  11975. enumerable: true,
  11976. configurable: true
  11977. });
  11978. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11979. get: function () {
  11980. return this._stencilOpStencilDepthPass;
  11981. },
  11982. set: function (value) {
  11983. if (this._stencilOpStencilDepthPass === value) {
  11984. return;
  11985. }
  11986. this._stencilOpStencilDepthPass = value;
  11987. this._isStencilOpDirty = true;
  11988. },
  11989. enumerable: true,
  11990. configurable: true
  11991. });
  11992. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11993. get: function () {
  11994. return this._stencilMask;
  11995. },
  11996. set: function (value) {
  11997. if (this._stencilMask === value) {
  11998. return;
  11999. }
  12000. this._stencilMask = value;
  12001. this._isStencilMaskDirty = true;
  12002. },
  12003. enumerable: true,
  12004. configurable: true
  12005. });
  12006. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  12007. get: function () {
  12008. return this._stencilTest;
  12009. },
  12010. set: function (value) {
  12011. if (this._stencilTest === value) {
  12012. return;
  12013. }
  12014. this._stencilTest = value;
  12015. this._isStencilTestDirty = true;
  12016. },
  12017. enumerable: true,
  12018. configurable: true
  12019. });
  12020. _StencilState.prototype.reset = function () {
  12021. this._stencilTest = false;
  12022. this._stencilMask = 0xFF;
  12023. this._stencilFunc = BABYLON.Engine.ALWAYS;
  12024. this._stencilFuncRef = 1;
  12025. this._stencilFuncMask = 0xFF;
  12026. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  12027. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  12028. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  12029. this._isStencilTestDirty = true;
  12030. this._isStencilMaskDirty = true;
  12031. this._isStencilFuncDirty = true;
  12032. this._isStencilOpDirty = true;
  12033. };
  12034. _StencilState.prototype.apply = function (gl) {
  12035. if (!this.isDirty) {
  12036. return;
  12037. }
  12038. // Stencil test
  12039. if (this._isStencilTestDirty) {
  12040. if (this.stencilTest) {
  12041. gl.enable(gl.STENCIL_TEST);
  12042. }
  12043. else {
  12044. gl.disable(gl.STENCIL_TEST);
  12045. }
  12046. this._isStencilTestDirty = false;
  12047. }
  12048. // Stencil mask
  12049. if (this._isStencilMaskDirty) {
  12050. gl.stencilMask(this.stencilMask);
  12051. this._isStencilMaskDirty = false;
  12052. }
  12053. // Stencil func
  12054. if (this._isStencilFuncDirty) {
  12055. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  12056. this._isStencilFuncDirty = false;
  12057. }
  12058. // Stencil op
  12059. if (this._isStencilOpDirty) {
  12060. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  12061. this._isStencilOpDirty = false;
  12062. }
  12063. };
  12064. return _StencilState;
  12065. }());
  12066. BABYLON._StencilState = _StencilState;
  12067. })(BABYLON || (BABYLON = {}));
  12068. //# sourceMappingURL=babylon.stencilState.js.map
  12069. var __assign = (this && this.__assign) || function () {
  12070. __assign = Object.assign || function(t) {
  12071. for (var s, i = 1, n = arguments.length; i < n; i++) {
  12072. s = arguments[i];
  12073. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  12074. t[p] = s[p];
  12075. }
  12076. return t;
  12077. };
  12078. return __assign.apply(this, arguments);
  12079. };
  12080. var BABYLON;
  12081. (function (BABYLON) {
  12082. /**
  12083. * Keeps track of all the buffer info used in engine.
  12084. */
  12085. var BufferPointer = /** @class */ (function () {
  12086. function BufferPointer() {
  12087. }
  12088. return BufferPointer;
  12089. }());
  12090. /**
  12091. * Interface for attribute information associated with buffer instanciation
  12092. */
  12093. var InstancingAttributeInfo = /** @class */ (function () {
  12094. function InstancingAttributeInfo() {
  12095. }
  12096. return InstancingAttributeInfo;
  12097. }());
  12098. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  12099. /**
  12100. * Define options used to create a render target texture
  12101. */
  12102. var RenderTargetCreationOptions = /** @class */ (function () {
  12103. function RenderTargetCreationOptions() {
  12104. }
  12105. return RenderTargetCreationOptions;
  12106. }());
  12107. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  12108. /**
  12109. * Define options used to create a depth texture
  12110. */
  12111. var DepthTextureCreationOptions = /** @class */ (function () {
  12112. function DepthTextureCreationOptions() {
  12113. }
  12114. return DepthTextureCreationOptions;
  12115. }());
  12116. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  12117. /**
  12118. * Class used to describe the capabilities of the engine relatively to the current browser
  12119. */
  12120. var EngineCapabilities = /** @class */ (function () {
  12121. function EngineCapabilities() {
  12122. }
  12123. return EngineCapabilities;
  12124. }());
  12125. BABYLON.EngineCapabilities = EngineCapabilities;
  12126. /**
  12127. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  12128. */
  12129. var Engine = /** @class */ (function () {
  12130. /**
  12131. * Creates a new engine
  12132. * @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
  12133. * @param antialias defines enable antialiasing (default: false)
  12134. * @param options defines further options to be sent to the getContext() function
  12135. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  12136. */
  12137. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  12138. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  12139. var _this = this;
  12140. // Public members
  12141. /**
  12142. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  12143. */
  12144. this.forcePOTTextures = false;
  12145. /**
  12146. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  12147. */
  12148. this.isFullscreen = false;
  12149. /**
  12150. * Gets a boolean indicating if the pointer is currently locked
  12151. */
  12152. this.isPointerLock = false;
  12153. /**
  12154. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  12155. */
  12156. this.cullBackFaces = true;
  12157. /**
  12158. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  12159. */
  12160. this.renderEvenInBackground = true;
  12161. /**
  12162. * Gets or sets a boolean indicating that cache can be kept between frames
  12163. */
  12164. this.preventCacheWipeBetweenFrames = false;
  12165. /**
  12166. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  12167. **/
  12168. this.enableOfflineSupport = false;
  12169. /**
  12170. * 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)
  12171. **/
  12172. this.disableManifestCheck = false;
  12173. /**
  12174. * Gets the list of created scenes
  12175. */
  12176. this.scenes = new Array();
  12177. /**
  12178. * Gets the list of created postprocesses
  12179. */
  12180. this.postProcesses = new Array();
  12181. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  12182. this.validateShaderPrograms = false;
  12183. // Observables
  12184. /**
  12185. * Observable event triggered each time the rendering canvas is resized
  12186. */
  12187. this.onResizeObservable = new BABYLON.Observable();
  12188. /**
  12189. * Observable event triggered each time the canvas loses focus
  12190. */
  12191. this.onCanvasBlurObservable = new BABYLON.Observable();
  12192. /**
  12193. * Observable event triggered each time the canvas gains focus
  12194. */
  12195. this.onCanvasFocusObservable = new BABYLON.Observable();
  12196. /**
  12197. * Observable event triggered each time the canvas receives pointerout event
  12198. */
  12199. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  12200. /**
  12201. * Observable event triggered before each texture is initialized
  12202. */
  12203. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  12204. //WebVR
  12205. this._vrDisplay = undefined;
  12206. this._vrSupported = false;
  12207. this._vrExclusivePointerMode = false;
  12208. // Uniform buffers list
  12209. /**
  12210. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  12211. */
  12212. this.disableUniformBuffers = false;
  12213. /** @hidden */
  12214. this._uniformBuffers = new Array();
  12215. // Observables
  12216. /**
  12217. * Observable raised when the engine begins a new frame
  12218. */
  12219. this.onBeginFrameObservable = new BABYLON.Observable();
  12220. /**
  12221. * Observable raised when the engine ends the current frame
  12222. */
  12223. this.onEndFrameObservable = new BABYLON.Observable();
  12224. /**
  12225. * Observable raised when the engine is about to compile a shader
  12226. */
  12227. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  12228. /**
  12229. * Observable raised when the engine has jsut compiled a shader
  12230. */
  12231. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  12232. this._windowIsBackground = false;
  12233. this._webGLVersion = 1.0;
  12234. /** @hidden */
  12235. this._badOS = false;
  12236. /** @hidden */
  12237. this._badDesktopOS = false;
  12238. /**
  12239. * Gets or sets a value indicating if we want to disable texture binding optmization.
  12240. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  12241. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  12242. */
  12243. this.disableTextureBindingOptimization = false;
  12244. /**
  12245. * Observable signaled when VR display mode changes
  12246. */
  12247. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  12248. /**
  12249. * Observable signaled when VR request present is complete
  12250. */
  12251. this.onVRRequestPresentComplete = new BABYLON.Observable();
  12252. /**
  12253. * Observable signaled when VR request present starts
  12254. */
  12255. this.onVRRequestPresentStart = new BABYLON.Observable();
  12256. this._colorWrite = true;
  12257. /** @hidden */
  12258. this._drawCalls = new BABYLON.PerfCounter();
  12259. /** @hidden */
  12260. this._textureCollisions = new BABYLON.PerfCounter();
  12261. this._renderingQueueLaunched = false;
  12262. this._activeRenderLoops = new Array();
  12263. // Deterministic lockstepMaxSteps
  12264. this._deterministicLockstep = false;
  12265. this._lockstepMaxSteps = 4;
  12266. // Lost context
  12267. /**
  12268. * Observable signaled when a context lost event is raised
  12269. */
  12270. this.onContextLostObservable = new BABYLON.Observable();
  12271. /**
  12272. * Observable signaled when a context restored event is raised
  12273. */
  12274. this.onContextRestoredObservable = new BABYLON.Observable();
  12275. this._contextWasLost = false;
  12276. this._doNotHandleContextLost = false;
  12277. // FPS
  12278. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  12279. this._fps = 60;
  12280. this._deltaTime = 0;
  12281. /**
  12282. * Turn this value on if you want to pause FPS computation when in background
  12283. */
  12284. this.disablePerformanceMonitorInBackground = false;
  12285. // States
  12286. /** @hidden */
  12287. this._depthCullingState = new BABYLON._DepthCullingState();
  12288. /** @hidden */
  12289. this._stencilState = new BABYLON._StencilState();
  12290. /** @hidden */
  12291. this._alphaState = new BABYLON._AlphaState();
  12292. /** @hidden */
  12293. this._alphaMode = Engine.ALPHA_DISABLE;
  12294. // Cache
  12295. this._internalTexturesCache = new Array();
  12296. /** @hidden */
  12297. this._activeChannel = 0;
  12298. this._currentTextureChannel = -1;
  12299. /** @hidden */
  12300. this._boundTexturesCache = {};
  12301. this._compiledEffects = {};
  12302. this._vertexAttribArraysEnabled = [];
  12303. this._uintIndicesCurrentlySet = false;
  12304. this._currentBoundBuffer = new Array();
  12305. /** @hidden */
  12306. this._currentFramebuffer = null;
  12307. this._currentBufferPointers = new Array();
  12308. this._currentInstanceLocations = new Array();
  12309. this._currentInstanceBuffers = new Array();
  12310. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  12311. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  12312. this._vaoRecordInProgress = false;
  12313. this._mustWipeVertexAttributes = false;
  12314. this._nextFreeTextureSlots = new Array();
  12315. this._maxSimultaneousTextures = 0;
  12316. this._activeRequests = new Array();
  12317. // Hardware supported Compressed Textures
  12318. this._texturesSupported = new Array();
  12319. /**
  12320. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  12321. */
  12322. this.premultipliedAlpha = true;
  12323. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  12324. this._onVRFullScreenTriggered = function () {
  12325. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  12326. //get the old size before we change
  12327. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  12328. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  12329. //get the width and height, change the render size
  12330. var leftEye = _this._vrDisplay.getEyeParameters('left');
  12331. _this.setHardwareScalingLevel(1);
  12332. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  12333. }
  12334. else {
  12335. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  12336. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  12337. }
  12338. };
  12339. this._unpackFlipYCached = null;
  12340. /**
  12341. * In case you are sharing the context with other applications, it might
  12342. * be interested to not cache the unpack flip y state to ensure a consistent
  12343. * value would be set.
  12344. */
  12345. this.enableUnpackFlipYCached = true;
  12346. this._boundUniforms = {};
  12347. // Register promises
  12348. BABYLON.PromisePolyfill.Apply();
  12349. var canvas = null;
  12350. Engine.Instances.push(this);
  12351. if (!canvasOrContext) {
  12352. return;
  12353. }
  12354. options = options || {};
  12355. if (canvasOrContext.getContext) {
  12356. canvas = canvasOrContext;
  12357. this._renderingCanvas = canvas;
  12358. if (antialias != null) {
  12359. options.antialias = antialias;
  12360. }
  12361. if (options.deterministicLockstep === undefined) {
  12362. options.deterministicLockstep = false;
  12363. }
  12364. if (options.lockstepMaxSteps === undefined) {
  12365. options.lockstepMaxSteps = 4;
  12366. }
  12367. if (options.preserveDrawingBuffer === undefined) {
  12368. options.preserveDrawingBuffer = false;
  12369. }
  12370. if (options.audioEngine === undefined) {
  12371. options.audioEngine = true;
  12372. }
  12373. if (options.stencil === undefined) {
  12374. options.stencil = true;
  12375. }
  12376. if (options.premultipliedAlpha === false) {
  12377. this.premultipliedAlpha = false;
  12378. }
  12379. this._deterministicLockstep = options.deterministicLockstep;
  12380. this._lockstepMaxSteps = options.lockstepMaxSteps;
  12381. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  12382. // Exceptions
  12383. if (navigator && navigator.userAgent) {
  12384. var ua = navigator.userAgent;
  12385. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  12386. var exception = _a[_i];
  12387. var key = exception.key;
  12388. var targets = exception.targets;
  12389. if (ua.indexOf(key) > -1) {
  12390. if (exception.capture && exception.captureConstraint) {
  12391. var capture = exception.capture;
  12392. var constraint = exception.captureConstraint;
  12393. var regex = new RegExp(capture);
  12394. var matches = regex.exec(ua);
  12395. if (matches && matches.length > 0) {
  12396. var capturedValue = parseInt(matches[matches.length - 1]);
  12397. if (capturedValue >= constraint) {
  12398. continue;
  12399. }
  12400. }
  12401. }
  12402. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  12403. var target = targets_1[_b];
  12404. switch (target) {
  12405. case "uniformBuffer":
  12406. this.disableUniformBuffers = true;
  12407. break;
  12408. case "textureBindingOptimization":
  12409. this.disableTextureBindingOptimization = true;
  12410. break;
  12411. }
  12412. }
  12413. }
  12414. }
  12415. }
  12416. // GL
  12417. if (!options.disableWebGL2Support) {
  12418. try {
  12419. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  12420. if (this._gl) {
  12421. this._webGLVersion = 2.0;
  12422. // Prevent weird browsers to lie :-)
  12423. if (!this._gl.deleteQuery) {
  12424. this._webGLVersion = 1.0;
  12425. }
  12426. }
  12427. }
  12428. catch (e) {
  12429. // Do nothing
  12430. }
  12431. }
  12432. if (!this._gl) {
  12433. if (!canvas) {
  12434. throw new Error("The provided canvas is null or undefined.");
  12435. }
  12436. try {
  12437. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  12438. }
  12439. catch (e) {
  12440. throw new Error("WebGL not supported");
  12441. }
  12442. }
  12443. if (!this._gl) {
  12444. throw new Error("WebGL not supported");
  12445. }
  12446. this._onCanvasFocus = function () {
  12447. _this.onCanvasFocusObservable.notifyObservers(_this);
  12448. };
  12449. this._onCanvasBlur = function () {
  12450. _this.onCanvasBlurObservable.notifyObservers(_this);
  12451. };
  12452. canvas.addEventListener("focus", this._onCanvasFocus);
  12453. canvas.addEventListener("blur", this._onCanvasBlur);
  12454. this._onBlur = function () {
  12455. if (_this.disablePerformanceMonitorInBackground) {
  12456. _this._performanceMonitor.disable();
  12457. }
  12458. _this._windowIsBackground = true;
  12459. };
  12460. this._onFocus = function () {
  12461. if (_this.disablePerformanceMonitorInBackground) {
  12462. _this._performanceMonitor.enable();
  12463. }
  12464. _this._windowIsBackground = false;
  12465. };
  12466. this._onCanvasPointerOut = function (ev) {
  12467. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  12468. };
  12469. window.addEventListener("blur", this._onBlur);
  12470. window.addEventListener("focus", this._onFocus);
  12471. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  12472. // Context lost
  12473. if (!this._doNotHandleContextLost) {
  12474. this._onContextLost = function (evt) {
  12475. evt.preventDefault();
  12476. _this._contextWasLost = true;
  12477. BABYLON.Tools.Warn("WebGL context lost.");
  12478. _this.onContextLostObservable.notifyObservers(_this);
  12479. };
  12480. this._onContextRestored = function (evt) {
  12481. // Adding a timeout to avoid race condition at browser level
  12482. setTimeout(function () {
  12483. // Rebuild gl context
  12484. _this._initGLContext();
  12485. // Rebuild effects
  12486. _this._rebuildEffects();
  12487. // Rebuild textures
  12488. _this._rebuildInternalTextures();
  12489. // Rebuild buffers
  12490. _this._rebuildBuffers();
  12491. // Cache
  12492. _this.wipeCaches(true);
  12493. BABYLON.Tools.Warn("WebGL context successfully restored.");
  12494. _this.onContextRestoredObservable.notifyObservers(_this);
  12495. _this._contextWasLost = false;
  12496. }, 0);
  12497. };
  12498. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  12499. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  12500. }
  12501. }
  12502. else {
  12503. this._gl = canvasOrContext;
  12504. this._renderingCanvas = this._gl.canvas;
  12505. if (this._gl.renderbufferStorageMultisample) {
  12506. this._webGLVersion = 2.0;
  12507. }
  12508. var attributes = this._gl.getContextAttributes();
  12509. if (attributes) {
  12510. options.stencil = attributes.stencil;
  12511. }
  12512. }
  12513. // Viewport
  12514. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  12515. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  12516. this.resize();
  12517. this._isStencilEnable = options.stencil ? true : false;
  12518. this._initGLContext();
  12519. if (canvas) {
  12520. // Fullscreen
  12521. this._onFullscreenChange = function () {
  12522. if (document.fullscreen !== undefined) {
  12523. _this.isFullscreen = document.fullscreen;
  12524. }
  12525. else if (document.mozFullScreen !== undefined) {
  12526. _this.isFullscreen = document.mozFullScreen;
  12527. }
  12528. else if (document.webkitIsFullScreen !== undefined) {
  12529. _this.isFullscreen = document.webkitIsFullScreen;
  12530. }
  12531. else if (document.msIsFullScreen !== undefined) {
  12532. _this.isFullscreen = document.msIsFullScreen;
  12533. }
  12534. // Pointer lock
  12535. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  12536. canvas.requestPointerLock = canvas.requestPointerLock ||
  12537. canvas.msRequestPointerLock ||
  12538. canvas.mozRequestPointerLock ||
  12539. canvas.webkitRequestPointerLock;
  12540. if (canvas.requestPointerLock) {
  12541. canvas.requestPointerLock();
  12542. }
  12543. }
  12544. };
  12545. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  12546. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  12547. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  12548. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  12549. // Pointer lock
  12550. this._onPointerLockChange = function () {
  12551. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  12552. document.webkitPointerLockElement === canvas ||
  12553. document.msPointerLockElement === canvas ||
  12554. document.pointerLockElement === canvas);
  12555. };
  12556. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  12557. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  12558. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  12559. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  12560. this._onVRDisplayPointerRestricted = function () {
  12561. if (canvas) {
  12562. canvas.requestPointerLock();
  12563. }
  12564. };
  12565. this._onVRDisplayPointerUnrestricted = function () {
  12566. document.exitPointerLock();
  12567. };
  12568. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  12569. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  12570. }
  12571. // Create Audio Engine if needed.
  12572. if (!Engine.audioEngine && options.audioEngine && Engine.AudioEngineFactory) {
  12573. Engine.audioEngine = Engine.AudioEngineFactory(this.getRenderingCanvas());
  12574. }
  12575. // Prepare buffer pointers
  12576. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  12577. this._currentBufferPointers[i] = new BufferPointer();
  12578. }
  12579. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  12580. // Load WebVR Devices
  12581. if (options.autoEnableWebVR) {
  12582. this.initWebVR();
  12583. }
  12584. // Detect if we are running on a faulty buggy OS.
  12585. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  12586. // Detect if we are running on a faulty buggy desktop OS.
  12587. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  12588. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  12589. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  12590. }
  12591. Object.defineProperty(Engine, "LastCreatedEngine", {
  12592. /**
  12593. * Gets the latest created engine
  12594. */
  12595. get: function () {
  12596. if (Engine.Instances.length === 0) {
  12597. return null;
  12598. }
  12599. return Engine.Instances[Engine.Instances.length - 1];
  12600. },
  12601. enumerable: true,
  12602. configurable: true
  12603. });
  12604. Object.defineProperty(Engine, "LastCreatedScene", {
  12605. /**
  12606. * Gets the latest created scene
  12607. */
  12608. get: function () {
  12609. var lastCreatedEngine = Engine.LastCreatedEngine;
  12610. if (!lastCreatedEngine) {
  12611. return null;
  12612. }
  12613. if (lastCreatedEngine.scenes.length === 0) {
  12614. return null;
  12615. }
  12616. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  12617. },
  12618. enumerable: true,
  12619. configurable: true
  12620. });
  12621. /**
  12622. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  12623. * @param flag defines which part of the materials must be marked as dirty
  12624. * @param predicate defines a predicate used to filter which materials should be affected
  12625. */
  12626. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  12627. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  12628. var engine = Engine.Instances[engineIndex];
  12629. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  12630. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  12631. }
  12632. }
  12633. };
  12634. Object.defineProperty(Engine, "Version", {
  12635. /**
  12636. * Returns the current version of the framework
  12637. */
  12638. get: function () {
  12639. return "3.3.0";
  12640. },
  12641. enumerable: true,
  12642. configurable: true
  12643. });
  12644. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12645. /**
  12646. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12647. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12648. */
  12649. get: function () {
  12650. return this._vrExclusivePointerMode;
  12651. },
  12652. enumerable: true,
  12653. configurable: true
  12654. });
  12655. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12656. /**
  12657. * Gets a boolean indicating that the engine supports uniform buffers
  12658. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12659. */
  12660. get: function () {
  12661. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12662. },
  12663. enumerable: true,
  12664. configurable: true
  12665. });
  12666. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12667. /**
  12668. * Gets a boolean indicating that only power of 2 textures are supported
  12669. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12670. */
  12671. get: function () {
  12672. return this._webGLVersion < 2 || this.forcePOTTextures;
  12673. },
  12674. enumerable: true,
  12675. configurable: true
  12676. });
  12677. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12678. /**
  12679. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12680. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12681. */
  12682. get: function () {
  12683. return this._doNotHandleContextLost;
  12684. },
  12685. set: function (value) {
  12686. this._doNotHandleContextLost = value;
  12687. },
  12688. enumerable: true,
  12689. configurable: true
  12690. });
  12691. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12692. /**
  12693. * Gets the performance monitor attached to this engine
  12694. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12695. */
  12696. get: function () {
  12697. return this._performanceMonitor;
  12698. },
  12699. enumerable: true,
  12700. configurable: true
  12701. });
  12702. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12703. /**
  12704. * Gets the list of texture formats supported
  12705. */
  12706. get: function () {
  12707. return this._texturesSupported;
  12708. },
  12709. enumerable: true,
  12710. configurable: true
  12711. });
  12712. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12713. /**
  12714. * Gets the list of texture formats in use
  12715. */
  12716. get: function () {
  12717. return this._textureFormatInUse;
  12718. },
  12719. enumerable: true,
  12720. configurable: true
  12721. });
  12722. Object.defineProperty(Engine.prototype, "currentViewport", {
  12723. /**
  12724. * Gets the current viewport
  12725. */
  12726. get: function () {
  12727. return this._cachedViewport;
  12728. },
  12729. enumerable: true,
  12730. configurable: true
  12731. });
  12732. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12733. /**
  12734. * Gets the default empty texture
  12735. */
  12736. get: function () {
  12737. if (!this._emptyTexture) {
  12738. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12739. }
  12740. return this._emptyTexture;
  12741. },
  12742. enumerable: true,
  12743. configurable: true
  12744. });
  12745. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12746. /**
  12747. * Gets the default empty 3D texture
  12748. */
  12749. get: function () {
  12750. if (!this._emptyTexture3D) {
  12751. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12752. }
  12753. return this._emptyTexture3D;
  12754. },
  12755. enumerable: true,
  12756. configurable: true
  12757. });
  12758. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12759. /**
  12760. * Gets the default empty cube texture
  12761. */
  12762. get: function () {
  12763. if (!this._emptyCubeTexture) {
  12764. var faceData = new Uint8Array(4);
  12765. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12766. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12767. }
  12768. return this._emptyCubeTexture;
  12769. },
  12770. enumerable: true,
  12771. configurable: true
  12772. });
  12773. Engine.prototype._rebuildInternalTextures = function () {
  12774. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12775. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12776. var internalTexture = currentState_1[_i];
  12777. internalTexture._rebuild();
  12778. }
  12779. };
  12780. Engine.prototype._rebuildEffects = function () {
  12781. for (var key in this._compiledEffects) {
  12782. var effect = this._compiledEffects[key];
  12783. effect._prepareEffect();
  12784. }
  12785. BABYLON.Effect.ResetCache();
  12786. };
  12787. Engine.prototype._rebuildBuffers = function () {
  12788. // Index / Vertex
  12789. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12790. var scene = _a[_i];
  12791. scene.resetCachedMaterial();
  12792. scene._rebuildGeometries();
  12793. scene._rebuildTextures();
  12794. }
  12795. // Uniforms
  12796. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12797. var uniformBuffer = _c[_b];
  12798. uniformBuffer._rebuild();
  12799. }
  12800. };
  12801. Engine.prototype._initGLContext = function () {
  12802. // Caps
  12803. this._caps = new EngineCapabilities();
  12804. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12805. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12806. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12807. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12808. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12809. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12810. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12811. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12812. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12813. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12814. // Infos
  12815. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12816. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12817. if (rendererInfo != null) {
  12818. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12819. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12820. }
  12821. if (!this._glVendor) {
  12822. this._glVendor = "Unknown vendor";
  12823. }
  12824. if (!this._glRenderer) {
  12825. this._glRenderer = "Unknown renderer";
  12826. }
  12827. // Constants
  12828. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12829. if (this._gl.RGBA16F !== 0x881A) {
  12830. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12831. }
  12832. if (this._gl.RGBA32F !== 0x8814) {
  12833. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12834. }
  12835. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12836. this._gl.DEPTH24_STENCIL8 = 35056;
  12837. }
  12838. // Extensions
  12839. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12840. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12841. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12842. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12843. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12844. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12845. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12846. 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');
  12847. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12848. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12849. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12850. this._caps.highPrecisionShaderSupported = true;
  12851. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12852. if (this._caps.timerQuery) {
  12853. if (this._webGLVersion === 1) {
  12854. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12855. }
  12856. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12857. }
  12858. // Checks if some of the format renders first to allow the use of webgl inspector.
  12859. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12860. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12861. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12862. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12863. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12864. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12865. if (this._webGLVersion > 1) {
  12866. this._gl.HALF_FLOAT_OES = 0x140B;
  12867. }
  12868. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12869. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12870. // Draw buffers
  12871. if (this._webGLVersion > 1) {
  12872. this._caps.drawBuffersExtension = true;
  12873. }
  12874. else {
  12875. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12876. if (drawBuffersExtension !== null) {
  12877. this._caps.drawBuffersExtension = true;
  12878. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12879. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12880. for (var i = 0; i < 16; i++) {
  12881. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12882. }
  12883. }
  12884. else {
  12885. this._caps.drawBuffersExtension = false;
  12886. }
  12887. }
  12888. // Depth Texture
  12889. if (this._webGLVersion > 1) {
  12890. this._caps.depthTextureExtension = true;
  12891. }
  12892. else {
  12893. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12894. if (depthTextureExtension != null) {
  12895. this._caps.depthTextureExtension = true;
  12896. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12897. }
  12898. }
  12899. // Vertex array object
  12900. if (this._webGLVersion > 1) {
  12901. this._caps.vertexArrayObject = true;
  12902. }
  12903. else {
  12904. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12905. if (vertexArrayObjectExtension != null) {
  12906. this._caps.vertexArrayObject = true;
  12907. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12908. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12909. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12910. }
  12911. else {
  12912. this._caps.vertexArrayObject = false;
  12913. }
  12914. }
  12915. // Instances count
  12916. if (this._webGLVersion > 1) {
  12917. this._caps.instancedArrays = true;
  12918. }
  12919. else {
  12920. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12921. if (instanceExtension != null) {
  12922. this._caps.instancedArrays = true;
  12923. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12924. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12925. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12926. }
  12927. else {
  12928. this._caps.instancedArrays = false;
  12929. }
  12930. }
  12931. // Intelligently add supported compressed formats in order to check for.
  12932. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12933. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12934. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12935. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12936. if (this._caps.astc) {
  12937. this.texturesSupported.push('-astc.ktx');
  12938. }
  12939. if (this._caps.s3tc) {
  12940. this.texturesSupported.push('-dxt.ktx');
  12941. }
  12942. if (this._caps.pvrtc) {
  12943. this.texturesSupported.push('-pvrtc.ktx');
  12944. }
  12945. if (this._caps.etc2) {
  12946. this.texturesSupported.push('-etc2.ktx');
  12947. }
  12948. if (this._caps.etc1) {
  12949. this.texturesSupported.push('-etc1.ktx');
  12950. }
  12951. if (this._gl.getShaderPrecisionFormat) {
  12952. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12953. if (highp) {
  12954. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12955. }
  12956. }
  12957. // Depth buffer
  12958. this.setDepthBuffer(true);
  12959. this.setDepthFunctionToLessOrEqual();
  12960. this.setDepthWrite(true);
  12961. // Texture maps
  12962. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12963. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12964. this._nextFreeTextureSlots.push(slot);
  12965. }
  12966. };
  12967. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12968. /**
  12969. * Gets version of the current webGL context
  12970. */
  12971. get: function () {
  12972. return this._webGLVersion;
  12973. },
  12974. enumerable: true,
  12975. configurable: true
  12976. });
  12977. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12978. /**
  12979. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12980. */
  12981. get: function () {
  12982. return this._isStencilEnable;
  12983. },
  12984. enumerable: true,
  12985. configurable: true
  12986. });
  12987. Engine.prototype._prepareWorkingCanvas = function () {
  12988. if (this._workingCanvas) {
  12989. return;
  12990. }
  12991. this._workingCanvas = document.createElement("canvas");
  12992. var context = this._workingCanvas.getContext("2d");
  12993. if (context) {
  12994. this._workingContext = context;
  12995. }
  12996. };
  12997. /**
  12998. * Reset the texture cache to empty state
  12999. */
  13000. Engine.prototype.resetTextureCache = function () {
  13001. for (var key in this._boundTexturesCache) {
  13002. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  13003. continue;
  13004. }
  13005. var boundTexture = this._boundTexturesCache[key];
  13006. if (boundTexture) {
  13007. this._removeDesignatedSlot(boundTexture);
  13008. }
  13009. this._boundTexturesCache[key] = null;
  13010. }
  13011. if (!this.disableTextureBindingOptimization) {
  13012. this._nextFreeTextureSlots = [];
  13013. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  13014. this._nextFreeTextureSlots.push(slot);
  13015. }
  13016. }
  13017. this._currentTextureChannel = -1;
  13018. };
  13019. /**
  13020. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  13021. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  13022. * @returns true if engine is in deterministic lock step mode
  13023. */
  13024. Engine.prototype.isDeterministicLockStep = function () {
  13025. return this._deterministicLockstep;
  13026. };
  13027. /**
  13028. * Gets the max steps when engine is running in deterministic lock step
  13029. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  13030. * @returns the max steps
  13031. */
  13032. Engine.prototype.getLockstepMaxSteps = function () {
  13033. return this._lockstepMaxSteps;
  13034. };
  13035. /**
  13036. * Gets an object containing information about the current webGL context
  13037. * @returns an object containing the vender, the renderer and the version of the current webGL context
  13038. */
  13039. Engine.prototype.getGlInfo = function () {
  13040. return {
  13041. vendor: this._glVendor,
  13042. renderer: this._glRenderer,
  13043. version: this._glVersion
  13044. };
  13045. };
  13046. /**
  13047. * Gets current aspect ratio
  13048. * @param camera defines the camera to use to get the aspect ratio
  13049. * @param useScreen defines if screen size must be used (or the current render target if any)
  13050. * @returns a number defining the aspect ratio
  13051. */
  13052. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  13053. if (useScreen === void 0) { useScreen = false; }
  13054. var viewport = camera.viewport;
  13055. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  13056. };
  13057. /**
  13058. * Gets current screen aspect ratio
  13059. * @returns a number defining the aspect ratio
  13060. */
  13061. Engine.prototype.getScreenAspectRatio = function () {
  13062. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  13063. };
  13064. /**
  13065. * Gets the current render width
  13066. * @param useScreen defines if screen size must be used (or the current render target if any)
  13067. * @returns a number defining the current render width
  13068. */
  13069. Engine.prototype.getRenderWidth = function (useScreen) {
  13070. if (useScreen === void 0) { useScreen = false; }
  13071. if (!useScreen && this._currentRenderTarget) {
  13072. return this._currentRenderTarget.width;
  13073. }
  13074. return this._gl.drawingBufferWidth;
  13075. };
  13076. /**
  13077. * Gets the current render height
  13078. * @param useScreen defines if screen size must be used (or the current render target if any)
  13079. * @returns a number defining the current render height
  13080. */
  13081. Engine.prototype.getRenderHeight = function (useScreen) {
  13082. if (useScreen === void 0) { useScreen = false; }
  13083. if (!useScreen && this._currentRenderTarget) {
  13084. return this._currentRenderTarget.height;
  13085. }
  13086. return this._gl.drawingBufferHeight;
  13087. };
  13088. /**
  13089. * Gets the HTML canvas attached with the current webGL context
  13090. * @returns a HTML canvas
  13091. */
  13092. Engine.prototype.getRenderingCanvas = function () {
  13093. return this._renderingCanvas;
  13094. };
  13095. /**
  13096. * Gets the client rect of the HTML canvas attached with the current webGL context
  13097. * @returns a client rectanglee
  13098. */
  13099. Engine.prototype.getRenderingCanvasClientRect = function () {
  13100. if (!this._renderingCanvas) {
  13101. return null;
  13102. }
  13103. return this._renderingCanvas.getBoundingClientRect();
  13104. };
  13105. /**
  13106. * Defines the hardware scaling level.
  13107. * By default the hardware scaling level is computed from the window device ratio.
  13108. * 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.
  13109. * @param level defines the level to use
  13110. */
  13111. Engine.prototype.setHardwareScalingLevel = function (level) {
  13112. this._hardwareScalingLevel = level;
  13113. this.resize();
  13114. };
  13115. /**
  13116. * Gets the current hardware scaling level.
  13117. * By default the hardware scaling level is computed from the window device ratio.
  13118. * 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.
  13119. * @returns a number indicating the current hardware scaling level
  13120. */
  13121. Engine.prototype.getHardwareScalingLevel = function () {
  13122. return this._hardwareScalingLevel;
  13123. };
  13124. /**
  13125. * Gets the list of loaded textures
  13126. * @returns an array containing all loaded textures
  13127. */
  13128. Engine.prototype.getLoadedTexturesCache = function () {
  13129. return this._internalTexturesCache;
  13130. };
  13131. /**
  13132. * Gets the object containing all engine capabilities
  13133. * @returns the EngineCapabilities object
  13134. */
  13135. Engine.prototype.getCaps = function () {
  13136. return this._caps;
  13137. };
  13138. Object.defineProperty(Engine.prototype, "drawCalls", {
  13139. /** @hidden */
  13140. get: function () {
  13141. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  13142. return 0;
  13143. },
  13144. enumerable: true,
  13145. configurable: true
  13146. });
  13147. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  13148. /** @hidden */
  13149. get: function () {
  13150. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  13151. return null;
  13152. },
  13153. enumerable: true,
  13154. configurable: true
  13155. });
  13156. /**
  13157. * Gets the current depth function
  13158. * @returns a number defining the depth function
  13159. */
  13160. Engine.prototype.getDepthFunction = function () {
  13161. return this._depthCullingState.depthFunc;
  13162. };
  13163. /**
  13164. * Sets the current depth function
  13165. * @param depthFunc defines the function to use
  13166. */
  13167. Engine.prototype.setDepthFunction = function (depthFunc) {
  13168. this._depthCullingState.depthFunc = depthFunc;
  13169. };
  13170. /**
  13171. * Sets the current depth function to GREATER
  13172. */
  13173. Engine.prototype.setDepthFunctionToGreater = function () {
  13174. this._depthCullingState.depthFunc = this._gl.GREATER;
  13175. };
  13176. /**
  13177. * Sets the current depth function to GEQUAL
  13178. */
  13179. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  13180. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  13181. };
  13182. /**
  13183. * Sets the current depth function to LESS
  13184. */
  13185. Engine.prototype.setDepthFunctionToLess = function () {
  13186. this._depthCullingState.depthFunc = this._gl.LESS;
  13187. };
  13188. /**
  13189. * Sets the current depth function to LEQUAL
  13190. */
  13191. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  13192. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  13193. };
  13194. /**
  13195. * Gets a boolean indicating if stencil buffer is enabled
  13196. * @returns the current stencil buffer state
  13197. */
  13198. Engine.prototype.getStencilBuffer = function () {
  13199. return this._stencilState.stencilTest;
  13200. };
  13201. /**
  13202. * Enable or disable the stencil buffer
  13203. * @param enable defines if the stencil buffer must be enabled or disabled
  13204. */
  13205. Engine.prototype.setStencilBuffer = function (enable) {
  13206. this._stencilState.stencilTest = enable;
  13207. };
  13208. /**
  13209. * Gets the current stencil mask
  13210. * @returns a number defining the new stencil mask to use
  13211. */
  13212. Engine.prototype.getStencilMask = function () {
  13213. return this._stencilState.stencilMask;
  13214. };
  13215. /**
  13216. * Sets the current stencil mask
  13217. * @param mask defines the new stencil mask to use
  13218. */
  13219. Engine.prototype.setStencilMask = function (mask) {
  13220. this._stencilState.stencilMask = mask;
  13221. };
  13222. /**
  13223. * Gets the current stencil function
  13224. * @returns a number defining the stencil function to use
  13225. */
  13226. Engine.prototype.getStencilFunction = function () {
  13227. return this._stencilState.stencilFunc;
  13228. };
  13229. /**
  13230. * Gets the current stencil reference value
  13231. * @returns a number defining the stencil reference value to use
  13232. */
  13233. Engine.prototype.getStencilFunctionReference = function () {
  13234. return this._stencilState.stencilFuncRef;
  13235. };
  13236. /**
  13237. * Gets the current stencil mask
  13238. * @returns a number defining the stencil mask to use
  13239. */
  13240. Engine.prototype.getStencilFunctionMask = function () {
  13241. return this._stencilState.stencilFuncMask;
  13242. };
  13243. /**
  13244. * Sets the current stencil function
  13245. * @param stencilFunc defines the new stencil function to use
  13246. */
  13247. Engine.prototype.setStencilFunction = function (stencilFunc) {
  13248. this._stencilState.stencilFunc = stencilFunc;
  13249. };
  13250. /**
  13251. * Sets the current stencil reference
  13252. * @param reference defines the new stencil reference to use
  13253. */
  13254. Engine.prototype.setStencilFunctionReference = function (reference) {
  13255. this._stencilState.stencilFuncRef = reference;
  13256. };
  13257. /**
  13258. * Sets the current stencil mask
  13259. * @param mask defines the new stencil mask to use
  13260. */
  13261. Engine.prototype.setStencilFunctionMask = function (mask) {
  13262. this._stencilState.stencilFuncMask = mask;
  13263. };
  13264. /**
  13265. * Gets the current stencil operation when stencil fails
  13266. * @returns a number defining stencil operation to use when stencil fails
  13267. */
  13268. Engine.prototype.getStencilOperationFail = function () {
  13269. return this._stencilState.stencilOpStencilFail;
  13270. };
  13271. /**
  13272. * Gets the current stencil operation when depth fails
  13273. * @returns a number defining stencil operation to use when depth fails
  13274. */
  13275. Engine.prototype.getStencilOperationDepthFail = function () {
  13276. return this._stencilState.stencilOpDepthFail;
  13277. };
  13278. /**
  13279. * Gets the current stencil operation when stencil passes
  13280. * @returns a number defining stencil operation to use when stencil passes
  13281. */
  13282. Engine.prototype.getStencilOperationPass = function () {
  13283. return this._stencilState.stencilOpStencilDepthPass;
  13284. };
  13285. /**
  13286. * Sets the stencil operation to use when stencil fails
  13287. * @param operation defines the stencil operation to use when stencil fails
  13288. */
  13289. Engine.prototype.setStencilOperationFail = function (operation) {
  13290. this._stencilState.stencilOpStencilFail = operation;
  13291. };
  13292. /**
  13293. * Sets the stencil operation to use when depth fails
  13294. * @param operation defines the stencil operation to use when depth fails
  13295. */
  13296. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  13297. this._stencilState.stencilOpDepthFail = operation;
  13298. };
  13299. /**
  13300. * Sets the stencil operation to use when stencil passes
  13301. * @param operation defines the stencil operation to use when stencil passes
  13302. */
  13303. Engine.prototype.setStencilOperationPass = function (operation) {
  13304. this._stencilState.stencilOpStencilDepthPass = operation;
  13305. };
  13306. /**
  13307. * Sets a boolean indicating if the dithering state is enabled or disabled
  13308. * @param value defines the dithering state
  13309. */
  13310. Engine.prototype.setDitheringState = function (value) {
  13311. if (value) {
  13312. this._gl.enable(this._gl.DITHER);
  13313. }
  13314. else {
  13315. this._gl.disable(this._gl.DITHER);
  13316. }
  13317. };
  13318. /**
  13319. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  13320. * @param value defines the rasterizer state
  13321. */
  13322. Engine.prototype.setRasterizerState = function (value) {
  13323. if (value) {
  13324. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  13325. }
  13326. else {
  13327. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  13328. }
  13329. };
  13330. /**
  13331. * stop executing a render loop function and remove it from the execution array
  13332. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  13333. */
  13334. Engine.prototype.stopRenderLoop = function (renderFunction) {
  13335. if (!renderFunction) {
  13336. this._activeRenderLoops = [];
  13337. return;
  13338. }
  13339. var index = this._activeRenderLoops.indexOf(renderFunction);
  13340. if (index >= 0) {
  13341. this._activeRenderLoops.splice(index, 1);
  13342. }
  13343. };
  13344. /** @hidden */
  13345. Engine.prototype._renderLoop = function () {
  13346. if (!this._contextWasLost) {
  13347. var shouldRender = true;
  13348. if (!this.renderEvenInBackground && this._windowIsBackground) {
  13349. shouldRender = false;
  13350. }
  13351. if (shouldRender) {
  13352. // Start new frame
  13353. this.beginFrame();
  13354. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  13355. var renderFunction = this._activeRenderLoops[index];
  13356. renderFunction();
  13357. }
  13358. // Present
  13359. this.endFrame();
  13360. }
  13361. }
  13362. if (this._activeRenderLoops.length > 0) {
  13363. // Register new frame
  13364. var requester = null;
  13365. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13366. requester = this._vrDisplay;
  13367. }
  13368. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  13369. }
  13370. else {
  13371. this._renderingQueueLaunched = false;
  13372. }
  13373. };
  13374. /**
  13375. * Register and execute a render loop. The engine can have more than one render function
  13376. * @param renderFunction defines the function to continuously execute
  13377. */
  13378. Engine.prototype.runRenderLoop = function (renderFunction) {
  13379. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  13380. return;
  13381. }
  13382. this._activeRenderLoops.push(renderFunction);
  13383. if (!this._renderingQueueLaunched) {
  13384. this._renderingQueueLaunched = true;
  13385. this._bindedRenderFunction = this._renderLoop.bind(this);
  13386. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  13387. }
  13388. };
  13389. /**
  13390. * Toggle full screen mode
  13391. * @param requestPointerLock defines if a pointer lock should be requested from the user
  13392. */
  13393. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  13394. if (this.isFullscreen) {
  13395. BABYLON.Tools.ExitFullscreen();
  13396. }
  13397. else {
  13398. this._pointerLockRequested = requestPointerLock;
  13399. if (this._renderingCanvas) {
  13400. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  13401. }
  13402. }
  13403. };
  13404. /**
  13405. * Clear the current render buffer or the current render target (if any is set up)
  13406. * @param color defines the color to use
  13407. * @param backBuffer defines if the back buffer must be cleared
  13408. * @param depth defines if the depth buffer must be cleared
  13409. * @param stencil defines if the stencil buffer must be cleared
  13410. */
  13411. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  13412. if (stencil === void 0) { stencil = false; }
  13413. this.applyStates();
  13414. var mode = 0;
  13415. if (backBuffer && color) {
  13416. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  13417. mode |= this._gl.COLOR_BUFFER_BIT;
  13418. }
  13419. if (depth) {
  13420. this._gl.clearDepth(1.0);
  13421. mode |= this._gl.DEPTH_BUFFER_BIT;
  13422. }
  13423. if (stencil) {
  13424. this._gl.clearStencil(0);
  13425. mode |= this._gl.STENCIL_BUFFER_BIT;
  13426. }
  13427. this._gl.clear(mode);
  13428. };
  13429. /**
  13430. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  13431. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  13432. * @param y defines the y-coordinate of the corner of the clear rectangle
  13433. * @param width defines the width of the clear rectangle
  13434. * @param height defines the height of the clear rectangle
  13435. * @param clearColor defines the clear color
  13436. */
  13437. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  13438. var gl = this._gl;
  13439. // Save state
  13440. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  13441. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  13442. // Change state
  13443. gl.enable(gl.SCISSOR_TEST);
  13444. gl.scissor(x, y, width, height);
  13445. // Clear
  13446. this.clear(clearColor, true, true, true);
  13447. // Restore state
  13448. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  13449. if (curScissor === true) {
  13450. gl.enable(gl.SCISSOR_TEST);
  13451. }
  13452. else {
  13453. gl.disable(gl.SCISSOR_TEST);
  13454. }
  13455. };
  13456. /** @hidden */
  13457. Engine.prototype._viewport = function (x, y, width, height) {
  13458. if (x !== this._viewportCached.x ||
  13459. y !== this._viewportCached.y ||
  13460. width !== this._viewportCached.z ||
  13461. height !== this._viewportCached.w) {
  13462. this._viewportCached.x = x;
  13463. this._viewportCached.y = y;
  13464. this._viewportCached.z = width;
  13465. this._viewportCached.w = height;
  13466. this._gl.viewport(x, y, width, height);
  13467. }
  13468. };
  13469. /**
  13470. * Set the WebGL's viewport
  13471. * @param viewport defines the viewport element to be used
  13472. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  13473. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  13474. */
  13475. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  13476. var width = requiredWidth || this.getRenderWidth();
  13477. var height = requiredHeight || this.getRenderHeight();
  13478. var x = viewport.x || 0;
  13479. var y = viewport.y || 0;
  13480. this._cachedViewport = viewport;
  13481. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  13482. };
  13483. /**
  13484. * Directly set the WebGL Viewport
  13485. * @param x defines the x coordinate of the viewport (in screen space)
  13486. * @param y defines the y coordinate of the viewport (in screen space)
  13487. * @param width defines the width of the viewport (in screen space)
  13488. * @param height defines the height of the viewport (in screen space)
  13489. * @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
  13490. */
  13491. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  13492. var currentViewport = this._cachedViewport;
  13493. this._cachedViewport = null;
  13494. this._viewport(x, y, width, height);
  13495. return currentViewport;
  13496. };
  13497. /**
  13498. * Begin a new frame
  13499. */
  13500. Engine.prototype.beginFrame = function () {
  13501. this.onBeginFrameObservable.notifyObservers(this);
  13502. this._measureFps();
  13503. };
  13504. /**
  13505. * Enf the current frame
  13506. */
  13507. Engine.prototype.endFrame = function () {
  13508. // Force a flush in case we are using a bad OS.
  13509. if (this._badOS) {
  13510. this.flushFramebuffer();
  13511. }
  13512. // Submit frame to the vr device, if enabled
  13513. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13514. // TODO: We should only submit the frame if we read frameData successfully.
  13515. this._vrDisplay.submitFrame();
  13516. }
  13517. this.onEndFrameObservable.notifyObservers(this);
  13518. };
  13519. /**
  13520. * Resize the view according to the canvas' size
  13521. */
  13522. Engine.prototype.resize = function () {
  13523. // We're not resizing the size of the canvas while in VR mode & presenting
  13524. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  13525. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  13526. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  13527. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  13528. }
  13529. };
  13530. /**
  13531. * Force a specific size of the canvas
  13532. * @param width defines the new canvas' width
  13533. * @param height defines the new canvas' height
  13534. */
  13535. Engine.prototype.setSize = function (width, height) {
  13536. if (!this._renderingCanvas) {
  13537. return;
  13538. }
  13539. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  13540. return;
  13541. }
  13542. this._renderingCanvas.width = width;
  13543. this._renderingCanvas.height = height;
  13544. for (var index = 0; index < this.scenes.length; index++) {
  13545. var scene = this.scenes[index];
  13546. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  13547. var cam = scene.cameras[camIndex];
  13548. cam._currentRenderId = 0;
  13549. }
  13550. }
  13551. if (this.onResizeObservable.hasObservers) {
  13552. this.onResizeObservable.notifyObservers(this);
  13553. }
  13554. };
  13555. // WebVR functions
  13556. /**
  13557. * Gets a boolean indicating if a webVR device was detected
  13558. * @returns true if a webVR device was detected
  13559. */
  13560. Engine.prototype.isVRDevicePresent = function () {
  13561. return !!this._vrDisplay;
  13562. };
  13563. /**
  13564. * Gets the current webVR device
  13565. * @returns the current webVR device (or null)
  13566. */
  13567. Engine.prototype.getVRDevice = function () {
  13568. return this._vrDisplay;
  13569. };
  13570. /**
  13571. * Initializes a webVR display and starts listening to display change events
  13572. * The onVRDisplayChangedObservable will be notified upon these changes
  13573. * @returns The onVRDisplayChangedObservable
  13574. */
  13575. Engine.prototype.initWebVR = function () {
  13576. this.initWebVRAsync();
  13577. return this.onVRDisplayChangedObservable;
  13578. };
  13579. /**
  13580. * Initializes a webVR display and starts listening to display change events
  13581. * The onVRDisplayChangedObservable will be notified upon these changes
  13582. * @returns A promise containing a VRDisplay and if vr is supported
  13583. */
  13584. Engine.prototype.initWebVRAsync = function () {
  13585. var _this = this;
  13586. var notifyObservers = function () {
  13587. var eventArgs = {
  13588. vrDisplay: _this._vrDisplay,
  13589. vrSupported: _this._vrSupported
  13590. };
  13591. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  13592. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  13593. };
  13594. if (!this._onVrDisplayConnect) {
  13595. this._onVrDisplayConnect = function (event) {
  13596. _this._vrDisplay = event.display;
  13597. notifyObservers();
  13598. };
  13599. this._onVrDisplayDisconnect = function () {
  13600. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  13601. _this._vrDisplay = undefined;
  13602. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  13603. notifyObservers();
  13604. };
  13605. this._onVrDisplayPresentChange = function () {
  13606. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  13607. };
  13608. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13609. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13610. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13611. }
  13612. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  13613. this._webVRInitPromise.then(notifyObservers);
  13614. return this._webVRInitPromise;
  13615. };
  13616. /**
  13617. * Call this function to switch to webVR mode
  13618. * Will do nothing if webVR is not supported or if there is no webVR device
  13619. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13620. */
  13621. Engine.prototype.enableVR = function () {
  13622. var _this = this;
  13623. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13624. var onResolved = function () {
  13625. _this.onVRRequestPresentComplete.notifyObservers(true);
  13626. _this._onVRFullScreenTriggered();
  13627. };
  13628. var onRejected = function () {
  13629. _this.onVRRequestPresentComplete.notifyObservers(false);
  13630. };
  13631. this.onVRRequestPresentStart.notifyObservers(this);
  13632. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13633. }
  13634. };
  13635. /**
  13636. * Call this function to leave webVR mode
  13637. * Will do nothing if webVR is not supported or if there is no webVR device
  13638. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13639. */
  13640. Engine.prototype.disableVR = function () {
  13641. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13642. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13643. }
  13644. };
  13645. Engine.prototype._getVRDisplaysAsync = function () {
  13646. var _this = this;
  13647. return new Promise(function (res, rej) {
  13648. if (navigator.getVRDisplays) {
  13649. navigator.getVRDisplays().then(function (devices) {
  13650. _this._vrSupported = true;
  13651. // note that devices may actually be an empty array. This is fine;
  13652. // we expect this._vrDisplay to be undefined in this case.
  13653. _this._vrDisplay = devices[0];
  13654. res({
  13655. vrDisplay: _this._vrDisplay,
  13656. vrSupported: _this._vrSupported
  13657. });
  13658. });
  13659. }
  13660. else {
  13661. _this._vrDisplay = undefined;
  13662. _this._vrSupported = false;
  13663. res({
  13664. vrDisplay: _this._vrDisplay,
  13665. vrSupported: _this._vrSupported
  13666. });
  13667. }
  13668. });
  13669. };
  13670. /**
  13671. * Binds the frame buffer to the specified texture.
  13672. * @param texture The texture to render to or null for the default canvas
  13673. * @param faceIndex The face of the texture to render to in case of cube texture
  13674. * @param requiredWidth The width of the target to render to
  13675. * @param requiredHeight The height of the target to render to
  13676. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13677. * @param depthStencilTexture The depth stencil texture to use to render
  13678. * @param lodLevel defines le lod level to bind to the frame buffer
  13679. */
  13680. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  13681. if (lodLevel === void 0) { lodLevel = 0; }
  13682. if (this._currentRenderTarget) {
  13683. this.unBindFramebuffer(this._currentRenderTarget);
  13684. }
  13685. this._currentRenderTarget = texture;
  13686. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13687. var gl = this._gl;
  13688. if (texture.isCube) {
  13689. if (faceIndex === undefined) {
  13690. faceIndex = 0;
  13691. }
  13692. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  13693. if (depthStencilTexture) {
  13694. if (depthStencilTexture._generateStencilBuffer) {
  13695. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13696. }
  13697. else {
  13698. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13699. }
  13700. }
  13701. }
  13702. if (this._cachedViewport && !forceFullscreenViewport) {
  13703. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13704. }
  13705. else {
  13706. if (!requiredWidth) {
  13707. requiredWidth = texture.width;
  13708. if (lodLevel) {
  13709. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  13710. }
  13711. }
  13712. if (!requiredHeight) {
  13713. requiredHeight = texture.height;
  13714. if (lodLevel) {
  13715. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  13716. }
  13717. }
  13718. this._viewport(0, 0, requiredWidth, requiredHeight);
  13719. }
  13720. this.wipeCaches();
  13721. };
  13722. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13723. if (this._currentFramebuffer !== framebuffer) {
  13724. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13725. this._currentFramebuffer = framebuffer;
  13726. }
  13727. };
  13728. /**
  13729. * Unbind the current render target texture from the webGL context
  13730. * @param texture defines the render target texture to unbind
  13731. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13732. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13733. */
  13734. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13735. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13736. this._currentRenderTarget = null;
  13737. // If MSAA, we need to bitblt back to main texture
  13738. var gl = this._gl;
  13739. if (texture._MSAAFramebuffer) {
  13740. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13741. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13742. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13743. }
  13744. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13745. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13746. gl.generateMipmap(gl.TEXTURE_2D);
  13747. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13748. }
  13749. if (onBeforeUnbind) {
  13750. if (texture._MSAAFramebuffer) {
  13751. // Bind the correct framebuffer
  13752. this.bindUnboundFramebuffer(texture._framebuffer);
  13753. }
  13754. onBeforeUnbind();
  13755. }
  13756. this.bindUnboundFramebuffer(null);
  13757. };
  13758. /**
  13759. * Unbind a list of render target textures from the webGL context
  13760. * This is used only when drawBuffer extension or webGL2 are active
  13761. * @param textures defines the render target textures to unbind
  13762. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13763. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13764. */
  13765. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13766. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13767. this._currentRenderTarget = null;
  13768. // If MSAA, we need to bitblt back to main texture
  13769. var gl = this._gl;
  13770. if (textures[0]._MSAAFramebuffer) {
  13771. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13772. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13773. var attachments = textures[0]._attachments;
  13774. if (!attachments) {
  13775. attachments = new Array(textures.length);
  13776. textures[0]._attachments = attachments;
  13777. }
  13778. for (var i = 0; i < textures.length; i++) {
  13779. var texture = textures[i];
  13780. for (var j = 0; j < attachments.length; j++) {
  13781. attachments[j] = gl.NONE;
  13782. }
  13783. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13784. gl.readBuffer(attachments[i]);
  13785. gl.drawBuffers(attachments);
  13786. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13787. }
  13788. for (var i = 0; i < attachments.length; i++) {
  13789. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13790. }
  13791. gl.drawBuffers(attachments);
  13792. }
  13793. for (var i = 0; i < textures.length; i++) {
  13794. var texture = textures[i];
  13795. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13796. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13797. gl.generateMipmap(gl.TEXTURE_2D);
  13798. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13799. }
  13800. }
  13801. if (onBeforeUnbind) {
  13802. if (textures[0]._MSAAFramebuffer) {
  13803. // Bind the correct framebuffer
  13804. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13805. }
  13806. onBeforeUnbind();
  13807. }
  13808. this.bindUnboundFramebuffer(null);
  13809. };
  13810. /**
  13811. * Force the mipmap generation for the given render target texture
  13812. * @param texture defines the render target texture to use
  13813. */
  13814. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13815. if (texture.generateMipMaps) {
  13816. var gl = this._gl;
  13817. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13818. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13819. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13820. }
  13821. };
  13822. /**
  13823. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13824. */
  13825. Engine.prototype.flushFramebuffer = function () {
  13826. this._gl.flush();
  13827. };
  13828. /**
  13829. * Unbind the current render target and bind the default framebuffer
  13830. */
  13831. Engine.prototype.restoreDefaultFramebuffer = function () {
  13832. if (this._currentRenderTarget) {
  13833. this.unBindFramebuffer(this._currentRenderTarget);
  13834. }
  13835. else {
  13836. this.bindUnboundFramebuffer(null);
  13837. }
  13838. if (this._cachedViewport) {
  13839. this.setViewport(this._cachedViewport);
  13840. }
  13841. this.wipeCaches();
  13842. };
  13843. // UBOs
  13844. /**
  13845. * Create an uniform buffer
  13846. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13847. * @param elements defines the content of the uniform buffer
  13848. * @returns the webGL uniform buffer
  13849. */
  13850. Engine.prototype.createUniformBuffer = function (elements) {
  13851. var ubo = this._gl.createBuffer();
  13852. if (!ubo) {
  13853. throw new Error("Unable to create uniform buffer");
  13854. }
  13855. this.bindUniformBuffer(ubo);
  13856. if (elements instanceof Float32Array) {
  13857. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13858. }
  13859. else {
  13860. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13861. }
  13862. this.bindUniformBuffer(null);
  13863. ubo.references = 1;
  13864. return ubo;
  13865. };
  13866. /**
  13867. * Create a dynamic uniform buffer
  13868. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13869. * @param elements defines the content of the uniform buffer
  13870. * @returns the webGL uniform buffer
  13871. */
  13872. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13873. var ubo = this._gl.createBuffer();
  13874. if (!ubo) {
  13875. throw new Error("Unable to create dynamic uniform buffer");
  13876. }
  13877. this.bindUniformBuffer(ubo);
  13878. if (elements instanceof Float32Array) {
  13879. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13880. }
  13881. else {
  13882. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13883. }
  13884. this.bindUniformBuffer(null);
  13885. ubo.references = 1;
  13886. return ubo;
  13887. };
  13888. /**
  13889. * Update an existing uniform buffer
  13890. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13891. * @param uniformBuffer defines the target uniform buffer
  13892. * @param elements defines the content to update
  13893. * @param offset defines the offset in the uniform buffer where update should start
  13894. * @param count defines the size of the data to update
  13895. */
  13896. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13897. this.bindUniformBuffer(uniformBuffer);
  13898. if (offset === undefined) {
  13899. offset = 0;
  13900. }
  13901. if (count === undefined) {
  13902. if (elements instanceof Float32Array) {
  13903. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13904. }
  13905. else {
  13906. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13907. }
  13908. }
  13909. else {
  13910. if (elements instanceof Float32Array) {
  13911. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13912. }
  13913. else {
  13914. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13915. }
  13916. }
  13917. this.bindUniformBuffer(null);
  13918. };
  13919. // VBOs
  13920. Engine.prototype._resetVertexBufferBinding = function () {
  13921. this.bindArrayBuffer(null);
  13922. this._cachedVertexBuffers = null;
  13923. };
  13924. /**
  13925. * Creates a vertex buffer
  13926. * @param data the data for the vertex buffer
  13927. * @returns the new WebGL static buffer
  13928. */
  13929. Engine.prototype.createVertexBuffer = function (data) {
  13930. var vbo = this._gl.createBuffer();
  13931. if (!vbo) {
  13932. throw new Error("Unable to create vertex buffer");
  13933. }
  13934. this.bindArrayBuffer(vbo);
  13935. if (data instanceof Array) {
  13936. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13937. }
  13938. else {
  13939. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13940. }
  13941. this._resetVertexBufferBinding();
  13942. vbo.references = 1;
  13943. return vbo;
  13944. };
  13945. /**
  13946. * Creates a dynamic vertex buffer
  13947. * @param data the data for the dynamic vertex buffer
  13948. * @returns the new WebGL dynamic buffer
  13949. */
  13950. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13951. var vbo = this._gl.createBuffer();
  13952. if (!vbo) {
  13953. throw new Error("Unable to create dynamic vertex buffer");
  13954. }
  13955. this.bindArrayBuffer(vbo);
  13956. if (data instanceof Array) {
  13957. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13958. }
  13959. else {
  13960. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13961. }
  13962. this._resetVertexBufferBinding();
  13963. vbo.references = 1;
  13964. return vbo;
  13965. };
  13966. /**
  13967. * Update a dynamic index buffer
  13968. * @param indexBuffer defines the target index buffer
  13969. * @param indices defines the data to update
  13970. * @param offset defines the offset in the target index buffer where update should start
  13971. */
  13972. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13973. if (offset === void 0) { offset = 0; }
  13974. // Force cache update
  13975. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13976. this.bindIndexBuffer(indexBuffer);
  13977. var arrayBuffer;
  13978. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13979. arrayBuffer = indices;
  13980. }
  13981. else {
  13982. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13983. }
  13984. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13985. this._resetIndexBufferBinding();
  13986. };
  13987. /**
  13988. * Updates a dynamic vertex buffer.
  13989. * @param vertexBuffer the vertex buffer to update
  13990. * @param data the data used to update the vertex buffer
  13991. * @param byteOffset the byte offset of the data
  13992. * @param byteLength the byte length of the data
  13993. */
  13994. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13995. this.bindArrayBuffer(vertexBuffer);
  13996. if (byteOffset === undefined) {
  13997. byteOffset = 0;
  13998. }
  13999. if (byteLength === undefined) {
  14000. if (data instanceof Array) {
  14001. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  14002. }
  14003. else {
  14004. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  14005. }
  14006. }
  14007. else {
  14008. if (data instanceof Array) {
  14009. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  14010. }
  14011. else {
  14012. if (data instanceof ArrayBuffer) {
  14013. data = new Uint8Array(data, byteOffset, byteLength);
  14014. }
  14015. else {
  14016. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  14017. }
  14018. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  14019. }
  14020. }
  14021. this._resetVertexBufferBinding();
  14022. };
  14023. Engine.prototype._resetIndexBufferBinding = function () {
  14024. this.bindIndexBuffer(null);
  14025. this._cachedIndexBuffer = null;
  14026. };
  14027. /**
  14028. * Creates a new index buffer
  14029. * @param indices defines the content of the index buffer
  14030. * @param updatable defines if the index buffer must be updatable
  14031. * @returns a new webGL buffer
  14032. */
  14033. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  14034. var vbo = this._gl.createBuffer();
  14035. if (!vbo) {
  14036. throw new Error("Unable to create index buffer");
  14037. }
  14038. this.bindIndexBuffer(vbo);
  14039. // Check for 32 bits indices
  14040. var arrayBuffer;
  14041. var need32Bits = false;
  14042. if (indices instanceof Uint16Array) {
  14043. arrayBuffer = indices;
  14044. }
  14045. else {
  14046. //check 32 bit support
  14047. if (this._caps.uintIndices) {
  14048. if (indices instanceof Uint32Array) {
  14049. arrayBuffer = indices;
  14050. need32Bits = true;
  14051. }
  14052. else {
  14053. //number[] or Int32Array, check if 32 bit is necessary
  14054. for (var index = 0; index < indices.length; index++) {
  14055. if (indices[index] > 65535) {
  14056. need32Bits = true;
  14057. break;
  14058. }
  14059. }
  14060. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  14061. }
  14062. }
  14063. else {
  14064. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  14065. arrayBuffer = new Uint16Array(indices);
  14066. }
  14067. }
  14068. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  14069. this._resetIndexBufferBinding();
  14070. vbo.references = 1;
  14071. vbo.is32Bits = need32Bits;
  14072. return vbo;
  14073. };
  14074. /**
  14075. * Bind a webGL buffer to the webGL context
  14076. * @param buffer defines the buffer to bind
  14077. */
  14078. Engine.prototype.bindArrayBuffer = function (buffer) {
  14079. if (!this._vaoRecordInProgress) {
  14080. this._unbindVertexArrayObject();
  14081. }
  14082. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  14083. };
  14084. /**
  14085. * Bind an uniform buffer to the current webGL context
  14086. * @param buffer defines the buffer to bind
  14087. */
  14088. Engine.prototype.bindUniformBuffer = function (buffer) {
  14089. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  14090. };
  14091. /**
  14092. * Bind a buffer to the current webGL context at a given location
  14093. * @param buffer defines the buffer to bind
  14094. * @param location defines the index where to bind the buffer
  14095. */
  14096. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  14097. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  14098. };
  14099. /**
  14100. * Bind a specific block at a given index in a specific shader program
  14101. * @param shaderProgram defines the shader program
  14102. * @param blockName defines the block name
  14103. * @param index defines the index where to bind the block
  14104. */
  14105. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  14106. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  14107. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  14108. };
  14109. Engine.prototype.bindIndexBuffer = function (buffer) {
  14110. if (!this._vaoRecordInProgress) {
  14111. this._unbindVertexArrayObject();
  14112. }
  14113. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  14114. };
  14115. Engine.prototype.bindBuffer = function (buffer, target) {
  14116. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  14117. this._gl.bindBuffer(target, buffer);
  14118. this._currentBoundBuffer[target] = buffer;
  14119. }
  14120. };
  14121. /**
  14122. * update the bound buffer with the given data
  14123. * @param data defines the data to update
  14124. */
  14125. Engine.prototype.updateArrayBuffer = function (data) {
  14126. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  14127. };
  14128. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  14129. var pointer = this._currentBufferPointers[indx];
  14130. var changed = false;
  14131. if (!pointer.active) {
  14132. changed = true;
  14133. pointer.active = true;
  14134. pointer.index = indx;
  14135. pointer.size = size;
  14136. pointer.type = type;
  14137. pointer.normalized = normalized;
  14138. pointer.stride = stride;
  14139. pointer.offset = offset;
  14140. pointer.buffer = buffer;
  14141. }
  14142. else {
  14143. if (pointer.buffer !== buffer) {
  14144. pointer.buffer = buffer;
  14145. changed = true;
  14146. }
  14147. if (pointer.size !== size) {
  14148. pointer.size = size;
  14149. changed = true;
  14150. }
  14151. if (pointer.type !== type) {
  14152. pointer.type = type;
  14153. changed = true;
  14154. }
  14155. if (pointer.normalized !== normalized) {
  14156. pointer.normalized = normalized;
  14157. changed = true;
  14158. }
  14159. if (pointer.stride !== stride) {
  14160. pointer.stride = stride;
  14161. changed = true;
  14162. }
  14163. if (pointer.offset !== offset) {
  14164. pointer.offset = offset;
  14165. changed = true;
  14166. }
  14167. }
  14168. if (changed || this._vaoRecordInProgress) {
  14169. this.bindArrayBuffer(buffer);
  14170. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  14171. }
  14172. };
  14173. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  14174. if (indexBuffer == null) {
  14175. return;
  14176. }
  14177. if (this._cachedIndexBuffer !== indexBuffer) {
  14178. this._cachedIndexBuffer = indexBuffer;
  14179. this.bindIndexBuffer(indexBuffer);
  14180. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  14181. }
  14182. };
  14183. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  14184. var attributes = effect.getAttributesNames();
  14185. if (!this._vaoRecordInProgress) {
  14186. this._unbindVertexArrayObject();
  14187. }
  14188. this.unbindAllAttributes();
  14189. for (var index = 0; index < attributes.length; index++) {
  14190. var order = effect.getAttributeLocation(index);
  14191. if (order >= 0) {
  14192. var vertexBuffer = vertexBuffers[attributes[index]];
  14193. if (!vertexBuffer) {
  14194. continue;
  14195. }
  14196. this._gl.enableVertexAttribArray(order);
  14197. if (!this._vaoRecordInProgress) {
  14198. this._vertexAttribArraysEnabled[order] = true;
  14199. }
  14200. var buffer = vertexBuffer.getBuffer();
  14201. if (buffer) {
  14202. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  14203. if (vertexBuffer.getIsInstanced()) {
  14204. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  14205. if (!this._vaoRecordInProgress) {
  14206. this._currentInstanceLocations.push(order);
  14207. this._currentInstanceBuffers.push(buffer);
  14208. }
  14209. }
  14210. }
  14211. }
  14212. }
  14213. };
  14214. /**
  14215. * Records a vertex array object
  14216. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  14217. * @param vertexBuffers defines the list of vertex buffers to store
  14218. * @param indexBuffer defines the index buffer to store
  14219. * @param effect defines the effect to store
  14220. * @returns the new vertex array object
  14221. */
  14222. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  14223. var vao = this._gl.createVertexArray();
  14224. this._vaoRecordInProgress = true;
  14225. this._gl.bindVertexArray(vao);
  14226. this._mustWipeVertexAttributes = true;
  14227. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  14228. this.bindIndexBuffer(indexBuffer);
  14229. this._vaoRecordInProgress = false;
  14230. this._gl.bindVertexArray(null);
  14231. return vao;
  14232. };
  14233. /**
  14234. * Bind a specific vertex array object
  14235. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  14236. * @param vertexArrayObject defines the vertex array object to bind
  14237. * @param indexBuffer defines the index buffer to bind
  14238. */
  14239. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  14240. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  14241. this._cachedVertexArrayObject = vertexArrayObject;
  14242. this._gl.bindVertexArray(vertexArrayObject);
  14243. this._cachedVertexBuffers = null;
  14244. this._cachedIndexBuffer = null;
  14245. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  14246. this._mustWipeVertexAttributes = true;
  14247. }
  14248. };
  14249. /**
  14250. * Bind webGl buffers directly to the webGL context
  14251. * @param vertexBuffer defines the vertex buffer to bind
  14252. * @param indexBuffer defines the index buffer to bind
  14253. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  14254. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  14255. * @param effect defines the effect associated with the vertex buffer
  14256. */
  14257. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  14258. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  14259. this._cachedVertexBuffers = vertexBuffer;
  14260. this._cachedEffectForVertexBuffers = effect;
  14261. var attributesCount = effect.getAttributesCount();
  14262. this._unbindVertexArrayObject();
  14263. this.unbindAllAttributes();
  14264. var offset = 0;
  14265. for (var index = 0; index < attributesCount; index++) {
  14266. if (index < vertexDeclaration.length) {
  14267. var order = effect.getAttributeLocation(index);
  14268. if (order >= 0) {
  14269. this._gl.enableVertexAttribArray(order);
  14270. this._vertexAttribArraysEnabled[order] = true;
  14271. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  14272. }
  14273. offset += vertexDeclaration[index] * 4;
  14274. }
  14275. }
  14276. }
  14277. this._bindIndexBufferWithCache(indexBuffer);
  14278. };
  14279. Engine.prototype._unbindVertexArrayObject = function () {
  14280. if (!this._cachedVertexArrayObject) {
  14281. return;
  14282. }
  14283. this._cachedVertexArrayObject = null;
  14284. this._gl.bindVertexArray(null);
  14285. };
  14286. /**
  14287. * Bind a list of vertex buffers to the webGL context
  14288. * @param vertexBuffers defines the list of vertex buffers to bind
  14289. * @param indexBuffer defines the index buffer to bind
  14290. * @param effect defines the effect associated with the vertex buffers
  14291. */
  14292. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  14293. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  14294. this._cachedVertexBuffers = vertexBuffers;
  14295. this._cachedEffectForVertexBuffers = effect;
  14296. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  14297. }
  14298. this._bindIndexBufferWithCache(indexBuffer);
  14299. };
  14300. /**
  14301. * Unbind all instance attributes
  14302. */
  14303. Engine.prototype.unbindInstanceAttributes = function () {
  14304. var boundBuffer;
  14305. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  14306. var instancesBuffer = this._currentInstanceBuffers[i];
  14307. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  14308. boundBuffer = instancesBuffer;
  14309. this.bindArrayBuffer(instancesBuffer);
  14310. }
  14311. var offsetLocation = this._currentInstanceLocations[i];
  14312. this._gl.vertexAttribDivisor(offsetLocation, 0);
  14313. }
  14314. this._currentInstanceBuffers.length = 0;
  14315. this._currentInstanceLocations.length = 0;
  14316. };
  14317. /**
  14318. * Release and free the memory of a vertex array object
  14319. * @param vao defines the vertex array object to delete
  14320. */
  14321. Engine.prototype.releaseVertexArrayObject = function (vao) {
  14322. this._gl.deleteVertexArray(vao);
  14323. };
  14324. /** @hidden */
  14325. Engine.prototype._releaseBuffer = function (buffer) {
  14326. buffer.references--;
  14327. if (buffer.references === 0) {
  14328. this._gl.deleteBuffer(buffer);
  14329. return true;
  14330. }
  14331. return false;
  14332. };
  14333. /**
  14334. * Creates a webGL buffer to use with instanciation
  14335. * @param capacity defines the size of the buffer
  14336. * @returns the webGL buffer
  14337. */
  14338. Engine.prototype.createInstancesBuffer = function (capacity) {
  14339. var buffer = this._gl.createBuffer();
  14340. if (!buffer) {
  14341. throw new Error("Unable to create instance buffer");
  14342. }
  14343. buffer.capacity = capacity;
  14344. this.bindArrayBuffer(buffer);
  14345. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  14346. return buffer;
  14347. };
  14348. /**
  14349. * Delete a webGL buffer used with instanciation
  14350. * @param buffer defines the webGL buffer to delete
  14351. */
  14352. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  14353. this._gl.deleteBuffer(buffer);
  14354. };
  14355. /**
  14356. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  14357. * @param instancesBuffer defines the webGL buffer to update and bind
  14358. * @param data defines the data to store in the buffer
  14359. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  14360. */
  14361. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  14362. this.bindArrayBuffer(instancesBuffer);
  14363. if (data) {
  14364. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  14365. }
  14366. if (offsetLocations[0].index !== undefined) {
  14367. var stride = 0;
  14368. for (var i = 0; i < offsetLocations.length; i++) {
  14369. var ai = offsetLocations[i];
  14370. stride += ai.attributeSize * 4;
  14371. }
  14372. for (var i = 0; i < offsetLocations.length; i++) {
  14373. var ai = offsetLocations[i];
  14374. if (!this._vertexAttribArraysEnabled[ai.index]) {
  14375. this._gl.enableVertexAttribArray(ai.index);
  14376. this._vertexAttribArraysEnabled[ai.index] = true;
  14377. }
  14378. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  14379. this._gl.vertexAttribDivisor(ai.index, 1);
  14380. this._currentInstanceLocations.push(ai.index);
  14381. this._currentInstanceBuffers.push(instancesBuffer);
  14382. }
  14383. }
  14384. else {
  14385. for (var index = 0; index < 4; index++) {
  14386. var offsetLocation = offsetLocations[index];
  14387. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  14388. this._gl.enableVertexAttribArray(offsetLocation);
  14389. this._vertexAttribArraysEnabled[offsetLocation] = true;
  14390. }
  14391. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  14392. this._gl.vertexAttribDivisor(offsetLocation, 1);
  14393. this._currentInstanceLocations.push(offsetLocation);
  14394. this._currentInstanceBuffers.push(instancesBuffer);
  14395. }
  14396. }
  14397. };
  14398. /**
  14399. * Apply all cached states (depth, culling, stencil and alpha)
  14400. */
  14401. Engine.prototype.applyStates = function () {
  14402. this._depthCullingState.apply(this._gl);
  14403. this._stencilState.apply(this._gl);
  14404. this._alphaState.apply(this._gl);
  14405. };
  14406. /**
  14407. * Send a draw order
  14408. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  14409. * @param indexStart defines the starting index
  14410. * @param indexCount defines the number of index to draw
  14411. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14412. */
  14413. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  14414. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  14415. };
  14416. /**
  14417. * Draw a list of points
  14418. * @param verticesStart defines the index of first vertex to draw
  14419. * @param verticesCount defines the count of vertices to draw
  14420. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14421. */
  14422. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  14423. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  14424. };
  14425. /**
  14426. * Draw a list of unindexed primitives
  14427. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  14428. * @param verticesStart defines the index of first vertex to draw
  14429. * @param verticesCount defines the count of vertices to draw
  14430. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14431. */
  14432. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  14433. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  14434. };
  14435. /**
  14436. * Draw a list of indexed primitives
  14437. * @param fillMode defines the primitive to use
  14438. * @param indexStart defines the starting index
  14439. * @param indexCount defines the number of index to draw
  14440. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14441. */
  14442. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  14443. // Apply states
  14444. this.applyStates();
  14445. this._drawCalls.addCount(1, false);
  14446. // Render
  14447. var drawMode = this._drawMode(fillMode);
  14448. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  14449. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  14450. if (instancesCount) {
  14451. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  14452. }
  14453. else {
  14454. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  14455. }
  14456. };
  14457. /**
  14458. * Draw a list of unindexed primitives
  14459. * @param fillMode defines the primitive to use
  14460. * @param verticesStart defines the index of first vertex to draw
  14461. * @param verticesCount defines the count of vertices to draw
  14462. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14463. */
  14464. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  14465. // Apply states
  14466. this.applyStates();
  14467. this._drawCalls.addCount(1, false);
  14468. var drawMode = this._drawMode(fillMode);
  14469. if (instancesCount) {
  14470. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  14471. }
  14472. else {
  14473. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  14474. }
  14475. };
  14476. Engine.prototype._drawMode = function (fillMode) {
  14477. switch (fillMode) {
  14478. // Triangle views
  14479. case BABYLON.Material.TriangleFillMode:
  14480. return this._gl.TRIANGLES;
  14481. case BABYLON.Material.PointFillMode:
  14482. return this._gl.POINTS;
  14483. case BABYLON.Material.WireFrameFillMode:
  14484. return this._gl.LINES;
  14485. // Draw modes
  14486. case BABYLON.Material.PointListDrawMode:
  14487. return this._gl.POINTS;
  14488. case BABYLON.Material.LineListDrawMode:
  14489. return this._gl.LINES;
  14490. case BABYLON.Material.LineLoopDrawMode:
  14491. return this._gl.LINE_LOOP;
  14492. case BABYLON.Material.LineStripDrawMode:
  14493. return this._gl.LINE_STRIP;
  14494. case BABYLON.Material.TriangleStripDrawMode:
  14495. return this._gl.TRIANGLE_STRIP;
  14496. case BABYLON.Material.TriangleFanDrawMode:
  14497. return this._gl.TRIANGLE_FAN;
  14498. default:
  14499. return this._gl.TRIANGLES;
  14500. }
  14501. };
  14502. // Shaders
  14503. /** @hidden */
  14504. Engine.prototype._releaseEffect = function (effect) {
  14505. if (this._compiledEffects[effect._key]) {
  14506. delete this._compiledEffects[effect._key];
  14507. this._deleteProgram(effect.getProgram());
  14508. }
  14509. };
  14510. /** @hidden */
  14511. Engine.prototype._deleteProgram = function (program) {
  14512. if (program) {
  14513. program.__SPECTOR_rebuildProgram = null;
  14514. if (program.transformFeedback) {
  14515. this.deleteTransformFeedback(program.transformFeedback);
  14516. program.transformFeedback = null;
  14517. }
  14518. this._gl.deleteProgram(program);
  14519. }
  14520. };
  14521. /**
  14522. * Create a new effect (used to store vertex/fragment shaders)
  14523. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  14524. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  14525. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  14526. * @param samplers defines an array of string used to represent textures
  14527. * @param defines defines the string containing the defines to use to compile the shaders
  14528. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  14529. * @param onCompiled defines a function to call when the effect creation is successful
  14530. * @param onError defines a function to call when the effect creation has failed
  14531. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  14532. * @returns the new Effect
  14533. */
  14534. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  14535. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  14536. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  14537. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  14538. if (this._compiledEffects[name]) {
  14539. var compiledEffect = this._compiledEffects[name];
  14540. if (onCompiled && compiledEffect.isReady()) {
  14541. onCompiled(compiledEffect);
  14542. }
  14543. return compiledEffect;
  14544. }
  14545. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  14546. effect._key = name;
  14547. this._compiledEffects[name] = effect;
  14548. return effect;
  14549. };
  14550. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  14551. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  14552. };
  14553. Engine.prototype._compileRawShader = function (source, type) {
  14554. var gl = this._gl;
  14555. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  14556. if (!shader) {
  14557. throw new Error("Something went wrong while compile the shader.");
  14558. }
  14559. gl.shaderSource(shader, source);
  14560. gl.compileShader(shader);
  14561. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  14562. var log = gl.getShaderInfoLog(shader);
  14563. if (log) {
  14564. throw new Error(log);
  14565. }
  14566. }
  14567. return shader;
  14568. };
  14569. /**
  14570. * Directly creates a webGL program
  14571. * @param vertexCode defines the vertex shader code to use
  14572. * @param fragmentCode defines the fragment shader code to use
  14573. * @param context defines the webGL context to use (if not set, the current one will be used)
  14574. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14575. * @returns the new webGL program
  14576. */
  14577. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  14578. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14579. context = context || this._gl;
  14580. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  14581. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  14582. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14583. };
  14584. /**
  14585. * Creates a webGL program
  14586. * @param vertexCode defines the vertex shader code to use
  14587. * @param fragmentCode defines the fragment shader code to use
  14588. * @param defines defines the string containing the defines to use to compile the shaders
  14589. * @param context defines the webGL context to use (if not set, the current one will be used)
  14590. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14591. * @returns the new webGL program
  14592. */
  14593. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  14594. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14595. context = context || this._gl;
  14596. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  14597. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  14598. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  14599. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  14600. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14601. this.onAfterShaderCompilationObservable.notifyObservers(this);
  14602. return program;
  14603. };
  14604. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  14605. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14606. var shaderProgram = context.createProgram();
  14607. if (!shaderProgram) {
  14608. throw new Error("Unable to create program");
  14609. }
  14610. context.attachShader(shaderProgram, vertexShader);
  14611. context.attachShader(shaderProgram, fragmentShader);
  14612. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14613. var transformFeedback = this.createTransformFeedback();
  14614. this.bindTransformFeedback(transformFeedback);
  14615. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  14616. shaderProgram.transformFeedback = transformFeedback;
  14617. }
  14618. context.linkProgram(shaderProgram);
  14619. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14620. this.bindTransformFeedback(null);
  14621. }
  14622. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  14623. if (!linked) {
  14624. var error = context.getProgramInfoLog(shaderProgram);
  14625. if (error) {
  14626. throw new Error(error);
  14627. }
  14628. }
  14629. if (this.validateShaderPrograms) {
  14630. context.validateProgram(shaderProgram);
  14631. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  14632. if (!validated) {
  14633. var error = context.getProgramInfoLog(shaderProgram);
  14634. if (error) {
  14635. throw new Error(error);
  14636. }
  14637. }
  14638. }
  14639. context.deleteShader(vertexShader);
  14640. context.deleteShader(fragmentShader);
  14641. return shaderProgram;
  14642. };
  14643. /**
  14644. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14645. * @param shaderProgram defines the webGL program to use
  14646. * @param uniformsNames defines the list of uniform names
  14647. * @returns an array of webGL uniform locations
  14648. */
  14649. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14650. var results = new Array();
  14651. for (var index = 0; index < uniformsNames.length; index++) {
  14652. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14653. }
  14654. return results;
  14655. };
  14656. /**
  14657. * Gets the lsit of active attributes for a given webGL program
  14658. * @param shaderProgram defines the webGL program to use
  14659. * @param attributesNames defines the list of attribute names to get
  14660. * @returns an array of indices indicating the offset of each attribute
  14661. */
  14662. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14663. var results = [];
  14664. for (var index = 0; index < attributesNames.length; index++) {
  14665. try {
  14666. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14667. }
  14668. catch (e) {
  14669. results.push(-1);
  14670. }
  14671. }
  14672. return results;
  14673. };
  14674. /**
  14675. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14676. * @param effect defines the effect to activate
  14677. */
  14678. Engine.prototype.enableEffect = function (effect) {
  14679. if (!effect || effect === this._currentEffect) {
  14680. return;
  14681. }
  14682. // Use program
  14683. this.bindSamplers(effect);
  14684. this._currentEffect = effect;
  14685. if (effect.onBind) {
  14686. effect.onBind(effect);
  14687. }
  14688. if (effect._onBindObservable) {
  14689. effect._onBindObservable.notifyObservers(effect);
  14690. }
  14691. };
  14692. /**
  14693. * Set the value of an uniform to an array of int32
  14694. * @param uniform defines the webGL uniform location where to store the value
  14695. * @param array defines the array of int32 to store
  14696. */
  14697. Engine.prototype.setIntArray = function (uniform, array) {
  14698. if (!uniform) {
  14699. return;
  14700. }
  14701. this._gl.uniform1iv(uniform, array);
  14702. };
  14703. /**
  14704. * Set the value of an uniform to an array of int32 (stored as vec2)
  14705. * @param uniform defines the webGL uniform location where to store the value
  14706. * @param array defines the array of int32 to store
  14707. */
  14708. Engine.prototype.setIntArray2 = function (uniform, array) {
  14709. if (!uniform || array.length % 2 !== 0) {
  14710. return;
  14711. }
  14712. this._gl.uniform2iv(uniform, array);
  14713. };
  14714. /**
  14715. * Set the value of an uniform to an array of int32 (stored as vec3)
  14716. * @param uniform defines the webGL uniform location where to store the value
  14717. * @param array defines the array of int32 to store
  14718. */
  14719. Engine.prototype.setIntArray3 = function (uniform, array) {
  14720. if (!uniform || array.length % 3 !== 0) {
  14721. return;
  14722. }
  14723. this._gl.uniform3iv(uniform, array);
  14724. };
  14725. /**
  14726. * Set the value of an uniform to an array of int32 (stored as vec4)
  14727. * @param uniform defines the webGL uniform location where to store the value
  14728. * @param array defines the array of int32 to store
  14729. */
  14730. Engine.prototype.setIntArray4 = function (uniform, array) {
  14731. if (!uniform || array.length % 4 !== 0) {
  14732. return;
  14733. }
  14734. this._gl.uniform4iv(uniform, array);
  14735. };
  14736. /**
  14737. * Set the value of an uniform to an array of float32
  14738. * @param uniform defines the webGL uniform location where to store the value
  14739. * @param array defines the array of float32 to store
  14740. */
  14741. Engine.prototype.setFloatArray = function (uniform, array) {
  14742. if (!uniform) {
  14743. return;
  14744. }
  14745. this._gl.uniform1fv(uniform, array);
  14746. };
  14747. /**
  14748. * Set the value of an uniform to an array of float32 (stored as vec2)
  14749. * @param uniform defines the webGL uniform location where to store the value
  14750. * @param array defines the array of float32 to store
  14751. */
  14752. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14753. if (!uniform || array.length % 2 !== 0) {
  14754. return;
  14755. }
  14756. this._gl.uniform2fv(uniform, array);
  14757. };
  14758. /**
  14759. * Set the value of an uniform to an array of float32 (stored as vec3)
  14760. * @param uniform defines the webGL uniform location where to store the value
  14761. * @param array defines the array of float32 to store
  14762. */
  14763. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14764. if (!uniform || array.length % 3 !== 0) {
  14765. return;
  14766. }
  14767. this._gl.uniform3fv(uniform, array);
  14768. };
  14769. /**
  14770. * Set the value of an uniform to an array of float32 (stored as vec4)
  14771. * @param uniform defines the webGL uniform location where to store the value
  14772. * @param array defines the array of float32 to store
  14773. */
  14774. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14775. if (!uniform || array.length % 4 !== 0) {
  14776. return;
  14777. }
  14778. this._gl.uniform4fv(uniform, array);
  14779. };
  14780. /**
  14781. * Set the value of an uniform to an array of number
  14782. * @param uniform defines the webGL uniform location where to store the value
  14783. * @param array defines the array of number to store
  14784. */
  14785. Engine.prototype.setArray = function (uniform, array) {
  14786. if (!uniform) {
  14787. return;
  14788. }
  14789. this._gl.uniform1fv(uniform, array);
  14790. };
  14791. /**
  14792. * Set the value of an uniform to an array of number (stored as vec2)
  14793. * @param uniform defines the webGL uniform location where to store the value
  14794. * @param array defines the array of number to store
  14795. */
  14796. Engine.prototype.setArray2 = function (uniform, array) {
  14797. if (!uniform || array.length % 2 !== 0) {
  14798. return;
  14799. }
  14800. this._gl.uniform2fv(uniform, array);
  14801. };
  14802. /**
  14803. * Set the value of an uniform to an array of number (stored as vec3)
  14804. * @param uniform defines the webGL uniform location where to store the value
  14805. * @param array defines the array of number to store
  14806. */
  14807. Engine.prototype.setArray3 = function (uniform, array) {
  14808. if (!uniform || array.length % 3 !== 0) {
  14809. return;
  14810. }
  14811. this._gl.uniform3fv(uniform, array);
  14812. };
  14813. /**
  14814. * Set the value of an uniform to an array of number (stored as vec4)
  14815. * @param uniform defines the webGL uniform location where to store the value
  14816. * @param array defines the array of number to store
  14817. */
  14818. Engine.prototype.setArray4 = function (uniform, array) {
  14819. if (!uniform || array.length % 4 !== 0) {
  14820. return;
  14821. }
  14822. this._gl.uniform4fv(uniform, array);
  14823. };
  14824. /**
  14825. * Set the value of an uniform to an array of float32 (stored as matrices)
  14826. * @param uniform defines the webGL uniform location where to store the value
  14827. * @param matrices defines the array of float32 to store
  14828. */
  14829. Engine.prototype.setMatrices = function (uniform, matrices) {
  14830. if (!uniform) {
  14831. return;
  14832. }
  14833. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14834. };
  14835. /**
  14836. * Set the value of an uniform to a matrix
  14837. * @param uniform defines the webGL uniform location where to store the value
  14838. * @param matrix defines the matrix to store
  14839. */
  14840. Engine.prototype.setMatrix = function (uniform, matrix) {
  14841. if (!uniform) {
  14842. return;
  14843. }
  14844. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14845. };
  14846. /**
  14847. * Set the value of an uniform to a matrix (3x3)
  14848. * @param uniform defines the webGL uniform location where to store the value
  14849. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14850. */
  14851. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14852. if (!uniform) {
  14853. return;
  14854. }
  14855. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14856. };
  14857. /**
  14858. * Set the value of an uniform to a matrix (2x2)
  14859. * @param uniform defines the webGL uniform location where to store the value
  14860. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14861. */
  14862. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14863. if (!uniform) {
  14864. return;
  14865. }
  14866. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14867. };
  14868. /**
  14869. * Set the value of an uniform to a number (int)
  14870. * @param uniform defines the webGL uniform location where to store the value
  14871. * @param value defines the int number to store
  14872. */
  14873. Engine.prototype.setInt = function (uniform, value) {
  14874. if (!uniform) {
  14875. return;
  14876. }
  14877. this._gl.uniform1i(uniform, value);
  14878. };
  14879. /**
  14880. * Set the value of an uniform to a number (float)
  14881. * @param uniform defines the webGL uniform location where to store the value
  14882. * @param value defines the float number to store
  14883. */
  14884. Engine.prototype.setFloat = function (uniform, value) {
  14885. if (!uniform) {
  14886. return;
  14887. }
  14888. this._gl.uniform1f(uniform, value);
  14889. };
  14890. /**
  14891. * Set the value of an uniform to a vec2
  14892. * @param uniform defines the webGL uniform location where to store the value
  14893. * @param x defines the 1st component of the value
  14894. * @param y defines the 2nd component of the value
  14895. */
  14896. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14897. if (!uniform) {
  14898. return;
  14899. }
  14900. this._gl.uniform2f(uniform, x, y);
  14901. };
  14902. /**
  14903. * Set the value of an uniform to a vec3
  14904. * @param uniform defines the webGL uniform location where to store the value
  14905. * @param x defines the 1st component of the value
  14906. * @param y defines the 2nd component of the value
  14907. * @param z defines the 3rd component of the value
  14908. */
  14909. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14910. if (!uniform) {
  14911. return;
  14912. }
  14913. this._gl.uniform3f(uniform, x, y, z);
  14914. };
  14915. /**
  14916. * Set the value of an uniform to a boolean
  14917. * @param uniform defines the webGL uniform location where to store the value
  14918. * @param bool defines the boolean to store
  14919. */
  14920. Engine.prototype.setBool = function (uniform, bool) {
  14921. if (!uniform) {
  14922. return;
  14923. }
  14924. this._gl.uniform1i(uniform, bool);
  14925. };
  14926. /**
  14927. * Set the value of an uniform to a vec4
  14928. * @param uniform defines the webGL uniform location where to store the value
  14929. * @param x defines the 1st component of the value
  14930. * @param y defines the 2nd component of the value
  14931. * @param z defines the 3rd component of the value
  14932. * @param w defines the 4th component of the value
  14933. */
  14934. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14935. if (!uniform) {
  14936. return;
  14937. }
  14938. this._gl.uniform4f(uniform, x, y, z, w);
  14939. };
  14940. /**
  14941. * Set the value of an uniform to a Color3
  14942. * @param uniform defines the webGL uniform location where to store the value
  14943. * @param color3 defines the color to store
  14944. */
  14945. Engine.prototype.setColor3 = function (uniform, color3) {
  14946. if (!uniform) {
  14947. return;
  14948. }
  14949. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14950. };
  14951. /**
  14952. * Set the value of an uniform to a Color3 and an alpha value
  14953. * @param uniform defines the webGL uniform location where to store the value
  14954. * @param color3 defines the color to store
  14955. * @param alpha defines the alpha component to store
  14956. */
  14957. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14958. if (!uniform) {
  14959. return;
  14960. }
  14961. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14962. };
  14963. /**
  14964. * Sets a Color4 on a uniform variable
  14965. * @param uniform defines the uniform location
  14966. * @param color4 defines the value to be set
  14967. */
  14968. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14969. if (!uniform) {
  14970. return;
  14971. }
  14972. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14973. };
  14974. // States
  14975. /**
  14976. * Set various states to the webGL context
  14977. * @param culling defines backface culling state
  14978. * @param zOffset defines the value to apply to zOffset (0 by default)
  14979. * @param force defines if states must be applied even if cache is up to date
  14980. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14981. */
  14982. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14983. if (zOffset === void 0) { zOffset = 0; }
  14984. if (reverseSide === void 0) { reverseSide = false; }
  14985. // Culling
  14986. if (this._depthCullingState.cull !== culling || force) {
  14987. this._depthCullingState.cull = culling;
  14988. }
  14989. // Cull face
  14990. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14991. if (this._depthCullingState.cullFace !== cullFace || force) {
  14992. this._depthCullingState.cullFace = cullFace;
  14993. }
  14994. // Z offset
  14995. this.setZOffset(zOffset);
  14996. // Front face
  14997. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14998. if (this._depthCullingState.frontFace !== frontFace || force) {
  14999. this._depthCullingState.frontFace = frontFace;
  15000. }
  15001. };
  15002. /**
  15003. * Set the z offset to apply to current rendering
  15004. * @param value defines the offset to apply
  15005. */
  15006. Engine.prototype.setZOffset = function (value) {
  15007. this._depthCullingState.zOffset = value;
  15008. };
  15009. /**
  15010. * Gets the current value of the zOffset
  15011. * @returns the current zOffset state
  15012. */
  15013. Engine.prototype.getZOffset = function () {
  15014. return this._depthCullingState.zOffset;
  15015. };
  15016. /**
  15017. * Enable or disable depth buffering
  15018. * @param enable defines the state to set
  15019. */
  15020. Engine.prototype.setDepthBuffer = function (enable) {
  15021. this._depthCullingState.depthTest = enable;
  15022. };
  15023. /**
  15024. * Gets a boolean indicating if depth writing is enabled
  15025. * @returns the current depth writing state
  15026. */
  15027. Engine.prototype.getDepthWrite = function () {
  15028. return this._depthCullingState.depthMask;
  15029. };
  15030. /**
  15031. * Enable or disable depth writing
  15032. * @param enable defines the state to set
  15033. */
  15034. Engine.prototype.setDepthWrite = function (enable) {
  15035. this._depthCullingState.depthMask = enable;
  15036. };
  15037. /**
  15038. * Enable or disable color writing
  15039. * @param enable defines the state to set
  15040. */
  15041. Engine.prototype.setColorWrite = function (enable) {
  15042. this._gl.colorMask(enable, enable, enable, enable);
  15043. this._colorWrite = enable;
  15044. };
  15045. /**
  15046. * Gets a boolean indicating if color writing is enabled
  15047. * @returns the current color writing state
  15048. */
  15049. Engine.prototype.getColorWrite = function () {
  15050. return this._colorWrite;
  15051. };
  15052. /**
  15053. * Sets alpha constants used by some alpha blending modes
  15054. * @param r defines the red component
  15055. * @param g defines the green component
  15056. * @param b defines the blue component
  15057. * @param a defines the alpha component
  15058. */
  15059. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  15060. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  15061. };
  15062. /**
  15063. * Sets the current alpha mode
  15064. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  15065. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  15066. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  15067. */
  15068. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  15069. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  15070. if (this._alphaMode === mode) {
  15071. return;
  15072. }
  15073. switch (mode) {
  15074. case Engine.ALPHA_DISABLE:
  15075. this._alphaState.alphaBlend = false;
  15076. break;
  15077. case Engine.ALPHA_PREMULTIPLIED:
  15078. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  15079. this._alphaState.alphaBlend = true;
  15080. break;
  15081. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  15082. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  15083. this._alphaState.alphaBlend = true;
  15084. break;
  15085. case Engine.ALPHA_COMBINE:
  15086. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  15087. this._alphaState.alphaBlend = true;
  15088. break;
  15089. case Engine.ALPHA_ONEONE:
  15090. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  15091. this._alphaState.alphaBlend = true;
  15092. break;
  15093. case Engine.ALPHA_ADD:
  15094. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  15095. this._alphaState.alphaBlend = true;
  15096. break;
  15097. case Engine.ALPHA_SUBTRACT:
  15098. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  15099. this._alphaState.alphaBlend = true;
  15100. break;
  15101. case Engine.ALPHA_MULTIPLY:
  15102. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  15103. this._alphaState.alphaBlend = true;
  15104. break;
  15105. case Engine.ALPHA_MAXIMIZED:
  15106. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  15107. this._alphaState.alphaBlend = true;
  15108. break;
  15109. case Engine.ALPHA_INTERPOLATE:
  15110. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  15111. this._alphaState.alphaBlend = true;
  15112. break;
  15113. case Engine.ALPHA_SCREENMODE:
  15114. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  15115. this._alphaState.alphaBlend = true;
  15116. break;
  15117. }
  15118. if (!noDepthWriteChange) {
  15119. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  15120. }
  15121. this._alphaMode = mode;
  15122. };
  15123. /**
  15124. * Gets the current alpha mode
  15125. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  15126. * @returns the current alpha mode
  15127. */
  15128. Engine.prototype.getAlphaMode = function () {
  15129. return this._alphaMode;
  15130. };
  15131. // Textures
  15132. /**
  15133. * Clears the list of texture accessible through engine.
  15134. * This can help preventing texture load conflict due to name collision.
  15135. */
  15136. Engine.prototype.clearInternalTexturesCache = function () {
  15137. this._internalTexturesCache = [];
  15138. };
  15139. /**
  15140. * Force the entire cache to be cleared
  15141. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  15142. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  15143. */
  15144. Engine.prototype.wipeCaches = function (bruteForce) {
  15145. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  15146. return;
  15147. }
  15148. this._currentEffect = null;
  15149. this._viewportCached.x = 0;
  15150. this._viewportCached.y = 0;
  15151. this._viewportCached.z = 0;
  15152. this._viewportCached.w = 0;
  15153. if (bruteForce) {
  15154. this.resetTextureCache();
  15155. this._currentProgram = null;
  15156. this._stencilState.reset();
  15157. this._depthCullingState.reset();
  15158. this.setDepthFunctionToLessOrEqual();
  15159. this._alphaState.reset();
  15160. this._unpackFlipYCached = null;
  15161. }
  15162. this._resetVertexBufferBinding();
  15163. this._cachedIndexBuffer = null;
  15164. this._cachedEffectForVertexBuffers = null;
  15165. this._unbindVertexArrayObject();
  15166. this.bindIndexBuffer(null);
  15167. };
  15168. /**
  15169. * Set the compressed texture format to use, based on the formats you have, and the formats
  15170. * supported by the hardware / browser.
  15171. *
  15172. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  15173. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  15174. * to API arguments needed to compressed textures. This puts the burden on the container
  15175. * generator to house the arcane code for determining these for current & future formats.
  15176. *
  15177. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  15178. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  15179. *
  15180. * Note: The result of this call is not taken into account when a texture is base64.
  15181. *
  15182. * @param formatsAvailable defines the list of those format families you have created
  15183. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  15184. *
  15185. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  15186. * @returns The extension selected.
  15187. */
  15188. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  15189. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  15190. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  15191. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  15192. return this._textureFormatInUse = this._texturesSupported[i];
  15193. }
  15194. }
  15195. }
  15196. // actively set format to nothing, to allow this to be called more than once
  15197. // and possibly fail the 2nd time
  15198. this._textureFormatInUse = null;
  15199. return null;
  15200. };
  15201. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  15202. var gl = this._gl;
  15203. var magFilter = gl.NEAREST;
  15204. var minFilter = gl.NEAREST;
  15205. switch (samplingMode) {
  15206. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  15207. magFilter = gl.LINEAR;
  15208. if (generateMipMaps) {
  15209. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  15210. }
  15211. else {
  15212. minFilter = gl.LINEAR;
  15213. }
  15214. break;
  15215. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  15216. magFilter = gl.LINEAR;
  15217. if (generateMipMaps) {
  15218. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  15219. }
  15220. else {
  15221. minFilter = gl.LINEAR;
  15222. }
  15223. break;
  15224. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  15225. magFilter = gl.NEAREST;
  15226. if (generateMipMaps) {
  15227. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  15228. }
  15229. else {
  15230. minFilter = gl.NEAREST;
  15231. }
  15232. break;
  15233. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  15234. magFilter = gl.NEAREST;
  15235. if (generateMipMaps) {
  15236. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  15237. }
  15238. else {
  15239. minFilter = gl.NEAREST;
  15240. }
  15241. break;
  15242. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  15243. magFilter = gl.NEAREST;
  15244. if (generateMipMaps) {
  15245. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  15246. }
  15247. else {
  15248. minFilter = gl.LINEAR;
  15249. }
  15250. break;
  15251. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  15252. magFilter = gl.NEAREST;
  15253. if (generateMipMaps) {
  15254. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  15255. }
  15256. else {
  15257. minFilter = gl.LINEAR;
  15258. }
  15259. break;
  15260. case Engine.TEXTURE_NEAREST_LINEAR:
  15261. magFilter = gl.NEAREST;
  15262. minFilter = gl.LINEAR;
  15263. break;
  15264. case Engine.TEXTURE_NEAREST_NEAREST:
  15265. magFilter = gl.NEAREST;
  15266. minFilter = gl.NEAREST;
  15267. break;
  15268. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  15269. magFilter = gl.LINEAR;
  15270. if (generateMipMaps) {
  15271. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  15272. }
  15273. else {
  15274. minFilter = gl.NEAREST;
  15275. }
  15276. break;
  15277. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  15278. magFilter = gl.LINEAR;
  15279. if (generateMipMaps) {
  15280. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  15281. }
  15282. else {
  15283. minFilter = gl.NEAREST;
  15284. }
  15285. break;
  15286. case Engine.TEXTURE_LINEAR_LINEAR:
  15287. magFilter = gl.LINEAR;
  15288. minFilter = gl.LINEAR;
  15289. break;
  15290. case Engine.TEXTURE_LINEAR_NEAREST:
  15291. magFilter = gl.LINEAR;
  15292. minFilter = gl.NEAREST;
  15293. break;
  15294. }
  15295. return {
  15296. min: minFilter,
  15297. mag: magFilter
  15298. };
  15299. };
  15300. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  15301. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15302. var img;
  15303. var onload = function () {
  15304. loadedImages[index] = img;
  15305. loadedImages._internalCount++;
  15306. if (scene) {
  15307. scene._removePendingData(img);
  15308. }
  15309. if (loadedImages._internalCount === 6) {
  15310. onfinish(loadedImages);
  15311. }
  15312. };
  15313. var onerror = function (message, exception) {
  15314. if (scene) {
  15315. scene._removePendingData(img);
  15316. }
  15317. if (onErrorCallBack) {
  15318. onErrorCallBack(message, exception);
  15319. }
  15320. };
  15321. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  15322. if (scene) {
  15323. scene._addPendingData(img);
  15324. }
  15325. };
  15326. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  15327. if (onError === void 0) { onError = null; }
  15328. var loadedImages = [];
  15329. loadedImages._internalCount = 0;
  15330. for (var index = 0; index < 6; index++) {
  15331. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  15332. }
  15333. };
  15334. /** @hidden */
  15335. Engine.prototype._createTexture = function () {
  15336. var texture = this._gl.createTexture();
  15337. if (!texture) {
  15338. throw new Error("Unable to create texture");
  15339. }
  15340. return texture;
  15341. };
  15342. /**
  15343. * Usually called from BABYLON.Texture.ts.
  15344. * Passed information to create a WebGLTexture
  15345. * @param urlArg defines a value which contains one of the following:
  15346. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  15347. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  15348. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  15349. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  15350. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  15351. * @param scene needed for loading to the correct scene
  15352. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  15353. * @param onLoad optional callback to be called upon successful completion
  15354. * @param onError optional callback to be called upon failure
  15355. * @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
  15356. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  15357. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  15358. * @param forcedExtension defines the extension to use to pick the right loader
  15359. * @returns a InternalTexture for assignment back into BABYLON.Texture
  15360. */
  15361. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  15362. var _this = this;
  15363. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15364. if (onLoad === void 0) { onLoad = null; }
  15365. if (onError === void 0) { onError = null; }
  15366. if (buffer === void 0) { buffer = null; }
  15367. if (fallback === void 0) { fallback = null; }
  15368. if (format === void 0) { format = null; }
  15369. if (forcedExtension === void 0) { forcedExtension = null; }
  15370. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  15371. var fromData = url.substr(0, 5) === "data:";
  15372. var fromBlob = url.substr(0, 5) === "blob:";
  15373. var isBase64 = fromData && url.indexOf(";base64,") !== -1;
  15374. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  15375. // establish the file extension, if possible
  15376. var lastDot = url.lastIndexOf('.');
  15377. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  15378. var loader = null;
  15379. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15380. var availableLoader = _a[_i];
  15381. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  15382. loader = availableLoader;
  15383. break;
  15384. }
  15385. }
  15386. if (loader) {
  15387. url = loader.transformUrl(url, this._textureFormatInUse);
  15388. }
  15389. if (scene) {
  15390. scene._addPendingData(texture);
  15391. }
  15392. texture.url = url;
  15393. texture.generateMipMaps = !noMipmap;
  15394. texture.samplingMode = samplingMode;
  15395. texture.invertY = invertY;
  15396. if (!this._doNotHandleContextLost) {
  15397. // Keep a link to the buffer only if we plan to handle context lost
  15398. texture._buffer = buffer;
  15399. }
  15400. var onLoadObserver = null;
  15401. if (onLoad && !fallback) {
  15402. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  15403. }
  15404. if (!fallback) {
  15405. this._internalTexturesCache.push(texture);
  15406. }
  15407. var onInternalError = function (message, exception) {
  15408. if (scene) {
  15409. scene._removePendingData(texture);
  15410. }
  15411. var customFallback = false;
  15412. if (loader) {
  15413. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  15414. if (fallbackUrl) {
  15415. // Add Back
  15416. customFallback = true;
  15417. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  15418. }
  15419. }
  15420. if (!customFallback) {
  15421. if (onLoadObserver) {
  15422. texture.onLoadedObservable.remove(onLoadObserver);
  15423. }
  15424. if (BABYLON.Tools.UseFallbackTexture) {
  15425. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  15426. }
  15427. }
  15428. if (onError) {
  15429. onError(message || "Unknown error", exception);
  15430. }
  15431. };
  15432. // processing for non-image formats
  15433. if (loader) {
  15434. var callback = function (data) {
  15435. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  15436. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  15437. done();
  15438. return false;
  15439. }, samplingMode);
  15440. });
  15441. };
  15442. if (!buffer) {
  15443. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  15444. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  15445. });
  15446. }
  15447. else {
  15448. callback(buffer);
  15449. }
  15450. }
  15451. else {
  15452. var onload = function (img) {
  15453. if (fromBlob && !_this._doNotHandleContextLost) {
  15454. // We need to store the image if we need to rebuild the texture
  15455. // in case of a webgl context lost
  15456. texture._buffer = img;
  15457. }
  15458. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  15459. var gl = _this._gl;
  15460. var isPot = (img.width === potWidth && img.height === potHeight);
  15461. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  15462. if (isPot) {
  15463. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  15464. return false;
  15465. }
  15466. var maxTextureSize = _this._caps.maxTextureSize;
  15467. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  15468. _this._prepareWorkingCanvas();
  15469. if (!_this._workingCanvas || !_this._workingContext) {
  15470. return false;
  15471. }
  15472. _this._workingCanvas.width = potWidth;
  15473. _this._workingCanvas.height = potHeight;
  15474. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  15475. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15476. texture.width = potWidth;
  15477. texture.height = potHeight;
  15478. return false;
  15479. }
  15480. else {
  15481. // Using shaders when possible to rescale because canvas.drawImage is lossy
  15482. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15483. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  15484. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  15485. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15486. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15487. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15488. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15489. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  15490. _this._releaseTexture(source_1);
  15491. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15492. continuationCallback();
  15493. });
  15494. }
  15495. return true;
  15496. }, samplingMode);
  15497. };
  15498. if (!fromData || isBase64) {
  15499. if (buffer instanceof HTMLImageElement) {
  15500. onload(buffer);
  15501. }
  15502. else {
  15503. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  15504. }
  15505. }
  15506. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  15507. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  15508. }
  15509. else {
  15510. onload(buffer);
  15511. }
  15512. }
  15513. return texture;
  15514. };
  15515. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  15516. var _this = this;
  15517. var rtt = this.createRenderTargetTexture({
  15518. width: destination.width,
  15519. height: destination.height,
  15520. }, {
  15521. generateMipMaps: false,
  15522. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  15523. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  15524. generateDepthBuffer: false,
  15525. generateStencilBuffer: false
  15526. });
  15527. if (!this._rescalePostProcess) {
  15528. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  15529. }
  15530. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  15531. _this._rescalePostProcess.onApply = function (effect) {
  15532. effect._bindTexture("textureSampler", source);
  15533. };
  15534. var hostingScene = scene;
  15535. if (!hostingScene) {
  15536. hostingScene = _this.scenes[_this.scenes.length - 1];
  15537. }
  15538. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  15539. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  15540. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  15541. _this.unBindFramebuffer(rtt);
  15542. _this._releaseTexture(rtt);
  15543. if (onComplete) {
  15544. onComplete();
  15545. }
  15546. });
  15547. };
  15548. /**
  15549. * Update a raw texture
  15550. * @param texture defines the texture to update
  15551. * @param data defines the data to store in the texture
  15552. * @param format defines the format of the data
  15553. * @param invertY defines if data must be stored with Y axis inverted
  15554. * @param compression defines the compression used (null by default)
  15555. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15556. */
  15557. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  15558. if (compression === void 0) { compression = null; }
  15559. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15560. if (!texture) {
  15561. return;
  15562. }
  15563. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  15564. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  15565. // babylon's internalFormat but gl's texImage2D format
  15566. var internalFormat = this._getInternalFormat(format);
  15567. var textureType = this._getWebGLTextureType(type);
  15568. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15569. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15570. if (!this._doNotHandleContextLost) {
  15571. texture._bufferView = data;
  15572. texture.format = format;
  15573. texture.type = type;
  15574. texture.invertY = invertY;
  15575. texture._compression = compression;
  15576. }
  15577. if (texture.width % 4 !== 0) {
  15578. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15579. }
  15580. if (compression && data) {
  15581. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  15582. }
  15583. else {
  15584. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  15585. }
  15586. if (texture.generateMipMaps) {
  15587. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15588. }
  15589. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15590. // this.resetTextureCache();
  15591. texture.isReady = true;
  15592. };
  15593. /**
  15594. * Creates a raw texture
  15595. * @param data defines the data to store in the texture
  15596. * @param width defines the width of the texture
  15597. * @param height defines the height of the texture
  15598. * @param format defines the format of the data
  15599. * @param generateMipMaps defines if the engine should generate the mip levels
  15600. * @param invertY defines if data must be stored with Y axis inverted
  15601. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  15602. * @param compression defines the compression used (null by default)
  15603. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15604. * @returns the raw texture inside an InternalTexture
  15605. */
  15606. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  15607. if (compression === void 0) { compression = null; }
  15608. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15609. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  15610. texture.baseWidth = width;
  15611. texture.baseHeight = height;
  15612. texture.width = width;
  15613. texture.height = height;
  15614. texture.format = format;
  15615. texture.generateMipMaps = generateMipMaps;
  15616. texture.samplingMode = samplingMode;
  15617. texture.invertY = invertY;
  15618. texture._compression = compression;
  15619. texture.type = type;
  15620. if (!this._doNotHandleContextLost) {
  15621. texture._bufferView = data;
  15622. }
  15623. this.updateRawTexture(texture, data, format, invertY, compression, type);
  15624. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15625. // Filters
  15626. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15627. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15628. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15629. if (generateMipMaps) {
  15630. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15631. }
  15632. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15633. this._internalTexturesCache.push(texture);
  15634. return texture;
  15635. };
  15636. /** @hidden */
  15637. Engine.prototype._unpackFlipY = function (value) {
  15638. if (this._unpackFlipYCached !== value) {
  15639. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  15640. if (this.enableUnpackFlipYCached) {
  15641. this._unpackFlipYCached = value;
  15642. }
  15643. }
  15644. };
  15645. /** @hidden */
  15646. Engine.prototype._getUnpackAlignement = function () {
  15647. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  15648. };
  15649. /**
  15650. * Creates a dynamic texture
  15651. * @param width defines the width of the texture
  15652. * @param height defines the height of the texture
  15653. * @param generateMipMaps defines if the engine should generate the mip levels
  15654. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  15655. * @returns the dynamic texture inside an InternalTexture
  15656. */
  15657. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  15658. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  15659. texture.baseWidth = width;
  15660. texture.baseHeight = height;
  15661. if (generateMipMaps) {
  15662. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  15663. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  15664. }
  15665. // this.resetTextureCache();
  15666. texture.width = width;
  15667. texture.height = height;
  15668. texture.isReady = false;
  15669. texture.generateMipMaps = generateMipMaps;
  15670. texture.samplingMode = samplingMode;
  15671. this.updateTextureSamplingMode(samplingMode, texture);
  15672. this._internalTexturesCache.push(texture);
  15673. return texture;
  15674. };
  15675. /**
  15676. * Update the sampling mode of a given texture
  15677. * @param samplingMode defines the required sampling mode
  15678. * @param texture defines the texture to update
  15679. */
  15680. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  15681. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  15682. if (texture.isCube) {
  15683. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15684. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15685. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15686. }
  15687. else if (texture.is3D) {
  15688. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15689. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15690. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15691. }
  15692. else {
  15693. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15694. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15695. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15696. }
  15697. texture.samplingMode = samplingMode;
  15698. };
  15699. /**
  15700. * Update the content of a dynamic texture
  15701. * @param texture defines the texture to update
  15702. * @param canvas defines the canvas containing the source
  15703. * @param invertY defines if data must be stored with Y axis inverted
  15704. * @param premulAlpha defines if alpha is stored as premultiplied
  15705. * @param format defines the format of the data
  15706. */
  15707. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  15708. if (premulAlpha === void 0) { premulAlpha = false; }
  15709. if (!texture) {
  15710. return;
  15711. }
  15712. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15713. this._unpackFlipY(invertY);
  15714. if (premulAlpha) {
  15715. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  15716. }
  15717. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  15718. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  15719. if (texture.generateMipMaps) {
  15720. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15721. }
  15722. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15723. if (premulAlpha) {
  15724. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  15725. }
  15726. texture.isReady = true;
  15727. };
  15728. /**
  15729. * Update a video texture
  15730. * @param texture defines the texture to update
  15731. * @param video defines the video element to use
  15732. * @param invertY defines if data must be stored with Y axis inverted
  15733. */
  15734. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  15735. if (!texture || texture._isDisabled) {
  15736. return;
  15737. }
  15738. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15739. this._unpackFlipY(!invertY); // Video are upside down by default
  15740. try {
  15741. // Testing video texture support
  15742. if (this._videoTextureSupported === undefined) {
  15743. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15744. if (this._gl.getError() !== 0) {
  15745. this._videoTextureSupported = false;
  15746. }
  15747. else {
  15748. this._videoTextureSupported = true;
  15749. }
  15750. }
  15751. // Copy video through the current working canvas if video texture is not supported
  15752. if (!this._videoTextureSupported) {
  15753. if (!texture._workingCanvas) {
  15754. texture._workingCanvas = document.createElement("canvas");
  15755. var context = texture._workingCanvas.getContext("2d");
  15756. if (!context) {
  15757. throw new Error("Unable to get 2d context");
  15758. }
  15759. texture._workingContext = context;
  15760. texture._workingCanvas.width = texture.width;
  15761. texture._workingCanvas.height = texture.height;
  15762. }
  15763. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  15764. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  15765. }
  15766. else {
  15767. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15768. }
  15769. if (texture.generateMipMaps) {
  15770. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15771. }
  15772. if (!wasPreviouslyBound) {
  15773. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15774. }
  15775. // this.resetTextureCache();
  15776. texture.isReady = true;
  15777. }
  15778. catch (ex) {
  15779. // Something unexpected
  15780. // Let's disable the texture
  15781. texture._isDisabled = true;
  15782. }
  15783. };
  15784. /**
  15785. * Updates a depth texture Comparison Mode and Function.
  15786. * If the comparison Function is equal to 0, the mode will be set to none.
  15787. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  15788. * @param texture The texture to set the comparison function for
  15789. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  15790. */
  15791. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  15792. if (this.webGLVersion === 1) {
  15793. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  15794. return;
  15795. }
  15796. var gl = this._gl;
  15797. if (texture.isCube) {
  15798. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15799. if (comparisonFunction === 0) {
  15800. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15801. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15802. }
  15803. else {
  15804. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15805. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15806. }
  15807. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15808. }
  15809. else {
  15810. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15811. if (comparisonFunction === 0) {
  15812. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15813. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15814. }
  15815. else {
  15816. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15817. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15818. }
  15819. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15820. }
  15821. texture._comparisonFunction = comparisonFunction;
  15822. };
  15823. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15824. var width = size.width || size;
  15825. var height = size.height || size;
  15826. internalTexture.baseWidth = width;
  15827. internalTexture.baseHeight = height;
  15828. internalTexture.width = width;
  15829. internalTexture.height = height;
  15830. internalTexture.isReady = true;
  15831. internalTexture.samples = 1;
  15832. internalTexture.generateMipMaps = false;
  15833. internalTexture._generateDepthBuffer = true;
  15834. internalTexture._generateStencilBuffer = generateStencil;
  15835. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15836. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15837. internalTexture._comparisonFunction = comparisonFunction;
  15838. var gl = this._gl;
  15839. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15840. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  15841. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15842. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15843. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15844. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15845. if (comparisonFunction === 0) {
  15846. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15847. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15848. }
  15849. else {
  15850. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15851. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15852. }
  15853. };
  15854. /**
  15855. * Creates a depth stencil texture.
  15856. * This is only available in WebGL 2 or with the depth texture extension available.
  15857. * @param size The size of face edge in the texture.
  15858. * @param options The options defining the texture.
  15859. * @returns The texture
  15860. */
  15861. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15862. if (options.isCube) {
  15863. var width = size.width || size;
  15864. return this._createDepthStencilCubeTexture(width, options);
  15865. }
  15866. else {
  15867. return this._createDepthStencilTexture(size, options);
  15868. }
  15869. };
  15870. /**
  15871. * Creates a depth stencil texture.
  15872. * This is only available in WebGL 2 or with the depth texture extension available.
  15873. * @param size The size of face edge in the texture.
  15874. * @param options The options defining the texture.
  15875. * @returns The texture
  15876. */
  15877. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15878. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15879. if (!this._caps.depthTextureExtension) {
  15880. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15881. return internalTexture;
  15882. }
  15883. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15884. var gl = this._gl;
  15885. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15886. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15887. if (this.webGLVersion > 1) {
  15888. if (internalOptions.generateStencil) {
  15889. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15890. }
  15891. else {
  15892. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15893. }
  15894. }
  15895. else {
  15896. if (internalOptions.generateStencil) {
  15897. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15898. }
  15899. else {
  15900. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15901. }
  15902. }
  15903. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15904. return internalTexture;
  15905. };
  15906. /**
  15907. * Creates a depth stencil cube texture.
  15908. * This is only available in WebGL 2.
  15909. * @param size The size of face edge in the cube texture.
  15910. * @param options The options defining the cube texture.
  15911. * @returns The cube texture
  15912. */
  15913. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15914. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15915. internalTexture.isCube = true;
  15916. if (this.webGLVersion === 1) {
  15917. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15918. return internalTexture;
  15919. }
  15920. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15921. var gl = this._gl;
  15922. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15923. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15924. // Create the depth/stencil buffer
  15925. for (var face = 0; face < 6; face++) {
  15926. if (internalOptions.generateStencil) {
  15927. 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);
  15928. }
  15929. else {
  15930. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15931. }
  15932. }
  15933. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15934. return internalTexture;
  15935. };
  15936. /**
  15937. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15938. * @param renderTarget The render target to set the frame buffer for
  15939. */
  15940. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15941. // Create the framebuffer
  15942. var internalTexture = renderTarget.getInternalTexture();
  15943. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15944. return;
  15945. }
  15946. var gl = this._gl;
  15947. var depthStencilTexture = renderTarget.depthStencilTexture;
  15948. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15949. if (depthStencilTexture.isCube) {
  15950. if (depthStencilTexture._generateStencilBuffer) {
  15951. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15952. }
  15953. else {
  15954. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15955. }
  15956. }
  15957. else {
  15958. if (depthStencilTexture._generateStencilBuffer) {
  15959. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15960. }
  15961. else {
  15962. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15963. }
  15964. }
  15965. this.bindUnboundFramebuffer(null);
  15966. };
  15967. /**
  15968. * Creates a new render target texture
  15969. * @param size defines the size of the texture
  15970. * @param options defines the options used to create the texture
  15971. * @returns a new render target texture stored in an InternalTexture
  15972. */
  15973. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15974. var fullOptions = new RenderTargetCreationOptions();
  15975. if (options !== undefined && typeof options === "object") {
  15976. fullOptions.generateMipMaps = options.generateMipMaps;
  15977. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15978. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15979. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15980. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15981. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15982. }
  15983. else {
  15984. fullOptions.generateMipMaps = options;
  15985. fullOptions.generateDepthBuffer = true;
  15986. fullOptions.generateStencilBuffer = false;
  15987. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15988. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15989. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15990. }
  15991. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15992. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15993. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15994. }
  15995. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15996. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15997. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15998. }
  15999. var gl = this._gl;
  16000. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  16001. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16002. var width = size.width || size;
  16003. var height = size.height || size;
  16004. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  16005. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  16006. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16007. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  16008. }
  16009. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16010. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16011. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16012. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16013. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  16014. // Create the framebuffer
  16015. var currentFrameBuffer = this._currentFramebuffer;
  16016. var framebuffer = gl.createFramebuffer();
  16017. this.bindUnboundFramebuffer(framebuffer);
  16018. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16019. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  16020. if (fullOptions.generateMipMaps) {
  16021. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  16022. }
  16023. // Unbind
  16024. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16025. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16026. this.bindUnboundFramebuffer(currentFrameBuffer);
  16027. texture._framebuffer = framebuffer;
  16028. texture.baseWidth = width;
  16029. texture.baseHeight = height;
  16030. texture.width = width;
  16031. texture.height = height;
  16032. texture.isReady = true;
  16033. texture.samples = 1;
  16034. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  16035. texture.samplingMode = fullOptions.samplingMode;
  16036. texture.type = fullOptions.type;
  16037. texture.format = fullOptions.format;
  16038. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  16039. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  16040. // this.resetTextureCache();
  16041. this._internalTexturesCache.push(texture);
  16042. return texture;
  16043. };
  16044. /**
  16045. * Create a multi render target texture
  16046. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  16047. * @param size defines the size of the texture
  16048. * @param options defines the creation options
  16049. * @returns the cube texture as an InternalTexture
  16050. */
  16051. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  16052. var generateMipMaps = false;
  16053. var generateDepthBuffer = true;
  16054. var generateStencilBuffer = false;
  16055. var generateDepthTexture = false;
  16056. var textureCount = 1;
  16057. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  16058. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  16059. var types = new Array();
  16060. var samplingModes = new Array();
  16061. if (options !== undefined) {
  16062. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  16063. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  16064. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  16065. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  16066. textureCount = options.textureCount || 1;
  16067. if (options.types) {
  16068. types = options.types;
  16069. }
  16070. if (options.samplingModes) {
  16071. samplingModes = options.samplingModes;
  16072. }
  16073. }
  16074. var gl = this._gl;
  16075. // Create the framebuffer
  16076. var framebuffer = gl.createFramebuffer();
  16077. this.bindUnboundFramebuffer(framebuffer);
  16078. var width = size.width || size;
  16079. var height = size.height || size;
  16080. var textures = [];
  16081. var attachments = [];
  16082. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  16083. for (var i = 0; i < textureCount; i++) {
  16084. var samplingMode = samplingModes[i] || defaultSamplingMode;
  16085. var type = types[i] || defaultType;
  16086. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  16087. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  16088. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16089. }
  16090. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  16091. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  16092. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16093. }
  16094. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16095. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  16096. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16097. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  16098. }
  16099. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  16100. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  16101. textures.push(texture);
  16102. attachments.push(attachment);
  16103. gl.activeTexture(gl["TEXTURE" + i]);
  16104. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  16105. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16106. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16107. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16108. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16109. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16110. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16111. if (generateMipMaps) {
  16112. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  16113. }
  16114. // Unbind
  16115. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16116. texture._framebuffer = framebuffer;
  16117. texture._depthStencilBuffer = depthStencilBuffer;
  16118. texture.baseWidth = width;
  16119. texture.baseHeight = height;
  16120. texture.width = width;
  16121. texture.height = height;
  16122. texture.isReady = true;
  16123. texture.samples = 1;
  16124. texture.generateMipMaps = generateMipMaps;
  16125. texture.samplingMode = samplingMode;
  16126. texture.type = type;
  16127. texture._generateDepthBuffer = generateDepthBuffer;
  16128. texture._generateStencilBuffer = generateStencilBuffer;
  16129. texture._attachments = attachments;
  16130. this._internalTexturesCache.push(texture);
  16131. }
  16132. if (generateDepthTexture && this._caps.depthTextureExtension) {
  16133. // Depth texture
  16134. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  16135. gl.activeTexture(gl.TEXTURE0);
  16136. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  16137. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16138. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16139. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16140. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16141. 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);
  16142. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  16143. depthTexture._framebuffer = framebuffer;
  16144. depthTexture.baseWidth = width;
  16145. depthTexture.baseHeight = height;
  16146. depthTexture.width = width;
  16147. depthTexture.height = height;
  16148. depthTexture.isReady = true;
  16149. depthTexture.samples = 1;
  16150. depthTexture.generateMipMaps = generateMipMaps;
  16151. depthTexture.samplingMode = gl.NEAREST;
  16152. depthTexture._generateDepthBuffer = generateDepthBuffer;
  16153. depthTexture._generateStencilBuffer = generateStencilBuffer;
  16154. textures.push(depthTexture);
  16155. this._internalTexturesCache.push(depthTexture);
  16156. }
  16157. gl.drawBuffers(attachments);
  16158. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16159. this.bindUnboundFramebuffer(null);
  16160. this.resetTextureCache();
  16161. return textures;
  16162. };
  16163. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  16164. if (samples === void 0) { samples = 1; }
  16165. var depthStencilBuffer = null;
  16166. var gl = this._gl;
  16167. // Create the depth/stencil buffer
  16168. if (generateStencilBuffer) {
  16169. depthStencilBuffer = gl.createRenderbuffer();
  16170. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  16171. if (samples > 1) {
  16172. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  16173. }
  16174. else {
  16175. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  16176. }
  16177. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  16178. }
  16179. else if (generateDepthBuffer) {
  16180. depthStencilBuffer = gl.createRenderbuffer();
  16181. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  16182. if (samples > 1) {
  16183. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  16184. }
  16185. else {
  16186. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  16187. }
  16188. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  16189. }
  16190. return depthStencilBuffer;
  16191. };
  16192. /**
  16193. * Updates the sample count of a render target texture
  16194. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  16195. * @param texture defines the texture to update
  16196. * @param samples defines the sample count to set
  16197. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  16198. */
  16199. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  16200. if (this.webGLVersion < 2 || !texture) {
  16201. return 1;
  16202. }
  16203. if (texture.samples === samples) {
  16204. return samples;
  16205. }
  16206. var gl = this._gl;
  16207. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  16208. // Dispose previous render buffers
  16209. if (texture._depthStencilBuffer) {
  16210. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16211. texture._depthStencilBuffer = null;
  16212. }
  16213. if (texture._MSAAFramebuffer) {
  16214. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16215. texture._MSAAFramebuffer = null;
  16216. }
  16217. if (texture._MSAARenderBuffer) {
  16218. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16219. texture._MSAARenderBuffer = null;
  16220. }
  16221. if (samples > 1) {
  16222. var framebuffer = gl.createFramebuffer();
  16223. if (!framebuffer) {
  16224. throw new Error("Unable to create multi sampled framebuffer");
  16225. }
  16226. texture._MSAAFramebuffer = framebuffer;
  16227. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  16228. var colorRenderbuffer = gl.createRenderbuffer();
  16229. if (!colorRenderbuffer) {
  16230. throw new Error("Unable to create multi sampled framebuffer");
  16231. }
  16232. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  16233. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  16234. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  16235. texture._MSAARenderBuffer = colorRenderbuffer;
  16236. }
  16237. else {
  16238. this.bindUnboundFramebuffer(texture._framebuffer);
  16239. }
  16240. texture.samples = samples;
  16241. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  16242. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16243. this.bindUnboundFramebuffer(null);
  16244. return samples;
  16245. };
  16246. /**
  16247. * Update the sample count for a given multiple render target texture
  16248. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  16249. * @param textures defines the textures to update
  16250. * @param samples defines the sample count to set
  16251. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  16252. */
  16253. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  16254. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  16255. return 1;
  16256. }
  16257. if (textures[0].samples === samples) {
  16258. return samples;
  16259. }
  16260. var gl = this._gl;
  16261. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  16262. // Dispose previous render buffers
  16263. if (textures[0]._depthStencilBuffer) {
  16264. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  16265. textures[0]._depthStencilBuffer = null;
  16266. }
  16267. if (textures[0]._MSAAFramebuffer) {
  16268. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  16269. textures[0]._MSAAFramebuffer = null;
  16270. }
  16271. for (var i = 0; i < textures.length; i++) {
  16272. if (textures[i]._MSAARenderBuffer) {
  16273. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  16274. textures[i]._MSAARenderBuffer = null;
  16275. }
  16276. }
  16277. if (samples > 1) {
  16278. var framebuffer = gl.createFramebuffer();
  16279. if (!framebuffer) {
  16280. throw new Error("Unable to create multi sampled framebuffer");
  16281. }
  16282. this.bindUnboundFramebuffer(framebuffer);
  16283. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  16284. var attachments = [];
  16285. for (var i = 0; i < textures.length; i++) {
  16286. var texture = textures[i];
  16287. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  16288. var colorRenderbuffer = gl.createRenderbuffer();
  16289. if (!colorRenderbuffer) {
  16290. throw new Error("Unable to create multi sampled framebuffer");
  16291. }
  16292. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  16293. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  16294. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  16295. texture._MSAAFramebuffer = framebuffer;
  16296. texture._MSAARenderBuffer = colorRenderbuffer;
  16297. texture.samples = samples;
  16298. texture._depthStencilBuffer = depthStencilBuffer;
  16299. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16300. attachments.push(attachment);
  16301. }
  16302. gl.drawBuffers(attachments);
  16303. }
  16304. else {
  16305. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  16306. }
  16307. this.bindUnboundFramebuffer(null);
  16308. return samples;
  16309. };
  16310. /** @hidden */
  16311. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  16312. if (faceIndex === void 0) { faceIndex = 0; }
  16313. if (lod === void 0) { lod = 0; }
  16314. var gl = this._gl;
  16315. var target = gl.TEXTURE_2D;
  16316. if (texture.isCube) {
  16317. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16318. }
  16319. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  16320. };
  16321. /** @hidden */
  16322. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  16323. if (faceIndex === void 0) { faceIndex = 0; }
  16324. if (lod === void 0) { lod = 0; }
  16325. var gl = this._gl;
  16326. var textureType = this._getWebGLTextureType(texture.type);
  16327. var format = this._getInternalFormat(texture.format);
  16328. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  16329. this._unpackFlipY(texture.invertY);
  16330. var target = gl.TEXTURE_2D;
  16331. if (texture.isCube) {
  16332. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16333. }
  16334. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  16335. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  16336. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  16337. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  16338. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  16339. };
  16340. /** @hidden */
  16341. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  16342. if (faceIndex === void 0) { faceIndex = 0; }
  16343. if (lod === void 0) { lod = 0; }
  16344. var gl = this._gl;
  16345. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  16346. this._bindTextureDirectly(bindTarget, texture, true);
  16347. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  16348. this._bindTextureDirectly(bindTarget, null, true);
  16349. };
  16350. /** @hidden */
  16351. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  16352. if (faceIndex === void 0) { faceIndex = 0; }
  16353. if (lod === void 0) { lod = 0; }
  16354. var gl = this._gl;
  16355. var textureType = this._getWebGLTextureType(texture.type);
  16356. var format = this._getInternalFormat(texture.format);
  16357. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  16358. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  16359. this._bindTextureDirectly(bindTarget, texture, true);
  16360. this._unpackFlipY(texture.invertY);
  16361. var target = gl.TEXTURE_2D;
  16362. if (texture.isCube) {
  16363. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16364. }
  16365. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  16366. this._bindTextureDirectly(bindTarget, null, true);
  16367. };
  16368. /**
  16369. * Creates a new render target cube texture
  16370. * @param size defines the size of the texture
  16371. * @param options defines the options used to create the texture
  16372. * @returns a new render target cube texture stored in an InternalTexture
  16373. */
  16374. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  16375. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  16376. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  16377. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  16378. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  16379. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16380. }
  16381. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  16382. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  16383. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16384. }
  16385. var gl = this._gl;
  16386. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  16387. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16388. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  16389. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  16390. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16391. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  16392. }
  16393. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16394. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16395. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16396. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16397. for (var face = 0; face < 6; face++) {
  16398. 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);
  16399. }
  16400. // Create the framebuffer
  16401. var framebuffer = gl.createFramebuffer();
  16402. this.bindUnboundFramebuffer(framebuffer);
  16403. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  16404. // MipMaps
  16405. if (fullOptions.generateMipMaps) {
  16406. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16407. }
  16408. // Unbind
  16409. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16410. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16411. this.bindUnboundFramebuffer(null);
  16412. texture._framebuffer = framebuffer;
  16413. texture.width = size;
  16414. texture.height = size;
  16415. texture.isReady = true;
  16416. texture.isCube = true;
  16417. texture.samples = 1;
  16418. texture.generateMipMaps = fullOptions.generateMipMaps;
  16419. texture.samplingMode = fullOptions.samplingMode;
  16420. texture.type = fullOptions.type;
  16421. texture.format = fullOptions.format;
  16422. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  16423. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  16424. this._internalTexturesCache.push(texture);
  16425. return texture;
  16426. };
  16427. /**
  16428. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  16429. * @param rootUrl defines the url where the file to load is located
  16430. * @param scene defines the current scene
  16431. * @param lodScale defines scale to apply to the mip map selection
  16432. * @param lodOffset defines offset to apply to the mip map selection
  16433. * @param onLoad defines an optional callback raised when the texture is loaded
  16434. * @param onError defines an optional callback raised if there is an issue to load the texture
  16435. * @param format defines the format of the data
  16436. * @param forcedExtension defines the extension to use to pick the right loader
  16437. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  16438. * @returns the cube texture as an InternalTexture
  16439. */
  16440. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  16441. var _this = this;
  16442. if (onLoad === void 0) { onLoad = null; }
  16443. if (onError === void 0) { onError = null; }
  16444. if (forcedExtension === void 0) { forcedExtension = null; }
  16445. if (createPolynomials === void 0) { createPolynomials = true; }
  16446. var callback = function (loadData) {
  16447. if (!loadData) {
  16448. if (onLoad) {
  16449. onLoad(null);
  16450. }
  16451. return;
  16452. }
  16453. var texture = loadData.texture;
  16454. if (!createPolynomials) {
  16455. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  16456. }
  16457. else if (loadData.info.sphericalPolynomial) {
  16458. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  16459. }
  16460. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  16461. if (_this._caps.textureLOD) {
  16462. // Do not add extra process if texture lod is supported.
  16463. if (onLoad) {
  16464. onLoad(texture);
  16465. }
  16466. return;
  16467. }
  16468. var mipSlices = 3;
  16469. var gl = _this._gl;
  16470. var width = loadData.width;
  16471. if (!width) {
  16472. return;
  16473. }
  16474. var textures = [];
  16475. for (var i = 0; i < mipSlices; i++) {
  16476. //compute LOD from even spacing in smoothness (matching shader calculation)
  16477. var smoothness = i / (mipSlices - 1);
  16478. var roughness = 1 - smoothness;
  16479. var minLODIndex = lodOffset; // roughness = 0
  16480. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  16481. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  16482. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  16483. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  16484. glTextureFromLod.type = texture.type;
  16485. glTextureFromLod.format = texture.format;
  16486. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  16487. glTextureFromLod.height = glTextureFromLod.width;
  16488. glTextureFromLod.isCube = true;
  16489. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  16490. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  16491. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  16492. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16493. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16494. if (loadData.isDDS) {
  16495. var info = loadData.info;
  16496. var data = loadData.data;
  16497. _this._unpackFlipY(info.isCompressed);
  16498. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  16499. }
  16500. else {
  16501. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  16502. }
  16503. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16504. // Wrap in a base texture for easy binding.
  16505. var lodTexture = new BABYLON.BaseTexture(scene);
  16506. lodTexture.isCube = true;
  16507. lodTexture._texture = glTextureFromLod;
  16508. glTextureFromLod.isReady = true;
  16509. textures.push(lodTexture);
  16510. }
  16511. texture._lodTextureHigh = textures[2];
  16512. texture._lodTextureMid = textures[1];
  16513. texture._lodTextureLow = textures[0];
  16514. if (onLoad) {
  16515. onLoad(texture);
  16516. }
  16517. };
  16518. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  16519. };
  16520. /**
  16521. * Creates a cube texture
  16522. * @param rootUrl defines the url where the files to load is located
  16523. * @param scene defines the current scene
  16524. * @param files defines the list of files to load (1 per face)
  16525. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  16526. * @param onLoad defines an optional callback raised when the texture is loaded
  16527. * @param onError defines an optional callback raised if there is an issue to load the texture
  16528. * @param format defines the format of the data
  16529. * @param forcedExtension defines the extension to use to pick the right loader
  16530. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  16531. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  16532. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  16533. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  16534. * @returns the cube texture as an InternalTexture
  16535. */
  16536. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  16537. var _this = this;
  16538. if (onLoad === void 0) { onLoad = null; }
  16539. if (onError === void 0) { onError = null; }
  16540. if (forcedExtension === void 0) { forcedExtension = null; }
  16541. if (createPolynomials === void 0) { createPolynomials = false; }
  16542. if (lodScale === void 0) { lodScale = 0; }
  16543. if (lodOffset === void 0) { lodOffset = 0; }
  16544. if (fallback === void 0) { fallback = null; }
  16545. var gl = this._gl;
  16546. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  16547. texture.isCube = true;
  16548. texture.url = rootUrl;
  16549. texture.generateMipMaps = !noMipmap;
  16550. texture._lodGenerationScale = lodScale;
  16551. texture._lodGenerationOffset = lodOffset;
  16552. if (!this._doNotHandleContextLost) {
  16553. texture._extension = forcedExtension;
  16554. texture._files = files;
  16555. }
  16556. var lastDot = rootUrl.lastIndexOf('.');
  16557. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  16558. var loader = null;
  16559. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  16560. var availableLoader = _a[_i];
  16561. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  16562. loader = availableLoader;
  16563. break;
  16564. }
  16565. }
  16566. var onInternalError = function (request, exception) {
  16567. if (loader) {
  16568. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  16569. if (fallbackUrl) {
  16570. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  16571. }
  16572. }
  16573. if (onError && request) {
  16574. onError(request.status + " " + request.statusText, exception);
  16575. }
  16576. };
  16577. if (loader) {
  16578. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  16579. var onloaddata = function (data) {
  16580. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16581. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  16582. };
  16583. if (files && files.length === 6) {
  16584. if (loader.supportCascades) {
  16585. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  16586. }
  16587. else if (onError) {
  16588. onError("Textures type does not support cascades.");
  16589. }
  16590. }
  16591. else {
  16592. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  16593. }
  16594. }
  16595. else {
  16596. if (!files) {
  16597. throw new Error("Cannot load cubemap because files were not defined");
  16598. }
  16599. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  16600. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  16601. var height = width;
  16602. _this._prepareWorkingCanvas();
  16603. if (!_this._workingCanvas || !_this._workingContext) {
  16604. return;
  16605. }
  16606. _this._workingCanvas.width = width;
  16607. _this._workingCanvas.height = height;
  16608. var faces = [
  16609. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  16610. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  16611. ];
  16612. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16613. _this._unpackFlipY(false);
  16614. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  16615. for (var index = 0; index < faces.length; index++) {
  16616. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  16617. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  16618. }
  16619. if (!noMipmap) {
  16620. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16621. }
  16622. _this._setCubeMapTextureParams(!noMipmap);
  16623. texture.width = width;
  16624. texture.height = height;
  16625. texture.isReady = true;
  16626. if (format) {
  16627. texture.format = format;
  16628. }
  16629. texture.onLoadedObservable.notifyObservers(texture);
  16630. texture.onLoadedObservable.clear();
  16631. if (onLoad) {
  16632. onLoad();
  16633. }
  16634. }, files, onError);
  16635. }
  16636. this._internalTexturesCache.push(texture);
  16637. return texture;
  16638. };
  16639. /**
  16640. * @hidden
  16641. */
  16642. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  16643. var gl = this._gl;
  16644. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  16645. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  16646. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16647. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16648. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16649. // this.resetTextureCache();
  16650. };
  16651. /**
  16652. * Update a raw cube texture
  16653. * @param texture defines the texture to udpdate
  16654. * @param data defines the data to store
  16655. * @param format defines the data format
  16656. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  16657. * @param invertY defines if data must be stored with Y axis inverted
  16658. * @param compression defines the compression used (null by default)
  16659. * @param level defines which level of the texture to update
  16660. */
  16661. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  16662. if (compression === void 0) { compression = null; }
  16663. if (level === void 0) { level = 0; }
  16664. texture._bufferViewArray = data;
  16665. texture.format = format;
  16666. texture.type = type;
  16667. texture.invertY = invertY;
  16668. texture._compression = compression;
  16669. var gl = this._gl;
  16670. var textureType = this._getWebGLTextureType(type);
  16671. var internalFormat = this._getInternalFormat(format);
  16672. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  16673. var needConversion = false;
  16674. if (internalFormat === gl.RGB) {
  16675. internalFormat = gl.RGBA;
  16676. needConversion = true;
  16677. }
  16678. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16679. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16680. if (texture.width % 4 !== 0) {
  16681. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  16682. }
  16683. // Data are known to be in +X +Y +Z -X -Y -Z
  16684. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16685. var faceData = data[faceIndex];
  16686. if (compression) {
  16687. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  16688. }
  16689. else {
  16690. if (needConversion) {
  16691. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  16692. }
  16693. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  16694. }
  16695. }
  16696. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16697. if (isPot && texture.generateMipMaps && level === 0) {
  16698. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16699. }
  16700. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16701. // this.resetTextureCache();
  16702. texture.isReady = true;
  16703. };
  16704. /**
  16705. * Creates a new raw cube texture
  16706. * @param data defines the array of data to use to create each face
  16707. * @param size defines the size of the textures
  16708. * @param format defines the format of the data
  16709. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16710. * @param generateMipMaps defines if the engine should generate the mip levels
  16711. * @param invertY defines if data must be stored with Y axis inverted
  16712. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16713. * @param compression defines the compression used (null by default)
  16714. * @returns the cube texture as an InternalTexture
  16715. */
  16716. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  16717. if (compression === void 0) { compression = null; }
  16718. var gl = this._gl;
  16719. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  16720. texture.isCube = true;
  16721. texture.format = format;
  16722. texture.type = type;
  16723. if (!this._doNotHandleContextLost) {
  16724. texture._bufferViewArray = data;
  16725. }
  16726. var textureType = this._getWebGLTextureType(type);
  16727. var internalFormat = this._getInternalFormat(format);
  16728. if (internalFormat === gl.RGB) {
  16729. internalFormat = gl.RGBA;
  16730. }
  16731. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  16732. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  16733. generateMipMaps = false;
  16734. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16735. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  16736. }
  16737. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  16738. generateMipMaps = false;
  16739. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16740. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  16741. }
  16742. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  16743. generateMipMaps = false;
  16744. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  16745. }
  16746. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  16747. generateMipMaps = false;
  16748. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  16749. }
  16750. var width = size;
  16751. var height = width;
  16752. texture.width = width;
  16753. texture.height = height;
  16754. // Double check on POT to generate Mips.
  16755. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16756. if (!isPot) {
  16757. generateMipMaps = false;
  16758. }
  16759. // Upload data if needed. The texture won't be ready until then.
  16760. if (data) {
  16761. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  16762. }
  16763. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  16764. // Filters
  16765. if (data && generateMipMaps) {
  16766. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16767. }
  16768. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16769. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16770. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16771. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16772. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16773. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16774. texture.generateMipMaps = generateMipMaps;
  16775. return texture;
  16776. };
  16777. /**
  16778. * Creates a new raw cube texture from a specified url
  16779. * @param url defines the url where the data is located
  16780. * @param scene defines the current scene
  16781. * @param size defines the size of the textures
  16782. * @param format defines the format of the data
  16783. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16784. * @param noMipmap defines if the engine should avoid generating the mip levels
  16785. * @param callback defines a callback used to extract texture data from loaded data
  16786. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  16787. * @param onLoad defines a callback called when texture is loaded
  16788. * @param onError defines a callback called if there is an error
  16789. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16790. * @param invertY defines if data must be stored with Y axis inverted
  16791. * @returns the cube texture as an InternalTexture
  16792. */
  16793. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  16794. var _this = this;
  16795. if (onLoad === void 0) { onLoad = null; }
  16796. if (onError === void 0) { onError = null; }
  16797. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16798. if (invertY === void 0) { invertY = false; }
  16799. var gl = this._gl;
  16800. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16801. scene._addPendingData(texture);
  16802. texture.url = url;
  16803. this._internalTexturesCache.push(texture);
  16804. var onerror = function (request, exception) {
  16805. scene._removePendingData(texture);
  16806. if (onError && request) {
  16807. onError(request.status + " " + request.statusText, exception);
  16808. }
  16809. };
  16810. var internalCallback = function (data) {
  16811. var width = texture.width;
  16812. var faceDataArrays = callback(data);
  16813. if (!faceDataArrays) {
  16814. return;
  16815. }
  16816. if (mipmapGenerator) {
  16817. var textureType = _this._getWebGLTextureType(type);
  16818. var internalFormat = _this._getInternalFormat(format);
  16819. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16820. var needConversion = false;
  16821. if (internalFormat === gl.RGB) {
  16822. internalFormat = gl.RGBA;
  16823. needConversion = true;
  16824. }
  16825. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16826. _this._unpackFlipY(false);
  16827. var mipData = mipmapGenerator(faceDataArrays);
  16828. for (var level = 0; level < mipData.length; level++) {
  16829. var mipSize = width >> level;
  16830. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16831. var mipFaceData = mipData[level][faceIndex];
  16832. if (needConversion) {
  16833. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16834. }
  16835. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16836. }
  16837. }
  16838. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16839. }
  16840. else {
  16841. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16842. }
  16843. texture.isReady = true;
  16844. // this.resetTextureCache();
  16845. scene._removePendingData(texture);
  16846. if (onLoad) {
  16847. onLoad();
  16848. }
  16849. };
  16850. this._loadFile(url, function (data) {
  16851. internalCallback(data);
  16852. }, undefined, scene.database, true, onerror);
  16853. return texture;
  16854. };
  16855. /**
  16856. * Update a raw 3D texture
  16857. * @param texture defines the texture to update
  16858. * @param data defines the data to store
  16859. * @param format defines the data format
  16860. * @param invertY defines if data must be stored with Y axis inverted
  16861. * @param compression defines the used compression (can be null)
  16862. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16863. */
  16864. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16865. if (compression === void 0) { compression = null; }
  16866. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16867. var internalType = this._getWebGLTextureType(textureType);
  16868. var internalFormat = this._getInternalFormat(format);
  16869. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16870. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16871. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16872. if (!this._doNotHandleContextLost) {
  16873. texture._bufferView = data;
  16874. texture.format = format;
  16875. texture.invertY = invertY;
  16876. texture._compression = compression;
  16877. }
  16878. if (texture.width % 4 !== 0) {
  16879. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16880. }
  16881. if (compression && data) {
  16882. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16883. }
  16884. else {
  16885. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16886. }
  16887. if (texture.generateMipMaps) {
  16888. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16889. }
  16890. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16891. // this.resetTextureCache();
  16892. texture.isReady = true;
  16893. };
  16894. /**
  16895. * Creates a new raw 3D texture
  16896. * @param data defines the data used to create the texture
  16897. * @param width defines the width of the texture
  16898. * @param height defines the height of the texture
  16899. * @param depth defines the depth of the texture
  16900. * @param format defines the format of the texture
  16901. * @param generateMipMaps defines if the engine must generate mip levels
  16902. * @param invertY defines if data must be stored with Y axis inverted
  16903. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16904. * @param compression defines the compressed used (can be null)
  16905. * @param textureType defines the compressed used (can be null)
  16906. * @returns a new raw 3D texture (stored in an InternalTexture)
  16907. */
  16908. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16909. if (compression === void 0) { compression = null; }
  16910. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16911. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16912. texture.baseWidth = width;
  16913. texture.baseHeight = height;
  16914. texture.baseDepth = depth;
  16915. texture.width = width;
  16916. texture.height = height;
  16917. texture.depth = depth;
  16918. texture.format = format;
  16919. texture.type = textureType;
  16920. texture.generateMipMaps = generateMipMaps;
  16921. texture.samplingMode = samplingMode;
  16922. texture.is3D = true;
  16923. if (!this._doNotHandleContextLost) {
  16924. texture._bufferView = data;
  16925. }
  16926. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16927. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16928. // Filters
  16929. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16930. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16931. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16932. if (generateMipMaps) {
  16933. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16934. }
  16935. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16936. this._internalTexturesCache.push(texture);
  16937. return texture;
  16938. };
  16939. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16940. var gl = this._gl;
  16941. if (!gl) {
  16942. return;
  16943. }
  16944. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  16945. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16946. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16947. if (!noMipmap && !isCompressed) {
  16948. gl.generateMipmap(gl.TEXTURE_2D);
  16949. }
  16950. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16951. // this.resetTextureCache();
  16952. if (scene) {
  16953. scene._removePendingData(texture);
  16954. }
  16955. texture.onLoadedObservable.notifyObservers(texture);
  16956. texture.onLoadedObservable.clear();
  16957. };
  16958. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16959. var _this = this;
  16960. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16961. var maxTextureSize = this.getCaps().maxTextureSize;
  16962. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16963. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16964. var gl = this._gl;
  16965. if (!gl) {
  16966. return;
  16967. }
  16968. if (!texture._webGLTexture) {
  16969. // this.resetTextureCache();
  16970. if (scene) {
  16971. scene._removePendingData(texture);
  16972. }
  16973. return;
  16974. }
  16975. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16976. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16977. texture.baseWidth = width;
  16978. texture.baseHeight = height;
  16979. texture.width = potWidth;
  16980. texture.height = potHeight;
  16981. texture.isReady = true;
  16982. if (processFunction(potWidth, potHeight, function () {
  16983. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16984. })) {
  16985. // Returning as texture needs extra async steps
  16986. return;
  16987. }
  16988. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16989. };
  16990. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16991. // Create new RGBA data container.
  16992. var rgbaData;
  16993. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16994. rgbaData = new Float32Array(width * height * 4);
  16995. }
  16996. else {
  16997. rgbaData = new Uint32Array(width * height * 4);
  16998. }
  16999. // Convert each pixel.
  17000. for (var x = 0; x < width; x++) {
  17001. for (var y = 0; y < height; y++) {
  17002. var index = (y * width + x) * 3;
  17003. var newIndex = (y * width + x) * 4;
  17004. // Map Old Value to new value.
  17005. rgbaData[newIndex + 0] = rgbData[index + 0];
  17006. rgbaData[newIndex + 1] = rgbData[index + 1];
  17007. rgbaData[newIndex + 2] = rgbData[index + 2];
  17008. // Add fully opaque alpha channel.
  17009. rgbaData[newIndex + 3] = 1;
  17010. }
  17011. }
  17012. return rgbaData;
  17013. };
  17014. /** @hidden */
  17015. Engine.prototype._releaseFramebufferObjects = function (texture) {
  17016. var gl = this._gl;
  17017. if (texture._framebuffer) {
  17018. gl.deleteFramebuffer(texture._framebuffer);
  17019. texture._framebuffer = null;
  17020. }
  17021. if (texture._depthStencilBuffer) {
  17022. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  17023. texture._depthStencilBuffer = null;
  17024. }
  17025. if (texture._MSAAFramebuffer) {
  17026. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  17027. texture._MSAAFramebuffer = null;
  17028. }
  17029. if (texture._MSAARenderBuffer) {
  17030. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  17031. texture._MSAARenderBuffer = null;
  17032. }
  17033. };
  17034. /** @hidden */
  17035. Engine.prototype._releaseTexture = function (texture) {
  17036. var gl = this._gl;
  17037. this._releaseFramebufferObjects(texture);
  17038. gl.deleteTexture(texture._webGLTexture);
  17039. // Unbind channels
  17040. this.unbindAllTextures();
  17041. var index = this._internalTexturesCache.indexOf(texture);
  17042. if (index !== -1) {
  17043. this._internalTexturesCache.splice(index, 1);
  17044. }
  17045. // Integrated fixed lod samplers.
  17046. if (texture._lodTextureHigh) {
  17047. texture._lodTextureHigh.dispose();
  17048. }
  17049. if (texture._lodTextureMid) {
  17050. texture._lodTextureMid.dispose();
  17051. }
  17052. if (texture._lodTextureLow) {
  17053. texture._lodTextureLow.dispose();
  17054. }
  17055. // Set output texture of post process to null if the texture has been released/disposed
  17056. this.scenes.forEach(function (scene) {
  17057. scene.postProcesses.forEach(function (postProcess) {
  17058. if (postProcess._outputTexture == texture) {
  17059. postProcess._outputTexture = null;
  17060. }
  17061. });
  17062. scene.cameras.forEach(function (camera) {
  17063. camera._postProcesses.forEach(function (postProcess) {
  17064. if (postProcess) {
  17065. if (postProcess._outputTexture == texture) {
  17066. postProcess._outputTexture = null;
  17067. }
  17068. }
  17069. });
  17070. });
  17071. });
  17072. };
  17073. Engine.prototype.setProgram = function (program) {
  17074. if (this._currentProgram !== program) {
  17075. this._gl.useProgram(program);
  17076. this._currentProgram = program;
  17077. }
  17078. };
  17079. /**
  17080. * Binds an effect to the webGL context
  17081. * @param effect defines the effect to bind
  17082. */
  17083. Engine.prototype.bindSamplers = function (effect) {
  17084. this.setProgram(effect.getProgram());
  17085. var samplers = effect.getSamplers();
  17086. for (var index = 0; index < samplers.length; index++) {
  17087. var uniform = effect.getUniform(samplers[index]);
  17088. if (uniform) {
  17089. this._boundUniforms[index] = uniform;
  17090. }
  17091. }
  17092. this._currentEffect = null;
  17093. };
  17094. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  17095. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  17096. return;
  17097. }
  17098. // Remove
  17099. this._linkTrackers(internalTexture.previous, internalTexture.next);
  17100. // Bind last to it
  17101. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  17102. // Bind to dummy
  17103. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  17104. };
  17105. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  17106. if (!internalTexture) {
  17107. return -1;
  17108. }
  17109. internalTexture._initialSlot = channel;
  17110. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  17111. if (channel !== internalTexture._designatedSlot) {
  17112. this._textureCollisions.addCount(1, false);
  17113. }
  17114. }
  17115. else {
  17116. if (channel !== internalTexture._designatedSlot) {
  17117. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  17118. return internalTexture._designatedSlot;
  17119. }
  17120. else {
  17121. // No slot for this texture, let's pick a new one (if we find a free slot)
  17122. if (this._nextFreeTextureSlots.length) {
  17123. return this._nextFreeTextureSlots[0];
  17124. }
  17125. // We need to recycle the oldest bound texture, sorry.
  17126. this._textureCollisions.addCount(1, false);
  17127. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  17128. }
  17129. }
  17130. }
  17131. return channel;
  17132. };
  17133. Engine.prototype._linkTrackers = function (previous, next) {
  17134. previous.next = next;
  17135. next.previous = previous;
  17136. };
  17137. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  17138. var currentSlot = internalTexture._designatedSlot;
  17139. if (currentSlot === -1) {
  17140. return -1;
  17141. }
  17142. internalTexture._designatedSlot = -1;
  17143. if (this.disableTextureBindingOptimization) {
  17144. return -1;
  17145. }
  17146. // Remove from bound list
  17147. this._linkTrackers(internalTexture.previous, internalTexture.next);
  17148. // Free the slot
  17149. this._boundTexturesCache[currentSlot] = null;
  17150. this._nextFreeTextureSlots.push(currentSlot);
  17151. return currentSlot;
  17152. };
  17153. Engine.prototype._activateCurrentTexture = function () {
  17154. if (this._currentTextureChannel !== this._activeChannel) {
  17155. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  17156. this._currentTextureChannel = this._activeChannel;
  17157. }
  17158. };
  17159. /** @hidden */
  17160. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  17161. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  17162. if (force === void 0) { force = false; }
  17163. var wasPreviouslyBound = false;
  17164. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  17165. this._activeChannel = texture._designatedSlot;
  17166. }
  17167. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  17168. var isTextureForRendering = texture && texture._initialSlot > -1;
  17169. if (currentTextureBound !== texture || force) {
  17170. if (currentTextureBound) {
  17171. this._removeDesignatedSlot(currentTextureBound);
  17172. }
  17173. this._activateCurrentTexture();
  17174. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  17175. this._boundTexturesCache[this._activeChannel] = texture;
  17176. if (texture) {
  17177. if (!this.disableTextureBindingOptimization) {
  17178. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  17179. if (slotIndex > -1) {
  17180. this._nextFreeTextureSlots.splice(slotIndex, 1);
  17181. }
  17182. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  17183. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  17184. }
  17185. texture._designatedSlot = this._activeChannel;
  17186. }
  17187. }
  17188. else if (forTextureDataUpdate) {
  17189. wasPreviouslyBound = true;
  17190. this._activateCurrentTexture();
  17191. }
  17192. if (isTextureForRendering && !forTextureDataUpdate) {
  17193. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  17194. }
  17195. return wasPreviouslyBound;
  17196. };
  17197. /** @hidden */
  17198. Engine.prototype._bindTexture = function (channel, texture) {
  17199. if (channel < 0) {
  17200. return;
  17201. }
  17202. if (texture) {
  17203. channel = this._getCorrectTextureChannel(channel, texture);
  17204. }
  17205. this._activeChannel = channel;
  17206. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  17207. };
  17208. /**
  17209. * Sets a texture to the webGL context from a postprocess
  17210. * @param channel defines the channel to use
  17211. * @param postProcess defines the source postprocess
  17212. */
  17213. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  17214. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  17215. };
  17216. /**
  17217. * Binds the output of the passed in post process to the texture channel specified
  17218. * @param channel The channel the texture should be bound to
  17219. * @param postProcess The post process which's output should be bound
  17220. */
  17221. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  17222. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  17223. };
  17224. /**
  17225. * Unbind all textures from the webGL context
  17226. */
  17227. Engine.prototype.unbindAllTextures = function () {
  17228. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  17229. this._activeChannel = channel;
  17230. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  17231. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  17232. if (this.webGLVersion > 1) {
  17233. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  17234. }
  17235. }
  17236. };
  17237. /**
  17238. * Sets a texture to the according uniform.
  17239. * @param channel The texture channel
  17240. * @param uniform The uniform to set
  17241. * @param texture The texture to apply
  17242. */
  17243. Engine.prototype.setTexture = function (channel, uniform, texture) {
  17244. if (channel < 0) {
  17245. return;
  17246. }
  17247. if (uniform) {
  17248. this._boundUniforms[channel] = uniform;
  17249. }
  17250. this._setTexture(channel, texture);
  17251. };
  17252. /**
  17253. * Sets a depth stencil texture from a render target to the according uniform.
  17254. * @param channel The texture channel
  17255. * @param uniform The uniform to set
  17256. * @param texture The render target texture containing the depth stencil texture to apply
  17257. */
  17258. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  17259. if (channel < 0) {
  17260. return;
  17261. }
  17262. if (uniform) {
  17263. this._boundUniforms[channel] = uniform;
  17264. }
  17265. if (!texture || !texture.depthStencilTexture) {
  17266. this._setTexture(channel, null);
  17267. }
  17268. else {
  17269. this._setTexture(channel, texture, false, true);
  17270. }
  17271. };
  17272. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  17273. var uniform = this._boundUniforms[sourceSlot];
  17274. if (uniform._currentState === destination) {
  17275. return;
  17276. }
  17277. this._gl.uniform1i(uniform, destination);
  17278. uniform._currentState = destination;
  17279. };
  17280. Engine.prototype._getTextureWrapMode = function (mode) {
  17281. switch (mode) {
  17282. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  17283. return this._gl.REPEAT;
  17284. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  17285. return this._gl.CLAMP_TO_EDGE;
  17286. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  17287. return this._gl.MIRRORED_REPEAT;
  17288. }
  17289. return this._gl.REPEAT;
  17290. };
  17291. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  17292. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  17293. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  17294. // Not ready?
  17295. if (!texture) {
  17296. if (this._boundTexturesCache[channel] != null) {
  17297. this._activeChannel = channel;
  17298. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  17299. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  17300. if (this.webGLVersion > 1) {
  17301. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  17302. }
  17303. }
  17304. return false;
  17305. }
  17306. // Video
  17307. if (texture.video) {
  17308. this._activeChannel = channel;
  17309. texture.update();
  17310. }
  17311. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  17312. texture.delayLoad();
  17313. return false;
  17314. }
  17315. var internalTexture;
  17316. if (depthStencilTexture) {
  17317. internalTexture = texture.depthStencilTexture;
  17318. }
  17319. else if (texture.isReady()) {
  17320. internalTexture = texture.getInternalTexture();
  17321. }
  17322. else if (texture.isCube) {
  17323. internalTexture = this.emptyCubeTexture;
  17324. }
  17325. else if (texture.is3D) {
  17326. internalTexture = this.emptyTexture3D;
  17327. }
  17328. else {
  17329. internalTexture = this.emptyTexture;
  17330. }
  17331. if (!isPartOfTextureArray) {
  17332. channel = this._getCorrectTextureChannel(channel, internalTexture);
  17333. }
  17334. var needToBind = true;
  17335. if (this._boundTexturesCache[channel] === internalTexture) {
  17336. this._moveBoundTextureOnTop(internalTexture);
  17337. if (!isPartOfTextureArray) {
  17338. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  17339. }
  17340. needToBind = false;
  17341. }
  17342. this._activeChannel = channel;
  17343. if (internalTexture && internalTexture.is3D) {
  17344. if (needToBind) {
  17345. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  17346. }
  17347. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  17348. internalTexture._cachedWrapU = texture.wrapU;
  17349. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  17350. }
  17351. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  17352. internalTexture._cachedWrapV = texture.wrapV;
  17353. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  17354. }
  17355. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  17356. internalTexture._cachedWrapR = texture.wrapR;
  17357. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  17358. }
  17359. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  17360. }
  17361. else if (internalTexture && internalTexture.isCube) {
  17362. if (needToBind) {
  17363. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  17364. }
  17365. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  17366. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  17367. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  17368. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  17369. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  17370. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  17371. }
  17372. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  17373. }
  17374. else {
  17375. if (needToBind) {
  17376. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  17377. }
  17378. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  17379. internalTexture._cachedWrapU = texture.wrapU;
  17380. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  17381. }
  17382. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  17383. internalTexture._cachedWrapV = texture.wrapV;
  17384. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  17385. }
  17386. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  17387. }
  17388. return true;
  17389. };
  17390. /**
  17391. * Sets an array of texture to the webGL context
  17392. * @param channel defines the channel where the texture array must be set
  17393. * @param uniform defines the associated uniform location
  17394. * @param textures defines the array of textures to bind
  17395. */
  17396. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  17397. if (channel < 0 || !uniform) {
  17398. return;
  17399. }
  17400. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  17401. this._textureUnits = new Int32Array(textures.length);
  17402. }
  17403. for (var i = 0; i < textures.length; i++) {
  17404. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  17405. }
  17406. this._gl.uniform1iv(uniform, this._textureUnits);
  17407. for (var index = 0; index < textures.length; index++) {
  17408. this._setTexture(this._textureUnits[index], textures[index], true);
  17409. }
  17410. };
  17411. /** @hidden */
  17412. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  17413. var internalTexture = texture.getInternalTexture();
  17414. if (!internalTexture) {
  17415. return;
  17416. }
  17417. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  17418. var value = texture.anisotropicFilteringLevel;
  17419. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  17420. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  17421. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  17422. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  17423. }
  17424. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  17425. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  17426. internalTexture._cachedAnisotropicFilteringLevel = value;
  17427. }
  17428. };
  17429. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  17430. this._bindTextureDirectly(target, texture, true, true);
  17431. this._gl.texParameterf(target, parameter, value);
  17432. };
  17433. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  17434. if (texture) {
  17435. this._bindTextureDirectly(target, texture, true, true);
  17436. }
  17437. this._gl.texParameteri(target, parameter, value);
  17438. };
  17439. /**
  17440. * Reads pixels from the current frame buffer. Please note that this function can be slow
  17441. * @param x defines the x coordinate of the rectangle where pixels must be read
  17442. * @param y defines the y coordinate of the rectangle where pixels must be read
  17443. * @param width defines the width of the rectangle where pixels must be read
  17444. * @param height defines the height of the rectangle where pixels must be read
  17445. * @returns a Uint8Array containing RGBA colors
  17446. */
  17447. Engine.prototype.readPixels = function (x, y, width, height) {
  17448. var data = new Uint8Array(height * width * 4);
  17449. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  17450. return data;
  17451. };
  17452. /**
  17453. * Add an externaly attached data from its key.
  17454. * This method call will fail and return false, if such key already exists.
  17455. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  17456. * @param key the unique key that identifies the data
  17457. * @param data the data object to associate to the key for this Engine instance
  17458. * @return true if no such key were already present and the data was added successfully, false otherwise
  17459. */
  17460. Engine.prototype.addExternalData = function (key, data) {
  17461. if (!this._externalData) {
  17462. this._externalData = new BABYLON.StringDictionary();
  17463. }
  17464. return this._externalData.add(key, data);
  17465. };
  17466. /**
  17467. * Get an externaly attached data from its key
  17468. * @param key the unique key that identifies the data
  17469. * @return the associated data, if present (can be null), or undefined if not present
  17470. */
  17471. Engine.prototype.getExternalData = function (key) {
  17472. if (!this._externalData) {
  17473. this._externalData = new BABYLON.StringDictionary();
  17474. }
  17475. return this._externalData.get(key);
  17476. };
  17477. /**
  17478. * Get an externaly attached data from its key, create it using a factory if it's not already present
  17479. * @param key the unique key that identifies the data
  17480. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  17481. * @return the associated data, can be null if the factory returned null.
  17482. */
  17483. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  17484. if (!this._externalData) {
  17485. this._externalData = new BABYLON.StringDictionary();
  17486. }
  17487. return this._externalData.getOrAddWithFactory(key, factory);
  17488. };
  17489. /**
  17490. * Remove an externaly attached data from the Engine instance
  17491. * @param key the unique key that identifies the data
  17492. * @return true if the data was successfully removed, false if it doesn't exist
  17493. */
  17494. Engine.prototype.removeExternalData = function (key) {
  17495. if (!this._externalData) {
  17496. this._externalData = new BABYLON.StringDictionary();
  17497. }
  17498. return this._externalData.remove(key);
  17499. };
  17500. /**
  17501. * Unbind all vertex attributes from the webGL context
  17502. */
  17503. Engine.prototype.unbindAllAttributes = function () {
  17504. if (this._mustWipeVertexAttributes) {
  17505. this._mustWipeVertexAttributes = false;
  17506. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  17507. this._gl.disableVertexAttribArray(i);
  17508. this._vertexAttribArraysEnabled[i] = false;
  17509. this._currentBufferPointers[i].active = false;
  17510. }
  17511. return;
  17512. }
  17513. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  17514. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  17515. continue;
  17516. }
  17517. this._gl.disableVertexAttribArray(i);
  17518. this._vertexAttribArraysEnabled[i] = false;
  17519. this._currentBufferPointers[i].active = false;
  17520. }
  17521. };
  17522. /**
  17523. * 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
  17524. */
  17525. Engine.prototype.releaseEffects = function () {
  17526. for (var name in this._compiledEffects) {
  17527. this._deleteProgram(this._compiledEffects[name]._program);
  17528. }
  17529. this._compiledEffects = {};
  17530. };
  17531. /**
  17532. * Dispose and release all associated resources
  17533. */
  17534. Engine.prototype.dispose = function () {
  17535. this.hideLoadingUI();
  17536. this.stopRenderLoop();
  17537. // Release postProcesses
  17538. while (this.postProcesses.length) {
  17539. this.postProcesses[0].dispose();
  17540. }
  17541. // Empty texture
  17542. if (this._emptyTexture) {
  17543. this._releaseTexture(this._emptyTexture);
  17544. this._emptyTexture = null;
  17545. }
  17546. if (this._emptyCubeTexture) {
  17547. this._releaseTexture(this._emptyCubeTexture);
  17548. this._emptyCubeTexture = null;
  17549. }
  17550. // Rescale PP
  17551. if (this._rescalePostProcess) {
  17552. this._rescalePostProcess.dispose();
  17553. }
  17554. // Release scenes
  17555. while (this.scenes.length) {
  17556. this.scenes[0].dispose();
  17557. }
  17558. // Release audio engine
  17559. if (Engine.Instances.length === 1 && Engine.audioEngine) {
  17560. Engine.audioEngine.dispose();
  17561. }
  17562. // Release effects
  17563. this.releaseEffects();
  17564. // Unbind
  17565. this.unbindAllAttributes();
  17566. this._boundUniforms = [];
  17567. if (this._dummyFramebuffer) {
  17568. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  17569. }
  17570. //WebVR
  17571. this.disableVR();
  17572. // Events
  17573. if (BABYLON.Tools.IsWindowObjectExist()) {
  17574. window.removeEventListener("blur", this._onBlur);
  17575. window.removeEventListener("focus", this._onFocus);
  17576. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  17577. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  17578. if (this._renderingCanvas) {
  17579. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  17580. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  17581. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  17582. if (!this._doNotHandleContextLost) {
  17583. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  17584. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  17585. }
  17586. }
  17587. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  17588. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  17589. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  17590. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  17591. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  17592. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  17593. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  17594. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  17595. if (this._onVrDisplayConnect) {
  17596. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  17597. if (this._onVrDisplayDisconnect) {
  17598. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  17599. }
  17600. if (this._onVrDisplayPresentChange) {
  17601. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  17602. }
  17603. this._onVrDisplayConnect = null;
  17604. this._onVrDisplayDisconnect = null;
  17605. }
  17606. }
  17607. // Remove from Instances
  17608. var index = Engine.Instances.indexOf(this);
  17609. if (index >= 0) {
  17610. Engine.Instances.splice(index, 1);
  17611. }
  17612. this._workingCanvas = null;
  17613. this._workingContext = null;
  17614. this._currentBufferPointers = [];
  17615. this._renderingCanvas = null;
  17616. this._currentProgram = null;
  17617. this._bindedRenderFunction = null;
  17618. this.onResizeObservable.clear();
  17619. this.onCanvasBlurObservable.clear();
  17620. this.onCanvasFocusObservable.clear();
  17621. this.onCanvasPointerOutObservable.clear();
  17622. this.onBeginFrameObservable.clear();
  17623. this.onEndFrameObservable.clear();
  17624. BABYLON.Effect.ResetCache();
  17625. // Abort active requests
  17626. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  17627. var request = _a[_i];
  17628. request.abort();
  17629. }
  17630. };
  17631. // Loading screen
  17632. /**
  17633. * Display the loading screen
  17634. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17635. */
  17636. Engine.prototype.displayLoadingUI = function () {
  17637. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17638. return;
  17639. }
  17640. var loadingScreen = this.loadingScreen;
  17641. if (loadingScreen) {
  17642. loadingScreen.displayLoadingUI();
  17643. }
  17644. };
  17645. /**
  17646. * Hide the loading screen
  17647. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17648. */
  17649. Engine.prototype.hideLoadingUI = function () {
  17650. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17651. return;
  17652. }
  17653. var loadingScreen = this.loadingScreen;
  17654. if (loadingScreen) {
  17655. loadingScreen.hideLoadingUI();
  17656. }
  17657. };
  17658. Object.defineProperty(Engine.prototype, "loadingScreen", {
  17659. /**
  17660. * Gets the current loading screen object
  17661. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17662. */
  17663. get: function () {
  17664. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas) {
  17665. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  17666. }
  17667. return this._loadingScreen;
  17668. },
  17669. /**
  17670. * Sets the current loading screen object
  17671. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17672. */
  17673. set: function (loadingScreen) {
  17674. this._loadingScreen = loadingScreen;
  17675. },
  17676. enumerable: true,
  17677. configurable: true
  17678. });
  17679. Object.defineProperty(Engine.prototype, "loadingUIText", {
  17680. /**
  17681. * Sets the current loading screen text
  17682. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17683. */
  17684. set: function (text) {
  17685. this.loadingScreen.loadingUIText = text;
  17686. },
  17687. enumerable: true,
  17688. configurable: true
  17689. });
  17690. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  17691. /**
  17692. * Sets the current loading screen background color
  17693. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17694. */
  17695. set: function (color) {
  17696. this.loadingScreen.loadingUIBackgroundColor = color;
  17697. },
  17698. enumerable: true,
  17699. configurable: true
  17700. });
  17701. /**
  17702. * Attach a new callback raised when context lost event is fired
  17703. * @param callback defines the callback to call
  17704. */
  17705. Engine.prototype.attachContextLostEvent = function (callback) {
  17706. if (this._renderingCanvas) {
  17707. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  17708. }
  17709. };
  17710. /**
  17711. * Attach a new callback raised when context restored event is fired
  17712. * @param callback defines the callback to call
  17713. */
  17714. Engine.prototype.attachContextRestoredEvent = function (callback) {
  17715. if (this._renderingCanvas) {
  17716. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  17717. }
  17718. };
  17719. /**
  17720. * Gets the source code of the vertex shader associated with a specific webGL program
  17721. * @param program defines the program to use
  17722. * @returns a string containing the source code of the vertex shader associated with the program
  17723. */
  17724. Engine.prototype.getVertexShaderSource = function (program) {
  17725. var shaders = this._gl.getAttachedShaders(program);
  17726. if (!shaders) {
  17727. return null;
  17728. }
  17729. return this._gl.getShaderSource(shaders[0]);
  17730. };
  17731. /**
  17732. * Gets the source code of the fragment shader associated with a specific webGL program
  17733. * @param program defines the program to use
  17734. * @returns a string containing the source code of the fragment shader associated with the program
  17735. */
  17736. Engine.prototype.getFragmentShaderSource = function (program) {
  17737. var shaders = this._gl.getAttachedShaders(program);
  17738. if (!shaders) {
  17739. return null;
  17740. }
  17741. return this._gl.getShaderSource(shaders[1]);
  17742. };
  17743. /**
  17744. * Get the current error code of the webGL context
  17745. * @returns the error code
  17746. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  17747. */
  17748. Engine.prototype.getError = function () {
  17749. return this._gl.getError();
  17750. };
  17751. // FPS
  17752. /**
  17753. * Gets the current framerate
  17754. * @returns a number representing the framerate
  17755. */
  17756. Engine.prototype.getFps = function () {
  17757. return this._fps;
  17758. };
  17759. /**
  17760. * Gets the time spent between current and previous frame
  17761. * @returns a number representing the delta time in ms
  17762. */
  17763. Engine.prototype.getDeltaTime = function () {
  17764. return this._deltaTime;
  17765. };
  17766. Engine.prototype._measureFps = function () {
  17767. this._performanceMonitor.sampleFrame();
  17768. this._fps = this._performanceMonitor.averageFPS;
  17769. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  17770. };
  17771. /** @hidden */
  17772. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level, buffer) {
  17773. if (faceIndex === void 0) { faceIndex = -1; }
  17774. if (level === void 0) { level = 0; }
  17775. if (buffer === void 0) { buffer = null; }
  17776. var gl = this._gl;
  17777. if (!this._dummyFramebuffer) {
  17778. var dummy = gl.createFramebuffer();
  17779. if (!dummy) {
  17780. throw new Error("Unable to create dummy framebuffer");
  17781. }
  17782. this._dummyFramebuffer = dummy;
  17783. }
  17784. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  17785. if (faceIndex > -1) {
  17786. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  17787. }
  17788. else {
  17789. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  17790. }
  17791. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  17792. switch (readType) {
  17793. case gl.UNSIGNED_BYTE:
  17794. if (!buffer) {
  17795. buffer = new Uint8Array(4 * width * height);
  17796. }
  17797. readType = gl.UNSIGNED_BYTE;
  17798. break;
  17799. default:
  17800. if (!buffer) {
  17801. buffer = new Float32Array(4 * width * height);
  17802. }
  17803. readType = gl.FLOAT;
  17804. break;
  17805. }
  17806. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17807. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17808. return buffer;
  17809. };
  17810. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17811. if (this._webGLVersion > 1) {
  17812. return this._caps.colorBufferFloat;
  17813. }
  17814. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17815. };
  17816. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17817. if (this._webGLVersion > 1) {
  17818. return this._caps.colorBufferFloat;
  17819. }
  17820. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17821. };
  17822. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17823. Engine.prototype._canRenderToFramebuffer = function (type) {
  17824. var gl = this._gl;
  17825. //clear existing errors
  17826. while (gl.getError() !== gl.NO_ERROR) { }
  17827. var successful = true;
  17828. var texture = gl.createTexture();
  17829. gl.bindTexture(gl.TEXTURE_2D, texture);
  17830. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17831. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17832. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17833. var fb = gl.createFramebuffer();
  17834. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17835. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17836. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17837. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17838. successful = successful && (gl.getError() === gl.NO_ERROR);
  17839. //try render by clearing frame buffer's color buffer
  17840. if (successful) {
  17841. gl.clear(gl.COLOR_BUFFER_BIT);
  17842. successful = successful && (gl.getError() === gl.NO_ERROR);
  17843. }
  17844. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17845. if (successful) {
  17846. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17847. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17848. var readFormat = gl.RGBA;
  17849. var readType = gl.UNSIGNED_BYTE;
  17850. var buffer = new Uint8Array(4);
  17851. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17852. successful = successful && (gl.getError() === gl.NO_ERROR);
  17853. }
  17854. //clean up
  17855. gl.deleteTexture(texture);
  17856. gl.deleteFramebuffer(fb);
  17857. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17858. //clear accumulated errors
  17859. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17860. return successful;
  17861. };
  17862. /** @hidden */
  17863. Engine.prototype._getWebGLTextureType = function (type) {
  17864. if (this._webGLVersion === 1) {
  17865. switch (type) {
  17866. case Engine.TEXTURETYPE_FLOAT:
  17867. return this._gl.FLOAT;
  17868. case Engine.TEXTURETYPE_HALF_FLOAT:
  17869. return this._gl.HALF_FLOAT_OES;
  17870. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17871. return this._gl.UNSIGNED_BYTE;
  17872. }
  17873. return this._gl.UNSIGNED_BYTE;
  17874. }
  17875. switch (type) {
  17876. case Engine.TEXTURETYPE_BYTE:
  17877. return this._gl.BYTE;
  17878. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17879. return this._gl.UNSIGNED_BYTE;
  17880. case Engine.TEXTURETYPE_SHORT:
  17881. return this._gl.SHORT;
  17882. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17883. return this._gl.UNSIGNED_SHORT;
  17884. case Engine.TEXTURETYPE_INT:
  17885. return this._gl.INT;
  17886. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17887. return this._gl.UNSIGNED_INT;
  17888. case Engine.TEXTURETYPE_FLOAT:
  17889. return this._gl.FLOAT;
  17890. case Engine.TEXTURETYPE_HALF_FLOAT:
  17891. return this._gl.HALF_FLOAT;
  17892. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17893. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  17894. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17895. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  17896. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17897. return this._gl.UNSIGNED_SHORT_5_6_5;
  17898. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17899. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  17900. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  17901. return this._gl.UNSIGNED_INT_24_8;
  17902. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17903. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  17904. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17905. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  17906. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  17907. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  17908. }
  17909. return this._gl.UNSIGNED_BYTE;
  17910. };
  17911. Engine.prototype._getInternalFormat = function (format) {
  17912. var internalFormat = this._gl.RGBA;
  17913. switch (format) {
  17914. case Engine.TEXTUREFORMAT_ALPHA:
  17915. internalFormat = this._gl.ALPHA;
  17916. break;
  17917. case Engine.TEXTUREFORMAT_LUMINANCE:
  17918. internalFormat = this._gl.LUMINANCE;
  17919. break;
  17920. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17921. internalFormat = this._gl.LUMINANCE_ALPHA;
  17922. break;
  17923. case Engine.TEXTUREFORMAT_RED:
  17924. internalFormat = this._gl.RED;
  17925. break;
  17926. case Engine.TEXTUREFORMAT_RG:
  17927. internalFormat = this._gl.RG;
  17928. break;
  17929. case Engine.TEXTUREFORMAT_RGB:
  17930. internalFormat = this._gl.RGB;
  17931. break;
  17932. case Engine.TEXTUREFORMAT_RGBA:
  17933. internalFormat = this._gl.RGBA;
  17934. break;
  17935. }
  17936. if (this._webGLVersion > 1) {
  17937. switch (format) {
  17938. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17939. internalFormat = this._gl.RED_INTEGER;
  17940. break;
  17941. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17942. internalFormat = this._gl.RG_INTEGER;
  17943. break;
  17944. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17945. internalFormat = this._gl.RGB_INTEGER;
  17946. break;
  17947. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17948. internalFormat = this._gl.RGBA_INTEGER;
  17949. break;
  17950. }
  17951. }
  17952. return internalFormat;
  17953. };
  17954. /** @hidden */
  17955. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17956. if (this._webGLVersion === 1) {
  17957. if (format !== undefined) {
  17958. switch (format) {
  17959. case Engine.TEXTUREFORMAT_ALPHA:
  17960. return this._gl.ALPHA;
  17961. case Engine.TEXTUREFORMAT_LUMINANCE:
  17962. return this._gl.LUMINANCE;
  17963. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17964. return this._gl.LUMINANCE_ALPHA;
  17965. }
  17966. }
  17967. return this._gl.RGBA;
  17968. }
  17969. switch (type) {
  17970. case Engine.TEXTURETYPE_BYTE:
  17971. switch (format) {
  17972. case Engine.TEXTUREFORMAT_RED:
  17973. return this._gl.R8_SNORM;
  17974. case Engine.TEXTUREFORMAT_RG:
  17975. return this._gl.RG8_SNORM;
  17976. case Engine.TEXTUREFORMAT_RGB:
  17977. return this._gl.RGB8_SNORM;
  17978. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17979. return this._gl.R8I;
  17980. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17981. return this._gl.RG8I;
  17982. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17983. return this._gl.RGB8I;
  17984. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17985. return this._gl.RGBA8I;
  17986. default:
  17987. return this._gl.RGBA8_SNORM;
  17988. }
  17989. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17990. switch (format) {
  17991. case Engine.TEXTUREFORMAT_RED:
  17992. return this._gl.R8;
  17993. case Engine.TEXTUREFORMAT_RG:
  17994. return this._gl.RG8;
  17995. case Engine.TEXTUREFORMAT_RGB:
  17996. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  17997. case Engine.TEXTUREFORMAT_RGBA:
  17998. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  17999. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18000. return this._gl.R8UI;
  18001. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18002. return this._gl.RG8UI;
  18003. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18004. return this._gl.RGB8UI;
  18005. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18006. return this._gl.RGBA8UI;
  18007. default:
  18008. return this._gl.RGBA8;
  18009. }
  18010. case Engine.TEXTURETYPE_SHORT:
  18011. switch (format) {
  18012. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18013. return this._gl.R16I;
  18014. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18015. return this._gl.RG16I;
  18016. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18017. return this._gl.RGB16I;
  18018. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18019. return this._gl.RGBA16I;
  18020. default:
  18021. return this._gl.RGBA16I;
  18022. }
  18023. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  18024. switch (format) {
  18025. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18026. return this._gl.R16UI;
  18027. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18028. return this._gl.RG16UI;
  18029. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18030. return this._gl.RGB16UI;
  18031. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18032. return this._gl.RGBA16UI;
  18033. default:
  18034. return this._gl.RGBA16UI;
  18035. }
  18036. case Engine.TEXTURETYPE_INT:
  18037. switch (format) {
  18038. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18039. return this._gl.R32I;
  18040. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18041. return this._gl.RG32I;
  18042. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18043. return this._gl.RGB32I;
  18044. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18045. return this._gl.RGBA32I;
  18046. default:
  18047. return this._gl.RGBA32I;
  18048. }
  18049. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  18050. switch (format) {
  18051. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18052. return this._gl.R32UI;
  18053. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18054. return this._gl.RG32UI;
  18055. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18056. return this._gl.RGB32UI;
  18057. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18058. return this._gl.RGBA32UI;
  18059. default:
  18060. return this._gl.RGBA32UI;
  18061. }
  18062. case Engine.TEXTURETYPE_FLOAT:
  18063. switch (format) {
  18064. case Engine.TEXTUREFORMAT_RED:
  18065. return this._gl.R32F; // By default. Other possibility is R16F.
  18066. case Engine.TEXTUREFORMAT_RG:
  18067. return this._gl.RG32F; // By default. Other possibility is RG16F.
  18068. case Engine.TEXTUREFORMAT_RGB:
  18069. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  18070. case Engine.TEXTUREFORMAT_RGBA:
  18071. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  18072. default:
  18073. return this._gl.RGBA32F;
  18074. }
  18075. case Engine.TEXTURETYPE_HALF_FLOAT:
  18076. switch (format) {
  18077. case Engine.TEXTUREFORMAT_RED:
  18078. return this._gl.R16F;
  18079. case Engine.TEXTUREFORMAT_RG:
  18080. return this._gl.RG16F;
  18081. case Engine.TEXTUREFORMAT_RGB:
  18082. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  18083. case Engine.TEXTUREFORMAT_RGBA:
  18084. return this._gl.RGBA16F;
  18085. default:
  18086. return this._gl.RGBA16F;
  18087. }
  18088. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  18089. return this._gl.RGB565;
  18090. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  18091. return this._gl.R11F_G11F_B10F;
  18092. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  18093. return this._gl.RGB9_E5;
  18094. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  18095. return this._gl.RGBA4;
  18096. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  18097. return this._gl.RGB5_A1;
  18098. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  18099. switch (format) {
  18100. case Engine.TEXTUREFORMAT_RGBA:
  18101. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  18102. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18103. return this._gl.RGB10_A2UI;
  18104. default:
  18105. return this._gl.RGB10_A2;
  18106. }
  18107. }
  18108. return this._gl.RGBA8;
  18109. };
  18110. /** @hidden */
  18111. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  18112. if (type === Engine.TEXTURETYPE_FLOAT) {
  18113. return this._gl.RGBA32F;
  18114. }
  18115. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  18116. return this._gl.RGBA16F;
  18117. }
  18118. return this._gl.RGBA8;
  18119. };
  18120. /** @hidden */
  18121. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  18122. var _this = this;
  18123. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  18124. this._activeRequests.push(request);
  18125. request.onCompleteObservable.add(function (request) {
  18126. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  18127. });
  18128. return request;
  18129. };
  18130. /** @hidden */
  18131. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  18132. var _this = this;
  18133. return new Promise(function (resolve, reject) {
  18134. _this._loadFile(url, function (data) {
  18135. resolve(data);
  18136. }, undefined, database, useArrayBuffer, function (request, exception) {
  18137. reject(exception);
  18138. });
  18139. });
  18140. };
  18141. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  18142. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  18143. var onload = function (data) {
  18144. loadedFiles[index] = data;
  18145. loadedFiles._internalCount++;
  18146. if (loadedFiles._internalCount === 6) {
  18147. onfinish(loadedFiles);
  18148. }
  18149. };
  18150. var onerror = function (request, exception) {
  18151. if (onErrorCallBack && request) {
  18152. onErrorCallBack(request.status + " " + request.statusText, exception);
  18153. }
  18154. };
  18155. this._loadFile(url, onload, undefined, undefined, true, onerror);
  18156. };
  18157. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  18158. if (onError === void 0) { onError = null; }
  18159. var loadedFiles = [];
  18160. loadedFiles._internalCount = 0;
  18161. for (var index = 0; index < 6; index++) {
  18162. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  18163. }
  18164. };
  18165. // Statics
  18166. /**
  18167. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  18168. * @returns true if the engine can be created
  18169. * @ignorenaming
  18170. */
  18171. Engine.isSupported = function () {
  18172. try {
  18173. var tempcanvas = document.createElement("canvas");
  18174. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  18175. return gl != null && !!window.WebGLRenderingContext;
  18176. }
  18177. catch (e) {
  18178. return false;
  18179. }
  18180. };
  18181. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  18182. Engine.ExceptionList = [
  18183. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  18184. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  18185. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  18186. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  18187. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  18188. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  18189. ];
  18190. /** Gets the list of created engines */
  18191. Engine.Instances = new Array();
  18192. /**
  18193. * Hidden
  18194. */
  18195. Engine._TextureLoaders = [];
  18196. // Const statics
  18197. /** Defines that alpha blending is disabled */
  18198. Engine.ALPHA_DISABLE = 0;
  18199. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  18200. Engine.ALPHA_ADD = 1;
  18201. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  18202. Engine.ALPHA_COMBINE = 2;
  18203. /** Defines that alpha blending to DEST - SRC * DEST */
  18204. Engine.ALPHA_SUBTRACT = 3;
  18205. /** Defines that alpha blending to SRC * DEST */
  18206. Engine.ALPHA_MULTIPLY = 4;
  18207. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  18208. Engine.ALPHA_MAXIMIZED = 5;
  18209. /** Defines that alpha blending to SRC + DEST */
  18210. Engine.ALPHA_ONEONE = 6;
  18211. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  18212. Engine.ALPHA_PREMULTIPLIED = 7;
  18213. /**
  18214. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  18215. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  18216. */
  18217. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  18218. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  18219. Engine.ALPHA_INTERPOLATE = 9;
  18220. /**
  18221. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  18222. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  18223. */
  18224. Engine.ALPHA_SCREENMODE = 10;
  18225. /** Defines that the ressource is not delayed*/
  18226. Engine.DELAYLOADSTATE_NONE = 0;
  18227. /** Defines that the ressource was successfully delay loaded */
  18228. Engine.DELAYLOADSTATE_LOADED = 1;
  18229. /** Defines that the ressource is currently delay loading */
  18230. Engine.DELAYLOADSTATE_LOADING = 2;
  18231. /** Defines that the ressource is delayed and has not started loading */
  18232. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  18233. // Depht or Stencil test Constants.
  18234. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  18235. Engine.NEVER = 0x0200;
  18236. /** 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 */
  18237. Engine.ALWAYS = 0x0207;
  18238. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  18239. Engine.LESS = 0x0201;
  18240. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  18241. Engine.EQUAL = 0x0202;
  18242. /** 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 */
  18243. Engine.LEQUAL = 0x0203;
  18244. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  18245. Engine.GREATER = 0x0204;
  18246. /** 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 */
  18247. Engine.GEQUAL = 0x0206;
  18248. /** 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 */
  18249. Engine.NOTEQUAL = 0x0205;
  18250. // Stencil Actions Constants.
  18251. /** Passed to stencilOperation to specify that stencil value must be kept */
  18252. Engine.KEEP = 0x1E00;
  18253. /** Passed to stencilOperation to specify that stencil value must be replaced */
  18254. Engine.REPLACE = 0x1E01;
  18255. /** Passed to stencilOperation to specify that stencil value must be incremented */
  18256. Engine.INCR = 0x1E02;
  18257. /** Passed to stencilOperation to specify that stencil value must be decremented */
  18258. Engine.DECR = 0x1E03;
  18259. /** Passed to stencilOperation to specify that stencil value must be inverted */
  18260. Engine.INVERT = 0x150A;
  18261. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  18262. Engine.INCR_WRAP = 0x8507;
  18263. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  18264. Engine.DECR_WRAP = 0x8508;
  18265. /** Texture is not repeating outside of 0..1 UVs */
  18266. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  18267. /** Texture is repeating outside of 0..1 UVs */
  18268. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  18269. /** Texture is repeating and mirrored */
  18270. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  18271. /** ALPHA */
  18272. Engine.TEXTUREFORMAT_ALPHA = 0;
  18273. /** LUMINANCE */
  18274. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  18275. /** LUMINANCE_ALPHA */
  18276. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  18277. /** RGB */
  18278. Engine.TEXTUREFORMAT_RGB = 4;
  18279. /** RGBA */
  18280. Engine.TEXTUREFORMAT_RGBA = 5;
  18281. /** RED */
  18282. Engine.TEXTUREFORMAT_RED = 6;
  18283. /** RED (2nd reference) */
  18284. Engine.TEXTUREFORMAT_R = 6;
  18285. /** RG */
  18286. Engine.TEXTUREFORMAT_RG = 7;
  18287. /** RED_INTEGER */
  18288. Engine.TEXTUREFORMAT_RED_INTEGER = 8;
  18289. /** RED_INTEGER (2nd reference) */
  18290. Engine.TEXTUREFORMAT_R_INTEGER = 8;
  18291. /** RG_INTEGER */
  18292. Engine.TEXTUREFORMAT_RG_INTEGER = 9;
  18293. /** RGB_INTEGER */
  18294. Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
  18295. /** RGBA_INTEGER */
  18296. Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
  18297. /** UNSIGNED_BYTE */
  18298. Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
  18299. /** UNSIGNED_BYTE (2nd reference) */
  18300. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  18301. /** FLOAT */
  18302. Engine.TEXTURETYPE_FLOAT = 1;
  18303. /** HALF_FLOAT */
  18304. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  18305. /** BYTE */
  18306. Engine.TEXTURETYPE_BYTE = 3;
  18307. /** SHORT */
  18308. Engine.TEXTURETYPE_SHORT = 4;
  18309. /** UNSIGNED_SHORT */
  18310. Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
  18311. /** INT */
  18312. Engine.TEXTURETYPE_INT = 6;
  18313. /** UNSIGNED_INT */
  18314. Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
  18315. /** UNSIGNED_SHORT_4_4_4_4 */
  18316. Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
  18317. /** UNSIGNED_SHORT_5_5_5_1 */
  18318. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
  18319. /** UNSIGNED_SHORT_5_6_5 */
  18320. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
  18321. /** UNSIGNED_INT_2_10_10_10_REV */
  18322. Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
  18323. /** UNSIGNED_INT_24_8 */
  18324. Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
  18325. /** UNSIGNED_INT_10F_11F_11F_REV */
  18326. Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
  18327. /** UNSIGNED_INT_5_9_9_9_REV */
  18328. Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
  18329. /** FLOAT_32_UNSIGNED_INT_24_8_REV */
  18330. Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
  18331. /** nearest is mag = nearest and min = nearest and mip = linear */
  18332. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  18333. /** Bilinear is mag = linear and min = linear and mip = nearest */
  18334. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  18335. /** Trilinear is mag = linear and min = linear and mip = linear */
  18336. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  18337. /** nearest is mag = nearest and min = nearest and mip = linear */
  18338. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  18339. /** Bilinear is mag = linear and min = linear and mip = nearest */
  18340. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  18341. /** Trilinear is mag = linear and min = linear and mip = linear */
  18342. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  18343. /** mag = nearest and min = nearest and mip = nearest */
  18344. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  18345. /** mag = nearest and min = linear and mip = nearest */
  18346. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  18347. /** mag = nearest and min = linear and mip = linear */
  18348. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  18349. /** mag = nearest and min = linear and mip = none */
  18350. Engine.TEXTURE_NEAREST_LINEAR = 7;
  18351. /** mag = nearest and min = nearest and mip = none */
  18352. Engine.TEXTURE_NEAREST_NEAREST = 8;
  18353. /** mag = linear and min = nearest and mip = nearest */
  18354. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  18355. /** mag = linear and min = nearest and mip = linear */
  18356. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  18357. /** mag = linear and min = linear and mip = none */
  18358. Engine.TEXTURE_LINEAR_LINEAR = 11;
  18359. /** mag = linear and min = nearest and mip = none */
  18360. Engine.TEXTURE_LINEAR_NEAREST = 12;
  18361. /** Explicit coordinates mode */
  18362. Engine.TEXTURE_EXPLICIT_MODE = 0;
  18363. /** Spherical coordinates mode */
  18364. Engine.TEXTURE_SPHERICAL_MODE = 1;
  18365. /** Planar coordinates mode */
  18366. Engine.TEXTURE_PLANAR_MODE = 2;
  18367. /** Cubic coordinates mode */
  18368. Engine.TEXTURE_CUBIC_MODE = 3;
  18369. /** Projection coordinates mode */
  18370. Engine.TEXTURE_PROJECTION_MODE = 4;
  18371. /** Skybox coordinates mode */
  18372. Engine.TEXTURE_SKYBOX_MODE = 5;
  18373. /** Inverse Cubic coordinates mode */
  18374. Engine.TEXTURE_INVCUBIC_MODE = 6;
  18375. /** Equirectangular coordinates mode */
  18376. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  18377. /** Equirectangular Fixed coordinates mode */
  18378. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  18379. /** Equirectangular Fixed Mirrored coordinates mode */
  18380. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  18381. // Texture rescaling mode
  18382. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  18383. Engine.SCALEMODE_FLOOR = 1;
  18384. /** Defines that texture rescaling will look for the nearest power of 2 size */
  18385. Engine.SCALEMODE_NEAREST = 2;
  18386. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  18387. Engine.SCALEMODE_CEILING = 3;
  18388. // Updatable statics so stick with vars here
  18389. /**
  18390. * Gets or sets the epsilon value used by collision engine
  18391. */
  18392. Engine.CollisionsEpsilon = 0.001;
  18393. /**
  18394. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  18395. */
  18396. Engine.CodeRepository = "src/";
  18397. /**
  18398. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  18399. */
  18400. Engine.ShadersRepository = "src/Shaders/";
  18401. return Engine;
  18402. }());
  18403. BABYLON.Engine = Engine;
  18404. })(BABYLON || (BABYLON = {}));
  18405. //# sourceMappingURL=babylon.engine.js.map
  18406. var BABYLON;
  18407. (function (BABYLON) {
  18408. /**
  18409. * Node is the basic class for all scene objects (Mesh, Light, Camera.)
  18410. */
  18411. var Node = /** @class */ (function () {
  18412. /**
  18413. * Creates a new Node
  18414. * @param name the name and id to be given to this node
  18415. * @param scene the scene this node will be added to
  18416. */
  18417. function Node(name, scene) {
  18418. if (scene === void 0) { scene = null; }
  18419. /**
  18420. * Gets or sets a string used to store user defined state for the node
  18421. */
  18422. this.state = "";
  18423. /**
  18424. * Gets or sets an object used to store user defined information for the node
  18425. */
  18426. this.metadata = null;
  18427. /**
  18428. * Gets or sets a boolean used to define if the node must be serialized
  18429. */
  18430. this.doNotSerialize = false;
  18431. /** @hidden */
  18432. this._isDisposed = false;
  18433. /**
  18434. * Gets a list of Animations associated with the node
  18435. */
  18436. this.animations = new Array();
  18437. this._ranges = {};
  18438. this._isEnabled = true;
  18439. this._isParentEnabled = true;
  18440. this._isReady = true;
  18441. /** @hidden */
  18442. this._currentRenderId = -1;
  18443. this._parentRenderId = -1;
  18444. this._childRenderId = -1;
  18445. /** @hidden */
  18446. this._worldMatrix = BABYLON.Matrix.Identity();
  18447. /** @hidden */
  18448. this._worldMatrixDeterminant = 0;
  18449. /** @hidden */
  18450. this._sceneRootNodesIndex = -1;
  18451. this._animationPropertiesOverride = null;
  18452. /**
  18453. * An event triggered when the mesh is disposed
  18454. */
  18455. this.onDisposeObservable = new BABYLON.Observable();
  18456. // Behaviors
  18457. this._behaviors = new Array();
  18458. this.name = name;
  18459. this.id = name;
  18460. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  18461. this.uniqueId = this._scene.getUniqueId();
  18462. this._initCache();
  18463. this.addToSceneRootNodes();
  18464. }
  18465. /**
  18466. * Add a new node constructor
  18467. * @param type defines the type name of the node to construct
  18468. * @param constructorFunc defines the constructor function
  18469. */
  18470. Node.AddNodeConstructor = function (type, constructorFunc) {
  18471. this._NodeConstructors[type] = constructorFunc;
  18472. };
  18473. /**
  18474. * Returns a node constructor based on type name
  18475. * @param type defines the type name
  18476. * @param name defines the new node name
  18477. * @param scene defines the hosting scene
  18478. * @param options defines optional options to transmit to constructors
  18479. * @returns the new constructor or null
  18480. */
  18481. Node.Construct = function (type, name, scene, options) {
  18482. var constructorFunc = this._NodeConstructors[type];
  18483. if (!constructorFunc) {
  18484. return null;
  18485. }
  18486. return constructorFunc(name, scene, options);
  18487. };
  18488. /**
  18489. * Gets a boolean indicating if the node has been disposed
  18490. * @returns true if the node was disposed
  18491. */
  18492. Node.prototype.isDisposed = function () {
  18493. return this._isDisposed;
  18494. };
  18495. Object.defineProperty(Node.prototype, "parent", {
  18496. get: function () {
  18497. return this._parentNode;
  18498. },
  18499. /**
  18500. * Gets or sets the parent of the node
  18501. */
  18502. set: function (parent) {
  18503. if (this._parentNode === parent) {
  18504. return;
  18505. }
  18506. var previousParentNode = this._parentNode;
  18507. // Remove self from list of children of parent
  18508. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  18509. var index = this._parentNode._children.indexOf(this);
  18510. if (index !== -1) {
  18511. this._parentNode._children.splice(index, 1);
  18512. }
  18513. if (!parent) {
  18514. this.addToSceneRootNodes();
  18515. }
  18516. }
  18517. // Store new parent
  18518. this._parentNode = parent;
  18519. // Add as child to new parent
  18520. if (this._parentNode) {
  18521. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  18522. this._parentNode._children = new Array();
  18523. }
  18524. this._parentNode._children.push(this);
  18525. if (!previousParentNode) {
  18526. this.removeFromSceneRootNodes();
  18527. }
  18528. }
  18529. // Enabled state
  18530. this._syncParentEnabledState();
  18531. },
  18532. enumerable: true,
  18533. configurable: true
  18534. });
  18535. Node.prototype.addToSceneRootNodes = function () {
  18536. if (this._sceneRootNodesIndex === -1) {
  18537. this._sceneRootNodesIndex = this._scene.rootNodes.length;
  18538. this._scene.rootNodes.push(this);
  18539. }
  18540. };
  18541. Node.prototype.removeFromSceneRootNodes = function () {
  18542. if (this._sceneRootNodesIndex !== -1) {
  18543. var rootNodes = this._scene.rootNodes;
  18544. var lastIdx = rootNodes.length - 1;
  18545. rootNodes[this._sceneRootNodesIndex] = rootNodes[lastIdx];
  18546. rootNodes[this._sceneRootNodesIndex]._sceneRootNodesIndex = this._sceneRootNodesIndex;
  18547. this._scene.rootNodes.pop();
  18548. this._sceneRootNodesIndex = -1;
  18549. }
  18550. };
  18551. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  18552. /**
  18553. * Gets or sets the animation properties override
  18554. */
  18555. get: function () {
  18556. if (!this._animationPropertiesOverride) {
  18557. return this._scene.animationPropertiesOverride;
  18558. }
  18559. return this._animationPropertiesOverride;
  18560. },
  18561. set: function (value) {
  18562. this._animationPropertiesOverride = value;
  18563. },
  18564. enumerable: true,
  18565. configurable: true
  18566. });
  18567. /**
  18568. * Gets a string idenfifying the name of the class
  18569. * @returns "Node" string
  18570. */
  18571. Node.prototype.getClassName = function () {
  18572. return "Node";
  18573. };
  18574. Object.defineProperty(Node.prototype, "onDispose", {
  18575. /**
  18576. * Sets a callback that will be raised when the node will be disposed
  18577. */
  18578. set: function (callback) {
  18579. if (this._onDisposeObserver) {
  18580. this.onDisposeObservable.remove(this._onDisposeObserver);
  18581. }
  18582. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18583. },
  18584. enumerable: true,
  18585. configurable: true
  18586. });
  18587. /**
  18588. * Gets the scene of the node
  18589. * @returns a scene
  18590. */
  18591. Node.prototype.getScene = function () {
  18592. return this._scene;
  18593. };
  18594. /**
  18595. * Gets the engine of the node
  18596. * @returns a Engine
  18597. */
  18598. Node.prototype.getEngine = function () {
  18599. return this._scene.getEngine();
  18600. };
  18601. /**
  18602. * Attach a behavior to the node
  18603. * @see http://doc.babylonjs.com/features/behaviour
  18604. * @param behavior defines the behavior to attach
  18605. * @param attachImmediately defines that the behavior must be attached even if the scene is still loading
  18606. * @returns the current Node
  18607. */
  18608. Node.prototype.addBehavior = function (behavior, attachImmediately) {
  18609. var _this = this;
  18610. if (attachImmediately === void 0) { attachImmediately = false; }
  18611. var index = this._behaviors.indexOf(behavior);
  18612. if (index !== -1) {
  18613. return this;
  18614. }
  18615. behavior.init();
  18616. if (this._scene.isLoading && !attachImmediately) {
  18617. // We defer the attach when the scene will be loaded
  18618. this._scene.onDataLoadedObservable.addOnce(function () {
  18619. behavior.attach(_this);
  18620. });
  18621. }
  18622. else {
  18623. behavior.attach(this);
  18624. }
  18625. this._behaviors.push(behavior);
  18626. return this;
  18627. };
  18628. /**
  18629. * Remove an attached behavior
  18630. * @see http://doc.babylonjs.com/features/behaviour
  18631. * @param behavior defines the behavior to attach
  18632. * @returns the current Node
  18633. */
  18634. Node.prototype.removeBehavior = function (behavior) {
  18635. var index = this._behaviors.indexOf(behavior);
  18636. if (index === -1) {
  18637. return this;
  18638. }
  18639. this._behaviors[index].detach();
  18640. this._behaviors.splice(index, 1);
  18641. return this;
  18642. };
  18643. Object.defineProperty(Node.prototype, "behaviors", {
  18644. /**
  18645. * Gets the list of attached behaviors
  18646. * @see http://doc.babylonjs.com/features/behaviour
  18647. */
  18648. get: function () {
  18649. return this._behaviors;
  18650. },
  18651. enumerable: true,
  18652. configurable: true
  18653. });
  18654. /**
  18655. * Gets an attached behavior by name
  18656. * @param name defines the name of the behavior to look for
  18657. * @see http://doc.babylonjs.com/features/behaviour
  18658. * @returns null if behavior was not found else the requested behavior
  18659. */
  18660. Node.prototype.getBehaviorByName = function (name) {
  18661. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  18662. var behavior = _a[_i];
  18663. if (behavior.name === name) {
  18664. return behavior;
  18665. }
  18666. }
  18667. return null;
  18668. };
  18669. /**
  18670. * Returns the latest update of the World matrix
  18671. * @returns a Matrix
  18672. */
  18673. Node.prototype.getWorldMatrix = function () {
  18674. if (this._currentRenderId !== this._scene.getRenderId()) {
  18675. this.computeWorldMatrix();
  18676. }
  18677. return this._worldMatrix;
  18678. };
  18679. /** @hidden */
  18680. Node.prototype._getWorldMatrixDeterminant = function () {
  18681. return this._worldMatrixDeterminant;
  18682. };
  18683. Object.defineProperty(Node.prototype, "worldMatrixFromCache", {
  18684. /**
  18685. * Returns directly the latest state of the mesh World matrix.
  18686. * A Matrix is returned.
  18687. */
  18688. get: function () {
  18689. return this._worldMatrix;
  18690. },
  18691. enumerable: true,
  18692. configurable: true
  18693. });
  18694. // override it in derived class if you add new variables to the cache
  18695. // and call the parent class method
  18696. /** @hidden */
  18697. Node.prototype._initCache = function () {
  18698. this._cache = {};
  18699. this._cache.parent = undefined;
  18700. };
  18701. /** @hidden */
  18702. Node.prototype.updateCache = function (force) {
  18703. if (!force && this.isSynchronized()) {
  18704. return;
  18705. }
  18706. this._cache.parent = this.parent;
  18707. this._updateCache();
  18708. };
  18709. // override it in derived class if you add new variables to the cache
  18710. // and call the parent class method if !ignoreParentClass
  18711. /** @hidden */
  18712. Node.prototype._updateCache = function (ignoreParentClass) {
  18713. };
  18714. // override it in derived class if you add new variables to the cache
  18715. /** @hidden */
  18716. Node.prototype._isSynchronized = function () {
  18717. return true;
  18718. };
  18719. /** @hidden */
  18720. Node.prototype._markSyncedWithParent = function () {
  18721. if (this._parentNode) {
  18722. this._parentRenderId = this._parentNode._childRenderId;
  18723. }
  18724. };
  18725. /** @hidden */
  18726. Node.prototype.isSynchronizedWithParent = function () {
  18727. if (!this._parentNode) {
  18728. return true;
  18729. }
  18730. if (this._parentRenderId !== this._parentNode._childRenderId) {
  18731. return false;
  18732. }
  18733. return this._parentNode.isSynchronized();
  18734. };
  18735. /** @hidden */
  18736. Node.prototype.isSynchronized = function () {
  18737. if (this._cache.parent != this._parentNode) {
  18738. this._cache.parent = this._parentNode;
  18739. return false;
  18740. }
  18741. if (this._parentNode && !this.isSynchronizedWithParent()) {
  18742. return false;
  18743. }
  18744. return this._isSynchronized();
  18745. };
  18746. /**
  18747. * Is this node ready to be used/rendered
  18748. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  18749. * @return true if the node is ready
  18750. */
  18751. Node.prototype.isReady = function (completeCheck) {
  18752. if (completeCheck === void 0) { completeCheck = false; }
  18753. return this._isReady;
  18754. };
  18755. /**
  18756. * Is this node enabled?
  18757. * 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
  18758. * @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
  18759. * @return whether this node (and its parent) is enabled
  18760. */
  18761. Node.prototype.isEnabled = function (checkAncestors) {
  18762. if (checkAncestors === void 0) { checkAncestors = true; }
  18763. if (checkAncestors === false) {
  18764. return this._isEnabled;
  18765. }
  18766. if (!this._isEnabled) {
  18767. return false;
  18768. }
  18769. return this._isParentEnabled;
  18770. };
  18771. /** @hidden */
  18772. Node.prototype._syncParentEnabledState = function () {
  18773. this._isParentEnabled = this._parentNode ? this._parentNode.isEnabled() : true;
  18774. if (this._children) {
  18775. this._children.forEach(function (c) {
  18776. c._syncParentEnabledState(); // Force children to update accordingly
  18777. });
  18778. }
  18779. };
  18780. /**
  18781. * Set the enabled state of this node
  18782. * @param value defines the new enabled state
  18783. */
  18784. Node.prototype.setEnabled = function (value) {
  18785. this._isEnabled = value;
  18786. this._syncParentEnabledState();
  18787. };
  18788. /**
  18789. * Is this node a descendant of the given node?
  18790. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  18791. * @param ancestor defines the parent node to inspect
  18792. * @returns a boolean indicating if this node is a descendant of the given node
  18793. */
  18794. Node.prototype.isDescendantOf = function (ancestor) {
  18795. if (this.parent) {
  18796. if (this.parent === ancestor) {
  18797. return true;
  18798. }
  18799. return this.parent.isDescendantOf(ancestor);
  18800. }
  18801. return false;
  18802. };
  18803. /** @hidden */
  18804. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  18805. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  18806. if (!this._children) {
  18807. return;
  18808. }
  18809. for (var index = 0; index < this._children.length; index++) {
  18810. var item = this._children[index];
  18811. if (!predicate || predicate(item)) {
  18812. results.push(item);
  18813. }
  18814. if (!directDescendantsOnly) {
  18815. item._getDescendants(results, false, predicate);
  18816. }
  18817. }
  18818. };
  18819. /**
  18820. * Will return all nodes that have this node as ascendant
  18821. * @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
  18822. * @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
  18823. * @return all children nodes of all types
  18824. */
  18825. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  18826. var results = new Array();
  18827. this._getDescendants(results, directDescendantsOnly, predicate);
  18828. return results;
  18829. };
  18830. /**
  18831. * Get all child-meshes of this node
  18832. * @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
  18833. * @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
  18834. * @returns an array of AbstractMesh
  18835. */
  18836. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  18837. var results = [];
  18838. this._getDescendants(results, directDescendantsOnly, function (node) {
  18839. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  18840. });
  18841. return results;
  18842. };
  18843. /**
  18844. * Get all child-transformNodes of this node
  18845. * @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
  18846. * @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
  18847. * @returns an array of TransformNode
  18848. */
  18849. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  18850. var results = [];
  18851. this._getDescendants(results, directDescendantsOnly, function (node) {
  18852. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  18853. });
  18854. return results;
  18855. };
  18856. /**
  18857. * Get all direct children of this node
  18858. * @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
  18859. * @returns an array of Node
  18860. */
  18861. Node.prototype.getChildren = function (predicate) {
  18862. return this.getDescendants(true, predicate);
  18863. };
  18864. /** @hidden */
  18865. Node.prototype._setReady = function (state) {
  18866. if (state === this._isReady) {
  18867. return;
  18868. }
  18869. if (!state) {
  18870. this._isReady = false;
  18871. return;
  18872. }
  18873. if (this.onReady) {
  18874. this.onReady(this);
  18875. }
  18876. this._isReady = true;
  18877. };
  18878. /**
  18879. * Get an animation by name
  18880. * @param name defines the name of the animation to look for
  18881. * @returns null if not found else the requested animation
  18882. */
  18883. Node.prototype.getAnimationByName = function (name) {
  18884. for (var i = 0; i < this.animations.length; i++) {
  18885. var animation = this.animations[i];
  18886. if (animation.name === name) {
  18887. return animation;
  18888. }
  18889. }
  18890. return null;
  18891. };
  18892. /**
  18893. * Creates an animation range for this node
  18894. * @param name defines the name of the range
  18895. * @param from defines the starting key
  18896. * @param to defines the end key
  18897. */
  18898. Node.prototype.createAnimationRange = function (name, from, to) {
  18899. // check name not already in use
  18900. if (!this._ranges[name]) {
  18901. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18902. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18903. if (this.animations[i]) {
  18904. this.animations[i].createRange(name, from, to);
  18905. }
  18906. }
  18907. }
  18908. };
  18909. /**
  18910. * Delete a specific animation range
  18911. * @param name defines the name of the range to delete
  18912. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18913. */
  18914. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18915. if (deleteFrames === void 0) { deleteFrames = true; }
  18916. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18917. if (this.animations[i]) {
  18918. this.animations[i].deleteRange(name, deleteFrames);
  18919. }
  18920. }
  18921. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18922. };
  18923. /**
  18924. * Get an animation range by name
  18925. * @param name defines the name of the animation range to look for
  18926. * @returns null if not found else the requested animation range
  18927. */
  18928. Node.prototype.getAnimationRange = function (name) {
  18929. return this._ranges[name];
  18930. };
  18931. /**
  18932. * Will start the animation sequence
  18933. * @param name defines the range frames for animation sequence
  18934. * @param loop defines if the animation should loop (false by default)
  18935. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18936. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18937. * @returns the object created for this animation. If range does not exist, it will return null
  18938. */
  18939. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18940. var range = this.getAnimationRange(name);
  18941. if (!range) {
  18942. return null;
  18943. }
  18944. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18945. };
  18946. /**
  18947. * Serialize animation ranges into a JSON compatible object
  18948. * @returns serialization object
  18949. */
  18950. Node.prototype.serializeAnimationRanges = function () {
  18951. var serializationRanges = [];
  18952. for (var name in this._ranges) {
  18953. var localRange = this._ranges[name];
  18954. if (!localRange) {
  18955. continue;
  18956. }
  18957. var range = {};
  18958. range.name = name;
  18959. range.from = localRange.from;
  18960. range.to = localRange.to;
  18961. serializationRanges.push(range);
  18962. }
  18963. return serializationRanges;
  18964. };
  18965. /**
  18966. * Computes the world matrix of the node
  18967. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18968. * @returns the world matrix
  18969. */
  18970. Node.prototype.computeWorldMatrix = function (force) {
  18971. if (!this._worldMatrix) {
  18972. this._worldMatrix = BABYLON.Matrix.Identity();
  18973. }
  18974. return this._worldMatrix;
  18975. };
  18976. /**
  18977. * Releases resources associated with this node.
  18978. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18979. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18980. */
  18981. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18982. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18983. if (!doNotRecurse) {
  18984. var nodes = this.getDescendants(true);
  18985. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18986. var node = nodes_1[_i];
  18987. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18988. }
  18989. }
  18990. else {
  18991. var transformNodes = this.getChildTransformNodes(true);
  18992. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18993. var transformNode = transformNodes_1[_a];
  18994. transformNode.parent = null;
  18995. transformNode.computeWorldMatrix(true);
  18996. }
  18997. }
  18998. if (!this.parent) {
  18999. this.removeFromSceneRootNodes();
  19000. }
  19001. else {
  19002. this.parent = null;
  19003. }
  19004. // Callback
  19005. this.onDisposeObservable.notifyObservers(this);
  19006. this.onDisposeObservable.clear();
  19007. // Behaviors
  19008. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  19009. var behavior = _c[_b];
  19010. behavior.detach();
  19011. }
  19012. this._behaviors = [];
  19013. this._isDisposed = true;
  19014. };
  19015. /**
  19016. * Parse animation range data from a serialization object and store them into a given node
  19017. * @param node defines where to store the animation ranges
  19018. * @param parsedNode defines the serialization object to read data from
  19019. * @param scene defines the hosting scene
  19020. */
  19021. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  19022. if (parsedNode.ranges) {
  19023. for (var index = 0; index < parsedNode.ranges.length; index++) {
  19024. var data = parsedNode.ranges[index];
  19025. node.createAnimationRange(data.name, data.from, data.to);
  19026. }
  19027. }
  19028. };
  19029. Node._NodeConstructors = {};
  19030. __decorate([
  19031. BABYLON.serialize()
  19032. ], Node.prototype, "name", void 0);
  19033. __decorate([
  19034. BABYLON.serialize()
  19035. ], Node.prototype, "id", void 0);
  19036. __decorate([
  19037. BABYLON.serialize()
  19038. ], Node.prototype, "uniqueId", void 0);
  19039. __decorate([
  19040. BABYLON.serialize()
  19041. ], Node.prototype, "state", void 0);
  19042. __decorate([
  19043. BABYLON.serialize()
  19044. ], Node.prototype, "metadata", void 0);
  19045. return Node;
  19046. }());
  19047. BABYLON.Node = Node;
  19048. })(BABYLON || (BABYLON = {}));
  19049. //# sourceMappingURL=babylon.node.js.map
  19050. var BABYLON;
  19051. (function (BABYLON) {
  19052. // This matrix is used as a value to reset the bounding box.
  19053. var _identityMatrix = BABYLON.Matrix.Identity();
  19054. /**
  19055. * Class used to store bounding sphere information
  19056. */
  19057. var BoundingSphere = /** @class */ (function () {
  19058. /**
  19059. * Creates a new bounding sphere
  19060. * @param min defines the minimum vector (in local space)
  19061. * @param max defines the maximum vector (in local space)
  19062. */
  19063. function BoundingSphere(min, max) {
  19064. /**
  19065. * Gets the center of the bounding sphere in local space
  19066. */
  19067. this.center = BABYLON.Vector3.Zero();
  19068. /**
  19069. * Gets the center of the bounding sphere in world space
  19070. */
  19071. this.centerWorld = BABYLON.Vector3.Zero();
  19072. /**
  19073. * Gets the minimum vector in local space
  19074. */
  19075. this.minimum = BABYLON.Vector3.Zero();
  19076. /**
  19077. * Gets the maximum vector in local space
  19078. */
  19079. this.maximum = BABYLON.Vector3.Zero();
  19080. this.reConstruct(min, max);
  19081. }
  19082. /**
  19083. * Recreates the entire bounding sphere from scratch
  19084. * @param min defines the new minimum vector (in local space)
  19085. * @param max defines the new maximum vector (in local space)
  19086. */
  19087. BoundingSphere.prototype.reConstruct = function (min, max) {
  19088. this.minimum.copyFrom(min);
  19089. this.maximum.copyFrom(max);
  19090. var distance = BABYLON.Vector3.Distance(min, max);
  19091. BABYLON.Vector3.LerpToRef(min, max, 0.5, this.center);
  19092. this.radius = distance * 0.5;
  19093. this.centerWorld.set(0, 0, 0);
  19094. this._update(_identityMatrix);
  19095. };
  19096. /**
  19097. * Scale the current bounding sphere by applying a scale factor
  19098. * @param factor defines the scale factor to apply
  19099. * @returns the current bounding box
  19100. */
  19101. BoundingSphere.prototype.scale = function (factor) {
  19102. var newRadius = this.radius * factor;
  19103. var tempRadiusVector = BABYLON.Tmp.Vector3[0].set(newRadius, newRadius, newRadius);
  19104. var min = BABYLON.Tmp.Vector3[1].copyFrom(this.center).subtractInPlace(tempRadiusVector);
  19105. var max = BABYLON.Tmp.Vector3[2].copyFrom(this.center).addInPlace(tempRadiusVector);
  19106. this.reConstruct(min, max);
  19107. return this;
  19108. };
  19109. // Methods
  19110. /** @hidden */
  19111. BoundingSphere.prototype._update = function (world) {
  19112. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  19113. var tempVector = BABYLON.Tmp.Vector3[0];
  19114. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, tempVector);
  19115. this.radiusWorld = Math.max(Math.abs(tempVector.x), Math.abs(tempVector.y), Math.abs(tempVector.z)) * this.radius;
  19116. };
  19117. /**
  19118. * Tests if the bounding sphere is intersecting the frustum planes
  19119. * @param frustumPlanes defines the frustum planes to test
  19120. * @returns true if there is an intersection
  19121. */
  19122. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  19123. for (var i = 0; i < 6; i++) {
  19124. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld) {
  19125. return false;
  19126. }
  19127. }
  19128. return true;
  19129. };
  19130. /**
  19131. * Tests if a point is inside the bounding sphere
  19132. * @param point defines the point to test
  19133. * @returns true if the point is inside the bounding sphere
  19134. */
  19135. BoundingSphere.prototype.intersectsPoint = function (point) {
  19136. var x = this.centerWorld.x - point.x;
  19137. var y = this.centerWorld.y - point.y;
  19138. var z = this.centerWorld.z - point.z;
  19139. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  19140. if (this.radiusWorld < distance) {
  19141. return false;
  19142. }
  19143. return true;
  19144. };
  19145. // Statics
  19146. /**
  19147. * Checks if two sphere intersct
  19148. * @param sphere0 sphere 0
  19149. * @param sphere1 sphere 1
  19150. * @returns true if the speres intersect
  19151. */
  19152. BoundingSphere.Intersects = function (sphere0, sphere1) {
  19153. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  19154. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  19155. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  19156. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  19157. if (sphere0.radiusWorld + sphere1.radiusWorld < distance) {
  19158. return false;
  19159. }
  19160. return true;
  19161. };
  19162. return BoundingSphere;
  19163. }());
  19164. BABYLON.BoundingSphere = BoundingSphere;
  19165. })(BABYLON || (BABYLON = {}));
  19166. //# sourceMappingURL=babylon.boundingSphere.js.map
  19167. var BABYLON;
  19168. (function (BABYLON) {
  19169. /**
  19170. * Class used to store bounding box information
  19171. */
  19172. var BoundingBox = /** @class */ (function () {
  19173. /**
  19174. * Creates a new bounding box
  19175. * @param min defines the minimum vector (in local space)
  19176. * @param max defines the maximum vector (in local space)
  19177. */
  19178. function BoundingBox(min, max) {
  19179. /**
  19180. * Gets the 8 vectors representing the bounding box in local space
  19181. */
  19182. this.vectors = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  19183. /**
  19184. * Gets the center of the bounding box in local space
  19185. */
  19186. this.center = BABYLON.Vector3.Zero();
  19187. /**
  19188. * Gets the center of the bounding box in world space
  19189. */
  19190. this.centerWorld = BABYLON.Vector3.Zero();
  19191. /**
  19192. * Gets the extend size in local space
  19193. */
  19194. this.extendSize = BABYLON.Vector3.Zero();
  19195. /**
  19196. * Gets the extend size in world space
  19197. */
  19198. this.extendSizeWorld = BABYLON.Vector3.Zero();
  19199. /**
  19200. * Gets the OBB (object bounding box) directions
  19201. */
  19202. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  19203. /**
  19204. * Gets the 8 vectors representing the bounding box in world space
  19205. */
  19206. this.vectorsWorld = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  19207. /**
  19208. * Gets the minimum vector in world space
  19209. */
  19210. this.minimumWorld = BABYLON.Vector3.Zero();
  19211. /**
  19212. * Gets the maximum vector in world space
  19213. */
  19214. this.maximumWorld = BABYLON.Vector3.Zero();
  19215. /**
  19216. * Gets the minimum vector in local space
  19217. */
  19218. this.minimum = BABYLON.Vector3.Zero();
  19219. /**
  19220. * Gets the maximum vector in local space
  19221. */
  19222. this.maximum = BABYLON.Vector3.Zero();
  19223. this.reConstruct(min, max);
  19224. }
  19225. // Methods
  19226. /**
  19227. * Recreates the entire bounding box from scratch
  19228. * @param min defines the new minimum vector (in local space)
  19229. * @param max defines the new maximum vector (in local space)
  19230. */
  19231. BoundingBox.prototype.reConstruct = function (min, max) {
  19232. this.minimum.copyFrom(min);
  19233. this.maximum.copyFrom(max);
  19234. // Bounding vectors
  19235. this.vectors[0].copyFrom(this.minimum);
  19236. this.vectors[1].copyFrom(this.maximum);
  19237. this.vectors[2].copyFrom(this.minimum);
  19238. this.vectors[3].copyFrom(this.minimum);
  19239. this.vectors[4].copyFrom(this.minimum);
  19240. this.vectors[5].copyFrom(this.maximum);
  19241. this.vectors[6].copyFrom(this.maximum);
  19242. this.vectors[7].copyFrom(this.maximum);
  19243. this.vectors[2].x = this.maximum.x;
  19244. this.vectors[3].y = this.maximum.y;
  19245. this.vectors[4].z = this.maximum.z;
  19246. this.vectors[5].z = this.minimum.z;
  19247. this.vectors[6].x = this.minimum.x;
  19248. this.vectors[7].y = this.minimum.y;
  19249. // OBB
  19250. this.center.copyFrom(this.maximum).addInPlace(this.minimum).scaleInPlace(0.5);
  19251. this.extendSize.copyFrom(this.maximum).subtractInPlace(this.minimum).scaleInPlace(0.5);
  19252. for (var index = 0; index < 3; index++) {
  19253. this.directions[index].copyFromFloats(0, 0, 0);
  19254. }
  19255. // World
  19256. for (var index = 0; index < 8; index++) {
  19257. this.vectorsWorld[index].copyFromFloats(0, 0, 0);
  19258. }
  19259. this.minimumWorld.copyFromFloats(0, 0, 0);
  19260. this.maximumWorld.copyFromFloats(0, 0, 0);
  19261. this.centerWorld.copyFromFloats(0, 0, 0);
  19262. this.extendSizeWorld.copyFromFloats(0, 0, 0);
  19263. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  19264. };
  19265. /**
  19266. * Scale the current bounding box by applying a scale factor
  19267. * @param factor defines the scale factor to apply
  19268. * @returns the current bounding box
  19269. */
  19270. BoundingBox.prototype.scale = function (factor) {
  19271. var diff = BABYLON.Tmp.Vector3[0].copyFrom(this.maximum).subtractInPlace(this.minimum);
  19272. var distance = diff.length() * factor;
  19273. diff.normalize();
  19274. var newRadius = diff.scaleInPlace(distance * 0.5);
  19275. var min = BABYLON.Tmp.Vector3[1].copyFrom(this.center).subtractInPlace(newRadius);
  19276. var max = BABYLON.Tmp.Vector3[2].copyFrom(this.center).addInPlace(newRadius);
  19277. this.reConstruct(min, max);
  19278. return this;
  19279. };
  19280. /**
  19281. * Gets the world matrix of the bounding box
  19282. * @returns a matrix
  19283. */
  19284. BoundingBox.prototype.getWorldMatrix = function () {
  19285. return this._worldMatrix;
  19286. };
  19287. /**
  19288. * Sets the world matrix stored in the bounding box
  19289. * @param matrix defines the matrix to store
  19290. * @returns current bounding box
  19291. */
  19292. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  19293. this._worldMatrix.copyFrom(matrix);
  19294. return this;
  19295. };
  19296. /** @hidden */
  19297. BoundingBox.prototype._update = function (world) {
  19298. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  19299. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  19300. for (var index = 0; index < 8; index++) {
  19301. var v = this.vectorsWorld[index];
  19302. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  19303. this.minimumWorld.minimizeInPlace(v);
  19304. this.maximumWorld.maximizeInPlace(v);
  19305. }
  19306. // Extend
  19307. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  19308. this.extendSizeWorld.scaleInPlace(0.5);
  19309. // OBB
  19310. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  19311. this.centerWorld.scaleInPlace(0.5);
  19312. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  19313. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  19314. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  19315. this._worldMatrix = world;
  19316. };
  19317. /**
  19318. * Tests if the bounding box is intersecting the frustum planes
  19319. * @param frustumPlanes defines the frustum planes to test
  19320. * @returns true if there is an intersection
  19321. */
  19322. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  19323. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  19324. };
  19325. /**
  19326. * Tests if the bounding box is entirely inside the frustum planes
  19327. * @param frustumPlanes defines the frustum planes to test
  19328. * @returns true if there is an inclusion
  19329. */
  19330. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  19331. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  19332. };
  19333. /**
  19334. * Tests if a point is inside the bounding box
  19335. * @param point defines the point to test
  19336. * @returns true if the point is inside the bounding box
  19337. */
  19338. BoundingBox.prototype.intersectsPoint = function (point) {
  19339. var delta = -BABYLON.Epsilon;
  19340. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x) {
  19341. return false;
  19342. }
  19343. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y) {
  19344. return false;
  19345. }
  19346. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z) {
  19347. return false;
  19348. }
  19349. return true;
  19350. };
  19351. /**
  19352. * Tests if the bounding box intersects with a bounding sphere
  19353. * @param sphere defines the sphere to test
  19354. * @returns true if there is an intersection
  19355. */
  19356. BoundingBox.prototype.intersectsSphere = function (sphere) {
  19357. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  19358. };
  19359. /**
  19360. * Tests if the bounding box intersects with a box defined by a min and max vectors
  19361. * @param min defines the min vector to use
  19362. * @param max defines the max vector to use
  19363. * @returns true if there is an intersection
  19364. */
  19365. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  19366. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x) {
  19367. return false;
  19368. }
  19369. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y) {
  19370. return false;
  19371. }
  19372. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z) {
  19373. return false;
  19374. }
  19375. return true;
  19376. };
  19377. // Statics
  19378. /**
  19379. * Tests if two bounding boxes are intersections
  19380. * @param box0 defines the first box to test
  19381. * @param box1 defines the second box to test
  19382. * @returns true if there is an intersection
  19383. */
  19384. BoundingBox.Intersects = function (box0, box1) {
  19385. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x) {
  19386. return false;
  19387. }
  19388. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y) {
  19389. return false;
  19390. }
  19391. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z) {
  19392. return false;
  19393. }
  19394. return true;
  19395. };
  19396. /**
  19397. * Tests if a bounding box defines by a min/max vectors intersects a sphere
  19398. * @param minPoint defines the minimum vector of the bounding box
  19399. * @param maxPoint defines the maximum vector of the bounding box
  19400. * @param sphereCenter defines the sphere center
  19401. * @param sphereRadius defines the sphere radius
  19402. * @returns true if there is an intersection
  19403. */
  19404. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  19405. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  19406. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  19407. return (num <= (sphereRadius * sphereRadius));
  19408. };
  19409. /**
  19410. * Tests if a bounding box defined with 8 vectors is entirely inside frustum planes
  19411. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  19412. * @param frustumPlanes defines the frustum planes to test
  19413. * @return true if there is an inclusion
  19414. */
  19415. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  19416. for (var p = 0; p < 6; p++) {
  19417. for (var i = 0; i < 8; i++) {
  19418. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  19419. return false;
  19420. }
  19421. }
  19422. }
  19423. return true;
  19424. };
  19425. /**
  19426. * Tests if a bounding box defined with 8 vectors intersects frustum planes
  19427. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  19428. * @param frustumPlanes defines the frustum planes to test
  19429. * @return true if there is an intersection
  19430. */
  19431. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  19432. for (var p = 0; p < 6; p++) {
  19433. var inCount = 8;
  19434. for (var i = 0; i < 8; i++) {
  19435. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  19436. --inCount;
  19437. }
  19438. else {
  19439. break;
  19440. }
  19441. }
  19442. if (inCount === 0) {
  19443. return false;
  19444. }
  19445. }
  19446. return true;
  19447. };
  19448. return BoundingBox;
  19449. }());
  19450. BABYLON.BoundingBox = BoundingBox;
  19451. })(BABYLON || (BABYLON = {}));
  19452. //# sourceMappingURL=babylon.boundingBox.js.map
  19453. var BABYLON;
  19454. (function (BABYLON) {
  19455. var computeBoxExtents = function (axis, box) {
  19456. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  19457. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  19458. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  19459. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  19460. var r = r0 + r1 + r2;
  19461. return {
  19462. min: p - r,
  19463. max: p + r
  19464. };
  19465. };
  19466. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  19467. var axisOverlap = function (axis, box0, box1) {
  19468. var result0 = computeBoxExtents(axis, box0);
  19469. var result1 = computeBoxExtents(axis, box1);
  19470. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  19471. };
  19472. /**
  19473. * Info for a bounding data of a mesh
  19474. */
  19475. var BoundingInfo = /** @class */ (function () {
  19476. /**
  19477. * Constructs bounding info
  19478. * @param minimum min vector of the bounding box/sphere
  19479. * @param maximum max vector of the bounding box/sphere
  19480. */
  19481. function BoundingInfo(minimum, maximum) {
  19482. this._isLocked = false;
  19483. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  19484. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  19485. }
  19486. Object.defineProperty(BoundingInfo.prototype, "minimum", {
  19487. /**
  19488. * min vector of the bounding box/sphere
  19489. */
  19490. get: function () {
  19491. return this.boundingBox.minimum;
  19492. },
  19493. enumerable: true,
  19494. configurable: true
  19495. });
  19496. Object.defineProperty(BoundingInfo.prototype, "maximum", {
  19497. /**
  19498. * max vector of the bounding box/sphere
  19499. */
  19500. get: function () {
  19501. return this.boundingBox.maximum;
  19502. },
  19503. enumerable: true,
  19504. configurable: true
  19505. });
  19506. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  19507. /**
  19508. * If the info is locked and won't be updated to avoid perf overhead
  19509. */
  19510. get: function () {
  19511. return this._isLocked;
  19512. },
  19513. set: function (value) {
  19514. this._isLocked = value;
  19515. },
  19516. enumerable: true,
  19517. configurable: true
  19518. });
  19519. // Methods
  19520. /**
  19521. * Updates the boudning sphere and box
  19522. * @param world world matrix to be used to update
  19523. */
  19524. BoundingInfo.prototype.update = function (world) {
  19525. if (this._isLocked) {
  19526. return;
  19527. }
  19528. this.boundingBox._update(world);
  19529. this.boundingSphere._update(world);
  19530. };
  19531. /**
  19532. * Recreate the bounding info to be centered around a specific point given a specific extend.
  19533. * @param center New center of the bounding info
  19534. * @param extend New extend of the bounding info
  19535. * @returns the current bounding info
  19536. */
  19537. BoundingInfo.prototype.centerOn = function (center, extend) {
  19538. var minimum = BABYLON.Tmp.Vector3[0].copyFrom(center).subtractInPlace(extend);
  19539. var maximum = BABYLON.Tmp.Vector3[1].copyFrom(center).addInPlace(extend);
  19540. this.boundingBox.reConstruct(minimum, maximum);
  19541. this.boundingSphere.reConstruct(minimum, maximum);
  19542. return this;
  19543. };
  19544. /**
  19545. * Scale the current bounding info by applying a scale factor
  19546. * @param factor defines the scale factor to apply
  19547. * @returns the current bounding info
  19548. */
  19549. BoundingInfo.prototype.scale = function (factor) {
  19550. this.boundingBox.scale(factor);
  19551. this.boundingSphere.scale(factor);
  19552. return this;
  19553. };
  19554. /**
  19555. * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.
  19556. * @param frustumPlanes defines the frustum to test
  19557. * @param strategy defines the strategy to use for the culling (default is BABYLON.Scene.CULLINGSTRATEGY_STANDARD)
  19558. * @returns true if the bounding info is in the frustum planes
  19559. */
  19560. BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) {
  19561. if (strategy === void 0) { strategy = BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD; }
  19562. if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
  19563. return false;
  19564. }
  19565. if (strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY) {
  19566. return true;
  19567. }
  19568. return this.boundingBox.isInFrustum(frustumPlanes);
  19569. };
  19570. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  19571. /**
  19572. * Gets the world distance between the min and max points of the bounding box
  19573. */
  19574. get: function () {
  19575. var boundingBox = this.boundingBox;
  19576. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  19577. return size.length();
  19578. },
  19579. enumerable: true,
  19580. configurable: true
  19581. });
  19582. /**
  19583. * Checks if a cullable object (mesh...) is in the camera frustum
  19584. * Unlike isInFrustum this cheks the full bounding box
  19585. * @param frustumPlanes Camera near/planes
  19586. * @returns true if the object is in frustum otherwise false
  19587. */
  19588. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  19589. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  19590. };
  19591. /** @hidden */
  19592. BoundingInfo.prototype._checkCollision = function (collider) {
  19593. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  19594. };
  19595. /**
  19596. * Checks if a point is inside the bounding box and bounding sphere or the mesh
  19597. * @see https://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  19598. * @param point the point to check intersection with
  19599. * @returns if the point intersects
  19600. */
  19601. BoundingInfo.prototype.intersectsPoint = function (point) {
  19602. if (!this.boundingSphere.centerWorld) {
  19603. return false;
  19604. }
  19605. if (!this.boundingSphere.intersectsPoint(point)) {
  19606. return false;
  19607. }
  19608. if (!this.boundingBox.intersectsPoint(point)) {
  19609. return false;
  19610. }
  19611. return true;
  19612. };
  19613. /**
  19614. * Checks if another bounding info intersects the bounding box and bounding sphere or the mesh
  19615. * @see https://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  19616. * @param boundingInfo the bounding info to check intersection with
  19617. * @param precise if the intersection should be done using OBB
  19618. * @returns if the bounding info intersects
  19619. */
  19620. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  19621. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  19622. return false;
  19623. }
  19624. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  19625. return false;
  19626. }
  19627. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  19628. return false;
  19629. }
  19630. if (!precise) {
  19631. return true;
  19632. }
  19633. var box0 = this.boundingBox;
  19634. var box1 = boundingInfo.boundingBox;
  19635. if (!axisOverlap(box0.directions[0], box0, box1)) {
  19636. return false;
  19637. }
  19638. if (!axisOverlap(box0.directions[1], box0, box1)) {
  19639. return false;
  19640. }
  19641. if (!axisOverlap(box0.directions[2], box0, box1)) {
  19642. return false;
  19643. }
  19644. if (!axisOverlap(box1.directions[0], box0, box1)) {
  19645. return false;
  19646. }
  19647. if (!axisOverlap(box1.directions[1], box0, box1)) {
  19648. return false;
  19649. }
  19650. if (!axisOverlap(box1.directions[2], box0, box1)) {
  19651. return false;
  19652. }
  19653. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1)) {
  19654. return false;
  19655. }
  19656. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1)) {
  19657. return false;
  19658. }
  19659. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1)) {
  19660. return false;
  19661. }
  19662. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1)) {
  19663. return false;
  19664. }
  19665. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1)) {
  19666. return false;
  19667. }
  19668. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1)) {
  19669. return false;
  19670. }
  19671. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1)) {
  19672. return false;
  19673. }
  19674. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1)) {
  19675. return false;
  19676. }
  19677. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1)) {
  19678. return false;
  19679. }
  19680. return true;
  19681. };
  19682. return BoundingInfo;
  19683. }());
  19684. BABYLON.BoundingInfo = BoundingInfo;
  19685. })(BABYLON || (BABYLON = {}));
  19686. //# sourceMappingURL=babylon.boundingInfo.js.map
  19687. var BABYLON;
  19688. (function (BABYLON) {
  19689. /**
  19690. * 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.
  19691. * @see https://doc.babylonjs.com/how_to/transformnode
  19692. */
  19693. var TransformNode = /** @class */ (function (_super) {
  19694. __extends(TransformNode, _super);
  19695. function TransformNode(name, scene, isPure) {
  19696. if (scene === void 0) { scene = null; }
  19697. if (isPure === void 0) { isPure = true; }
  19698. var _this = _super.call(this, name, scene) || this;
  19699. _this._forward = new BABYLON.Vector3(0, 0, 1);
  19700. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  19701. _this._up = new BABYLON.Vector3(0, 1, 0);
  19702. _this._right = new BABYLON.Vector3(1, 0, 0);
  19703. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  19704. // Properties
  19705. _this._position = BABYLON.Vector3.Zero();
  19706. _this._rotation = BABYLON.Vector3.Zero();
  19707. _this._scaling = BABYLON.Vector3.One();
  19708. _this._isDirty = false;
  19709. /**
  19710. * Set the billboard mode. Default is 0.
  19711. *
  19712. * | Value | Type | Description |
  19713. * | --- | --- | --- |
  19714. * | 0 | BILLBOARDMODE_NONE | |
  19715. * | 1 | BILLBOARDMODE_X | |
  19716. * | 2 | BILLBOARDMODE_Y | |
  19717. * | 4 | BILLBOARDMODE_Z | |
  19718. * | 7 | BILLBOARDMODE_ALL | |
  19719. *
  19720. */
  19721. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  19722. /**
  19723. * 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
  19724. */
  19725. _this.scalingDeterminant = 1;
  19726. /**
  19727. * Sets the distance of the object to max, often used by skybox
  19728. */
  19729. _this.infiniteDistance = false;
  19730. /**
  19731. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  19732. * By default the system will update normals to compensate
  19733. */
  19734. _this.ignoreNonUniformScaling = false;
  19735. _this._localWorld = BABYLON.Matrix.Zero();
  19736. _this._absolutePosition = BABYLON.Vector3.Zero();
  19737. _this._pivotMatrix = BABYLON.Matrix.Identity();
  19738. _this._postMultiplyPivotMatrix = false;
  19739. _this._isWorldMatrixFrozen = false;
  19740. /**
  19741. * An event triggered after the world matrix is updated
  19742. */
  19743. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  19744. _this._nonUniformScaling = false;
  19745. if (isPure) {
  19746. _this.getScene().addTransformNode(_this);
  19747. }
  19748. return _this;
  19749. }
  19750. /**
  19751. * Gets a string identifying the name of the class
  19752. * @returns "TransformNode" string
  19753. */
  19754. TransformNode.prototype.getClassName = function () {
  19755. return "TransformNode";
  19756. };
  19757. Object.defineProperty(TransformNode.prototype, "position", {
  19758. /**
  19759. * Gets or set the node position (default is (0.0, 0.0, 0.0))
  19760. */
  19761. get: function () {
  19762. return this._position;
  19763. },
  19764. set: function (newPosition) {
  19765. this._position = newPosition;
  19766. this._isDirty = true;
  19767. },
  19768. enumerable: true,
  19769. configurable: true
  19770. });
  19771. Object.defineProperty(TransformNode.prototype, "rotation", {
  19772. /**
  19773. * 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)).
  19774. * If rotation quaternion is set, this Vector3 will be ignored and copy from the quaternion
  19775. */
  19776. get: function () {
  19777. return this._rotation;
  19778. },
  19779. set: function (newRotation) {
  19780. this._rotation = newRotation;
  19781. this._isDirty = true;
  19782. },
  19783. enumerable: true,
  19784. configurable: true
  19785. });
  19786. Object.defineProperty(TransformNode.prototype, "scaling", {
  19787. /**
  19788. * 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)).
  19789. */
  19790. get: function () {
  19791. return this._scaling;
  19792. },
  19793. set: function (newScaling) {
  19794. this._scaling = newScaling;
  19795. this._isDirty = true;
  19796. },
  19797. enumerable: true,
  19798. configurable: true
  19799. });
  19800. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  19801. /**
  19802. * Gets or sets the rotation Quaternion property : this a Quaternion object defining the node rotation by using a unit quaternion (null by default).
  19803. * If set, only the rotationQuaternion is then used to compute the node rotation (ie. node.rotation will be ignored)
  19804. */
  19805. get: function () {
  19806. return this._rotationQuaternion;
  19807. },
  19808. set: function (quaternion) {
  19809. this._rotationQuaternion = quaternion;
  19810. //reset the rotation vector.
  19811. if (quaternion && this.rotation.length()) {
  19812. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  19813. }
  19814. },
  19815. enumerable: true,
  19816. configurable: true
  19817. });
  19818. Object.defineProperty(TransformNode.prototype, "forward", {
  19819. /**
  19820. * The forward direction of that transform in world space.
  19821. */
  19822. get: function () {
  19823. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  19824. },
  19825. enumerable: true,
  19826. configurable: true
  19827. });
  19828. Object.defineProperty(TransformNode.prototype, "up", {
  19829. /**
  19830. * The up direction of that transform in world space.
  19831. */
  19832. get: function () {
  19833. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  19834. },
  19835. enumerable: true,
  19836. configurable: true
  19837. });
  19838. Object.defineProperty(TransformNode.prototype, "right", {
  19839. /**
  19840. * The right direction of that transform in world space.
  19841. */
  19842. get: function () {
  19843. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  19844. },
  19845. enumerable: true,
  19846. configurable: true
  19847. });
  19848. /**
  19849. * Copies the parameter passed Matrix into the mesh Pose matrix.
  19850. * @param matrix the matrix to copy the pose from
  19851. * @returns this TransformNode.
  19852. */
  19853. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  19854. this._poseMatrix.copyFrom(matrix);
  19855. return this;
  19856. };
  19857. /**
  19858. * Returns the mesh Pose matrix.
  19859. * @returns the pose matrix
  19860. */
  19861. TransformNode.prototype.getPoseMatrix = function () {
  19862. return this._poseMatrix;
  19863. };
  19864. /** @hidden */
  19865. TransformNode.prototype._isSynchronized = function () {
  19866. if (this._isDirty) {
  19867. return false;
  19868. }
  19869. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19870. return false;
  19871. }
  19872. if (this._cache.pivotMatrixUpdated) {
  19873. return false;
  19874. }
  19875. if (this.infiniteDistance) {
  19876. return false;
  19877. }
  19878. if (!this._cache.position.equals(this._position)) {
  19879. return false;
  19880. }
  19881. if (this._rotationQuaternion) {
  19882. if (!this._cache.rotationQuaternion.equals(this._rotationQuaternion)) {
  19883. return false;
  19884. }
  19885. }
  19886. if (!this._cache.rotation.equals(this._rotation)) {
  19887. return false;
  19888. }
  19889. if (!this._cache.scaling.equals(this._scaling)) {
  19890. return false;
  19891. }
  19892. return true;
  19893. };
  19894. /** @hidden */
  19895. TransformNode.prototype._initCache = function () {
  19896. _super.prototype._initCache.call(this);
  19897. this._cache.localMatrixUpdated = false;
  19898. this._cache.position = BABYLON.Vector3.Zero();
  19899. this._cache.scaling = BABYLON.Vector3.Zero();
  19900. this._cache.rotation = BABYLON.Vector3.Zero();
  19901. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  19902. this._cache.billboardMode = -1;
  19903. };
  19904. /**
  19905. * Flag the transform node as dirty (Forcing it to update everything)
  19906. * @param property if set to "rotation" the objects rotationQuaternion will be set to null
  19907. * @returns this transform node
  19908. */
  19909. TransformNode.prototype.markAsDirty = function (property) {
  19910. if (property === "rotation") {
  19911. this.rotationQuaternion = null;
  19912. }
  19913. this._currentRenderId = Number.MAX_VALUE;
  19914. this._isDirty = true;
  19915. return this;
  19916. };
  19917. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  19918. /**
  19919. * Returns the current mesh absolute position.
  19920. * Returns a Vector3.
  19921. */
  19922. get: function () {
  19923. return this._absolutePosition;
  19924. },
  19925. enumerable: true,
  19926. configurable: true
  19927. });
  19928. /**
  19929. * Sets a new matrix to apply before all other transformation
  19930. * @param matrix defines the transform matrix
  19931. * @returns the current TransformNode
  19932. */
  19933. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  19934. return this.setPivotMatrix(matrix, false);
  19935. };
  19936. /**
  19937. * Sets a new pivot matrix to the current node
  19938. * @param matrix defines the new pivot matrix to use
  19939. * @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
  19940. * @returns the current TransformNode
  19941. */
  19942. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  19943. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  19944. this._pivotMatrix = matrix.clone();
  19945. this._cache.pivotMatrixUpdated = true;
  19946. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  19947. if (this._postMultiplyPivotMatrix) {
  19948. if (!this._pivotMatrixInverse) {
  19949. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  19950. }
  19951. else {
  19952. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  19953. }
  19954. }
  19955. return this;
  19956. };
  19957. /**
  19958. * Returns the mesh pivot matrix.
  19959. * Default : Identity.
  19960. * @returns the matrix
  19961. */
  19962. TransformNode.prototype.getPivotMatrix = function () {
  19963. return this._pivotMatrix;
  19964. };
  19965. /**
  19966. * Prevents the World matrix to be computed any longer.
  19967. * @returns the TransformNode.
  19968. */
  19969. TransformNode.prototype.freezeWorldMatrix = function () {
  19970. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  19971. this.computeWorldMatrix(true);
  19972. this._isWorldMatrixFrozen = true;
  19973. return this;
  19974. };
  19975. /**
  19976. * Allows back the World matrix computation.
  19977. * @returns the TransformNode.
  19978. */
  19979. TransformNode.prototype.unfreezeWorldMatrix = function () {
  19980. this._isWorldMatrixFrozen = false;
  19981. this.computeWorldMatrix(true);
  19982. return this;
  19983. };
  19984. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  19985. /**
  19986. * True if the World matrix has been frozen.
  19987. */
  19988. get: function () {
  19989. return this._isWorldMatrixFrozen;
  19990. },
  19991. enumerable: true,
  19992. configurable: true
  19993. });
  19994. /**
  19995. * Retuns the mesh absolute position in the World.
  19996. * @returns a Vector3.
  19997. */
  19998. TransformNode.prototype.getAbsolutePosition = function () {
  19999. this.computeWorldMatrix();
  20000. return this._absolutePosition;
  20001. };
  20002. /**
  20003. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  20004. * @param absolutePosition the absolute position to set
  20005. * @returns the TransformNode.
  20006. */
  20007. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  20008. if (!absolutePosition) {
  20009. return this;
  20010. }
  20011. var absolutePositionX;
  20012. var absolutePositionY;
  20013. var absolutePositionZ;
  20014. if (absolutePosition.x === undefined) {
  20015. if (arguments.length < 3) {
  20016. return this;
  20017. }
  20018. absolutePositionX = arguments[0];
  20019. absolutePositionY = arguments[1];
  20020. absolutePositionZ = arguments[2];
  20021. }
  20022. else {
  20023. absolutePositionX = absolutePosition.x;
  20024. absolutePositionY = absolutePosition.y;
  20025. absolutePositionZ = absolutePosition.z;
  20026. }
  20027. if (this.parent) {
  20028. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  20029. invertParentWorldMatrix.invert();
  20030. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  20031. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  20032. }
  20033. else {
  20034. this.position.x = absolutePositionX;
  20035. this.position.y = absolutePositionY;
  20036. this.position.z = absolutePositionZ;
  20037. }
  20038. return this;
  20039. };
  20040. /**
  20041. * Sets the mesh position in its local space.
  20042. * @param vector3 the position to set in localspace
  20043. * @returns the TransformNode.
  20044. */
  20045. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  20046. this.computeWorldMatrix();
  20047. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  20048. return this;
  20049. };
  20050. /**
  20051. * Returns the mesh position in the local space from the current World matrix values.
  20052. * @returns a new Vector3.
  20053. */
  20054. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  20055. this.computeWorldMatrix();
  20056. var invLocalWorldMatrix = this._localWorld.clone();
  20057. invLocalWorldMatrix.invert();
  20058. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  20059. };
  20060. /**
  20061. * Translates the mesh along the passed Vector3 in its local space.
  20062. * @param vector3 the distance to translate in localspace
  20063. * @returns the TransformNode.
  20064. */
  20065. TransformNode.prototype.locallyTranslate = function (vector3) {
  20066. this.computeWorldMatrix(true);
  20067. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  20068. return this;
  20069. };
  20070. /**
  20071. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  20072. * @param targetPoint the position (must be in same space as current mesh) to look at
  20073. * @param yawCor optional yaw (y-axis) correction in radians
  20074. * @param pitchCor optional pitch (x-axis) correction in radians
  20075. * @param rollCor optional roll (z-axis) correction in radians
  20076. * @param space the choosen space of the target
  20077. * @returns the TransformNode.
  20078. */
  20079. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  20080. if (yawCor === void 0) { yawCor = 0; }
  20081. if (pitchCor === void 0) { pitchCor = 0; }
  20082. if (rollCor === void 0) { rollCor = 0; }
  20083. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  20084. var dv = TransformNode._lookAtVectorCache;
  20085. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  20086. targetPoint.subtractToRef(pos, dv);
  20087. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  20088. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  20089. var pitch = Math.atan2(dv.y, len);
  20090. if (this.rotationQuaternion) {
  20091. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  20092. }
  20093. else {
  20094. this.rotation.x = pitch + pitchCor;
  20095. this.rotation.y = yaw + yawCor;
  20096. this.rotation.z = rollCor;
  20097. }
  20098. return this;
  20099. };
  20100. /**
  20101. * Returns a new Vector3 that is the localAxis, expressed in the mesh local space, rotated like the mesh.
  20102. * This Vector3 is expressed in the World space.
  20103. * @param localAxis axis to rotate
  20104. * @returns a new Vector3 that is the localAxis, expressed in the mesh local space, rotated like the mesh.
  20105. */
  20106. TransformNode.prototype.getDirection = function (localAxis) {
  20107. var result = BABYLON.Vector3.Zero();
  20108. this.getDirectionToRef(localAxis, result);
  20109. return result;
  20110. };
  20111. /**
  20112. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  20113. * localAxis is expressed in the mesh local space.
  20114. * result is computed in the Wordl space from the mesh World matrix.
  20115. * @param localAxis axis to rotate
  20116. * @param result the resulting transformnode
  20117. * @returns this TransformNode.
  20118. */
  20119. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  20120. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20121. return this;
  20122. };
  20123. /**
  20124. * Sets a new pivot point to the current node
  20125. * @param point defines the new pivot point to use
  20126. * @param space defines if the point is in world or local space (local by default)
  20127. * @returns the current TransformNode
  20128. */
  20129. TransformNode.prototype.setPivotPoint = function (point, space) {
  20130. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  20131. if (this.getScene().getRenderId() == 0) {
  20132. this.computeWorldMatrix(true);
  20133. }
  20134. var wm = this.getWorldMatrix();
  20135. if (space == BABYLON.Space.WORLD) {
  20136. var tmat = BABYLON.Tmp.Matrix[0];
  20137. wm.invertToRef(tmat);
  20138. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  20139. }
  20140. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  20141. };
  20142. /**
  20143. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  20144. * @returns the pivot point
  20145. */
  20146. TransformNode.prototype.getPivotPoint = function () {
  20147. var point = BABYLON.Vector3.Zero();
  20148. this.getPivotPointToRef(point);
  20149. return point;
  20150. };
  20151. /**
  20152. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  20153. * @param result the vector3 to store the result
  20154. * @returns this TransformNode.
  20155. */
  20156. TransformNode.prototype.getPivotPointToRef = function (result) {
  20157. result.x = -this._pivotMatrix.m[12];
  20158. result.y = -this._pivotMatrix.m[13];
  20159. result.z = -this._pivotMatrix.m[14];
  20160. return this;
  20161. };
  20162. /**
  20163. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  20164. * @returns a new Vector3 set with the mesh pivot point World coordinates.
  20165. */
  20166. TransformNode.prototype.getAbsolutePivotPoint = function () {
  20167. var point = BABYLON.Vector3.Zero();
  20168. this.getAbsolutePivotPointToRef(point);
  20169. return point;
  20170. };
  20171. /**
  20172. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  20173. * @param result vector3 to store the result
  20174. * @returns this TransformNode.
  20175. */
  20176. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  20177. result.x = this._pivotMatrix.m[12];
  20178. result.y = this._pivotMatrix.m[13];
  20179. result.z = this._pivotMatrix.m[14];
  20180. this.getPivotPointToRef(result);
  20181. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  20182. return this;
  20183. };
  20184. /**
  20185. * Defines the passed node as the parent of the current node.
  20186. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  20187. * @param node the node ot set as the parent
  20188. * @returns this TransformNode.
  20189. */
  20190. TransformNode.prototype.setParent = function (node) {
  20191. if (!node && !this.parent) {
  20192. return this;
  20193. }
  20194. if (!node) {
  20195. var rotation = BABYLON.Tmp.Quaternion[0];
  20196. var position = BABYLON.Tmp.Vector3[0];
  20197. var scale = BABYLON.Tmp.Vector3[1];
  20198. if (this.parent && this.parent.computeWorldMatrix) {
  20199. this.parent.computeWorldMatrix(true);
  20200. }
  20201. this.computeWorldMatrix(true);
  20202. this.getWorldMatrix().decompose(scale, rotation, position);
  20203. if (this.rotationQuaternion) {
  20204. this.rotationQuaternion.copyFrom(rotation);
  20205. }
  20206. else {
  20207. rotation.toEulerAnglesToRef(this.rotation);
  20208. }
  20209. this.scaling.x = scale.x;
  20210. this.scaling.y = scale.y;
  20211. this.scaling.z = scale.z;
  20212. this.position.x = position.x;
  20213. this.position.y = position.y;
  20214. this.position.z = position.z;
  20215. }
  20216. else {
  20217. var rotation = BABYLON.Tmp.Quaternion[0];
  20218. var position = BABYLON.Tmp.Vector3[0];
  20219. var scale = BABYLON.Tmp.Vector3[1];
  20220. var diffMatrix = BABYLON.Tmp.Matrix[0];
  20221. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  20222. this.computeWorldMatrix(true);
  20223. node.computeWorldMatrix(true);
  20224. node.getWorldMatrix().invertToRef(invParentMatrix);
  20225. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  20226. diffMatrix.decompose(scale, rotation, position);
  20227. if (this.rotationQuaternion) {
  20228. this.rotationQuaternion.copyFrom(rotation);
  20229. }
  20230. else {
  20231. rotation.toEulerAnglesToRef(this.rotation);
  20232. }
  20233. this.position.x = position.x;
  20234. this.position.y = position.y;
  20235. this.position.z = position.z;
  20236. this.scaling.x = scale.x;
  20237. this.scaling.y = scale.y;
  20238. this.scaling.z = scale.z;
  20239. }
  20240. this.parent = node;
  20241. return this;
  20242. };
  20243. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  20244. /**
  20245. * True if the scaling property of this object is non uniform eg. (1,2,1)
  20246. */
  20247. get: function () {
  20248. return this._nonUniformScaling;
  20249. },
  20250. enumerable: true,
  20251. configurable: true
  20252. });
  20253. /** @hidden */
  20254. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  20255. if (this._nonUniformScaling === value) {
  20256. return false;
  20257. }
  20258. this._nonUniformScaling = value;
  20259. return true;
  20260. };
  20261. /**
  20262. * Attach the current TransformNode to another TransformNode associated with a bone
  20263. * @param bone Bone affecting the TransformNode
  20264. * @param affectedTransformNode TransformNode associated with the bone
  20265. * @returns this object
  20266. */
  20267. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  20268. this._transformToBoneReferal = affectedTransformNode;
  20269. this.parent = bone;
  20270. if (bone.getWorldMatrix().determinant() < 0) {
  20271. this.scalingDeterminant *= -1;
  20272. }
  20273. return this;
  20274. };
  20275. /**
  20276. * Detach the transform node if its associated with a bone
  20277. * @returns this object
  20278. */
  20279. TransformNode.prototype.detachFromBone = function () {
  20280. if (!this.parent) {
  20281. return this;
  20282. }
  20283. if (this.parent.getWorldMatrix().determinant() < 0) {
  20284. this.scalingDeterminant *= -1;
  20285. }
  20286. this._transformToBoneReferal = null;
  20287. this.parent = null;
  20288. return this;
  20289. };
  20290. /**
  20291. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  20292. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  20293. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  20294. * The passed axis is also normalized.
  20295. * @param axis the axis to rotate around
  20296. * @param amount the amount to rotate in radians
  20297. * @param space Space to rotate in (Default: local)
  20298. * @returns the TransformNode.
  20299. */
  20300. TransformNode.prototype.rotate = function (axis, amount, space) {
  20301. axis.normalize();
  20302. if (!this.rotationQuaternion) {
  20303. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20304. this.rotation = BABYLON.Vector3.Zero();
  20305. }
  20306. var rotationQuaternion;
  20307. if (!space || space === BABYLON.Space.LOCAL) {
  20308. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  20309. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  20310. }
  20311. else {
  20312. if (this.parent) {
  20313. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  20314. invertParentWorldMatrix.invert();
  20315. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  20316. }
  20317. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  20318. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  20319. }
  20320. return this;
  20321. };
  20322. /**
  20323. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  20324. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  20325. * The passed axis is also normalized. .
  20326. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  20327. * @param point the point to rotate around
  20328. * @param axis the axis to rotate around
  20329. * @param amount the amount to rotate in radians
  20330. * @returns the TransformNode
  20331. */
  20332. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  20333. axis.normalize();
  20334. if (!this.rotationQuaternion) {
  20335. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20336. this.rotation.copyFromFloats(0, 0, 0);
  20337. }
  20338. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  20339. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  20340. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  20341. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  20342. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  20343. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  20344. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  20345. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  20346. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  20347. return this;
  20348. };
  20349. /**
  20350. * Translates the mesh along the axis vector for the passed distance in the given space.
  20351. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  20352. * @param axis the axis to translate in
  20353. * @param distance the distance to translate
  20354. * @param space Space to rotate in (Default: local)
  20355. * @returns the TransformNode.
  20356. */
  20357. TransformNode.prototype.translate = function (axis, distance, space) {
  20358. var displacementVector = axis.scale(distance);
  20359. if (!space || space === BABYLON.Space.LOCAL) {
  20360. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  20361. this.setPositionWithLocalVector(tempV3);
  20362. }
  20363. else {
  20364. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  20365. }
  20366. return this;
  20367. };
  20368. /**
  20369. * Adds a rotation step to the mesh current rotation.
  20370. * x, y, z are Euler angles expressed in radians.
  20371. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  20372. * This means this rotation is made in the mesh local space only.
  20373. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  20374. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  20375. * ```javascript
  20376. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  20377. * ```
  20378. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  20379. * 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.
  20380. * @param x Rotation to add
  20381. * @param y Rotation to add
  20382. * @param z Rotation to add
  20383. * @returns the TransformNode.
  20384. */
  20385. TransformNode.prototype.addRotation = function (x, y, z) {
  20386. var rotationQuaternion;
  20387. if (this.rotationQuaternion) {
  20388. rotationQuaternion = this.rotationQuaternion;
  20389. }
  20390. else {
  20391. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  20392. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  20393. }
  20394. var accumulation = BABYLON.Tmp.Quaternion[0];
  20395. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  20396. rotationQuaternion.multiplyInPlace(accumulation);
  20397. if (!this.rotationQuaternion) {
  20398. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  20399. }
  20400. return this;
  20401. };
  20402. /**
  20403. * Computes the world matrix of the node
  20404. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  20405. * @returns the world matrix
  20406. */
  20407. TransformNode.prototype.computeWorldMatrix = function (force) {
  20408. if (this._isWorldMatrixFrozen) {
  20409. return this._worldMatrix;
  20410. }
  20411. if (!force && this.isSynchronized()) {
  20412. this._currentRenderId = this.getScene().getRenderId();
  20413. return this._worldMatrix;
  20414. }
  20415. this._updateCache();
  20416. this._cache.position.copyFrom(this.position);
  20417. this._cache.scaling.copyFrom(this.scaling);
  20418. this._cache.pivotMatrixUpdated = false;
  20419. this._cache.billboardMode = this.billboardMode;
  20420. this._currentRenderId = this.getScene().getRenderId();
  20421. this._childRenderId = this.getScene().getRenderId();
  20422. this._isDirty = false;
  20423. // Scaling
  20424. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  20425. // Rotation
  20426. //rotate, if quaternion is set and rotation was used
  20427. if (this.rotationQuaternion) {
  20428. var len = this.rotation.length();
  20429. if (len) {
  20430. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  20431. this.rotation.copyFromFloats(0, 0, 0);
  20432. }
  20433. }
  20434. if (this.rotationQuaternion) {
  20435. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  20436. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  20437. }
  20438. else {
  20439. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  20440. this._cache.rotation.copyFrom(this.rotation);
  20441. }
  20442. // Translation
  20443. var camera = this.getScene().activeCamera;
  20444. if (this.infiniteDistance && !this.parent && camera) {
  20445. var cameraWorldMatrix = camera.getWorldMatrix();
  20446. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  20447. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  20448. }
  20449. else {
  20450. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  20451. }
  20452. // Composing transformations
  20453. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  20454. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  20455. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  20456. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  20457. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  20458. // Need to decompose each rotation here
  20459. var currentPosition = BABYLON.Tmp.Vector3[3];
  20460. if (this.parent && this.parent.getWorldMatrix) {
  20461. if (this._transformToBoneReferal) {
  20462. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20463. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  20464. }
  20465. else {
  20466. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  20467. }
  20468. }
  20469. else {
  20470. currentPosition.copyFrom(this.position);
  20471. }
  20472. currentPosition.subtractInPlace(camera.globalPosition);
  20473. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  20474. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  20475. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  20476. }
  20477. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  20478. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  20479. }
  20480. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  20481. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  20482. }
  20483. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  20484. }
  20485. else {
  20486. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  20487. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  20488. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  20489. }
  20490. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  20491. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  20492. }
  20493. // Post multiply inverse of pivotMatrix
  20494. if (this._postMultiplyPivotMatrix) {
  20495. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  20496. }
  20497. // Local world
  20498. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  20499. // Parent
  20500. if (this.parent && this.parent.getWorldMatrix) {
  20501. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  20502. if (this._transformToBoneReferal) {
  20503. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20504. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  20505. }
  20506. else {
  20507. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  20508. }
  20509. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  20510. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  20511. this._worldMatrix.copyFrom(this._localWorld);
  20512. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  20513. }
  20514. else {
  20515. if (this._transformToBoneReferal) {
  20516. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20517. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  20518. }
  20519. else {
  20520. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  20521. }
  20522. }
  20523. this._markSyncedWithParent();
  20524. }
  20525. else {
  20526. this._worldMatrix.copyFrom(this._localWorld);
  20527. }
  20528. // Normal matrix
  20529. if (!this.ignoreNonUniformScaling) {
  20530. if (this.scaling.isNonUniform) {
  20531. this._updateNonUniformScalingState(true);
  20532. }
  20533. else if (this.parent && this.parent._nonUniformScaling) {
  20534. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  20535. }
  20536. else {
  20537. this._updateNonUniformScalingState(false);
  20538. }
  20539. }
  20540. else {
  20541. this._updateNonUniformScalingState(false);
  20542. }
  20543. this._afterComputeWorldMatrix();
  20544. // Absolute position
  20545. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  20546. // Callbacks
  20547. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  20548. if (!this._poseMatrix) {
  20549. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  20550. }
  20551. // Cache the determinant
  20552. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  20553. return this._worldMatrix;
  20554. };
  20555. TransformNode.prototype._afterComputeWorldMatrix = function () {
  20556. };
  20557. /**
  20558. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  20559. * @param func callback function to add
  20560. *
  20561. * @returns the TransformNode.
  20562. */
  20563. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  20564. this.onAfterWorldMatrixUpdateObservable.add(func);
  20565. return this;
  20566. };
  20567. /**
  20568. * Removes a registered callback function.
  20569. * @param func callback function to remove
  20570. * @returns the TransformNode.
  20571. */
  20572. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  20573. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  20574. return this;
  20575. };
  20576. /**
  20577. * Clone the current transform node
  20578. * @param name Name of the new clone
  20579. * @param newParent New parent for the clone
  20580. * @param doNotCloneChildren Do not clone children hierarchy
  20581. * @returns the new transform node
  20582. */
  20583. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20584. var _this = this;
  20585. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  20586. result.name = name;
  20587. result.id = name;
  20588. if (newParent) {
  20589. result.parent = newParent;
  20590. }
  20591. if (!doNotCloneChildren) {
  20592. // Children
  20593. var directDescendants = this.getDescendants(true);
  20594. for (var index = 0; index < directDescendants.length; index++) {
  20595. var child = directDescendants[index];
  20596. if (child.clone) {
  20597. child.clone(name + "." + child.name, result);
  20598. }
  20599. }
  20600. }
  20601. return result;
  20602. };
  20603. /**
  20604. * Serializes the objects information.
  20605. * @param currentSerializationObject defines the object to serialize in
  20606. * @returns the serialized object
  20607. */
  20608. TransformNode.prototype.serialize = function (currentSerializationObject) {
  20609. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  20610. serializationObject.type = this.getClassName();
  20611. // Parent
  20612. if (this.parent) {
  20613. serializationObject.parentId = this.parent.id;
  20614. }
  20615. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  20616. serializationObject.tags = BABYLON.Tags.GetTags(this);
  20617. }
  20618. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  20619. serializationObject.isEnabled = this.isEnabled();
  20620. // Parent
  20621. if (this.parent) {
  20622. serializationObject.parentId = this.parent.id;
  20623. }
  20624. return serializationObject;
  20625. };
  20626. // Statics
  20627. /**
  20628. * Returns a new TransformNode object parsed from the source provided.
  20629. * @param parsedTransformNode is the source.
  20630. * @param scene the scne the object belongs to
  20631. * @param rootUrl is a string, it's the root URL to prefix the `delayLoadingFile` property with
  20632. * @returns a new TransformNode object parsed from the source provided.
  20633. */
  20634. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  20635. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  20636. if (BABYLON.Tags) {
  20637. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  20638. }
  20639. if (parsedTransformNode.localMatrix) {
  20640. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  20641. }
  20642. else if (parsedTransformNode.pivotMatrix) {
  20643. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  20644. }
  20645. transformNode.setEnabled(parsedTransformNode.isEnabled);
  20646. // Parent
  20647. if (parsedTransformNode.parentId) {
  20648. transformNode._waitingParentId = parsedTransformNode.parentId;
  20649. }
  20650. return transformNode;
  20651. };
  20652. /**
  20653. * Releases resources associated with this transform node.
  20654. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20655. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20656. */
  20657. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20658. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20659. // Animations
  20660. this.getScene().stopAnimation(this);
  20661. // Remove from scene
  20662. this.getScene().removeTransformNode(this);
  20663. this.onAfterWorldMatrixUpdateObservable.clear();
  20664. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20665. };
  20666. // Statics
  20667. /**
  20668. * Object will not rotate to face the camera
  20669. */
  20670. TransformNode.BILLBOARDMODE_NONE = 0;
  20671. /**
  20672. * Object will rotate to face the camera but only on the x axis
  20673. */
  20674. TransformNode.BILLBOARDMODE_X = 1;
  20675. /**
  20676. * Object will rotate to face the camera but only on the y axis
  20677. */
  20678. TransformNode.BILLBOARDMODE_Y = 2;
  20679. /**
  20680. * Object will rotate to face the camera but only on the z axis
  20681. */
  20682. TransformNode.BILLBOARDMODE_Z = 4;
  20683. /**
  20684. * Object will rotate to face the camera
  20685. */
  20686. TransformNode.BILLBOARDMODE_ALL = 7;
  20687. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  20688. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  20689. __decorate([
  20690. BABYLON.serializeAsVector3("position")
  20691. ], TransformNode.prototype, "_position", void 0);
  20692. __decorate([
  20693. BABYLON.serializeAsVector3("rotation")
  20694. ], TransformNode.prototype, "_rotation", void 0);
  20695. __decorate([
  20696. BABYLON.serializeAsQuaternion("rotationQuaternion")
  20697. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  20698. __decorate([
  20699. BABYLON.serializeAsVector3("scaling")
  20700. ], TransformNode.prototype, "_scaling", void 0);
  20701. __decorate([
  20702. BABYLON.serialize()
  20703. ], TransformNode.prototype, "billboardMode", void 0);
  20704. __decorate([
  20705. BABYLON.serialize()
  20706. ], TransformNode.prototype, "scalingDeterminant", void 0);
  20707. __decorate([
  20708. BABYLON.serialize()
  20709. ], TransformNode.prototype, "infiniteDistance", void 0);
  20710. __decorate([
  20711. BABYLON.serialize()
  20712. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  20713. return TransformNode;
  20714. }(BABYLON.Node));
  20715. BABYLON.TransformNode = TransformNode;
  20716. })(BABYLON || (BABYLON = {}));
  20717. //# sourceMappingURL=babylon.transformNode.js.map
  20718. var BABYLON;
  20719. (function (BABYLON) {
  20720. /** @hidden */
  20721. var _FacetDataStorage = /** @class */ (function () {
  20722. function _FacetDataStorage() {
  20723. this.facetNb = 0; // facet number
  20724. this.partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  20725. this.partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  20726. this.facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  20727. this.facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  20728. this.bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  20729. this.subDiv = {
  20730. max: 1,
  20731. X: 1,
  20732. Y: 1,
  20733. Z: 1
  20734. };
  20735. this.facetDepthSort = false; // is the facet depth sort to be computed
  20736. this.facetDepthSortEnabled = false; // is the facet depth sort initialized
  20737. }
  20738. return _FacetDataStorage;
  20739. }());
  20740. /**
  20741. * Class used to store all common mesh properties
  20742. */
  20743. var AbstractMesh = /** @class */ (function (_super) {
  20744. __extends(AbstractMesh, _super);
  20745. // Constructor
  20746. /**
  20747. * Creates a new AbstractMesh
  20748. * @param name defines the name of the mesh
  20749. * @param scene defines the hosting scene
  20750. */
  20751. function AbstractMesh(name, scene) {
  20752. if (scene === void 0) { scene = null; }
  20753. var _this = _super.call(this, name, scene, false) || this;
  20754. _this._facetData = new _FacetDataStorage();
  20755. /** Gets ot sets the culling strategy to use to find visible meshes */
  20756. _this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_STANDARD;
  20757. // Events
  20758. /**
  20759. * An event triggered when this mesh collides with another one
  20760. */
  20761. _this.onCollideObservable = new BABYLON.Observable();
  20762. /**
  20763. * An event triggered when the collision's position changes
  20764. */
  20765. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  20766. /**
  20767. * An event triggered when material is changed
  20768. */
  20769. _this.onMaterialChangedObservable = new BABYLON.Observable();
  20770. // Properties
  20771. /**
  20772. * Gets or sets the orientation for POV movement & rotation
  20773. */
  20774. _this.definedFacingForward = true;
  20775. _this._visibility = 1.0;
  20776. /** Gets or sets the alpha index used to sort transparent meshes
  20777. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  20778. */
  20779. _this.alphaIndex = Number.MAX_VALUE;
  20780. /**
  20781. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  20782. */
  20783. _this.isVisible = true;
  20784. /**
  20785. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  20786. */
  20787. _this.isPickable = true;
  20788. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  20789. _this.showSubMeshesBoundingBox = false;
  20790. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  20791. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  20792. */
  20793. _this.isBlocker = false;
  20794. /**
  20795. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  20796. */
  20797. _this.enablePointerMoveEvents = false;
  20798. /**
  20799. * Specifies the rendering group id for this mesh (0 by default)
  20800. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  20801. */
  20802. _this.renderingGroupId = 0;
  20803. _this._receiveShadows = false;
  20804. /** Defines color to use when rendering outline */
  20805. _this.outlineColor = BABYLON.Color3.Red();
  20806. /** Define width to use when rendering outline */
  20807. _this.outlineWidth = 0.02;
  20808. /** Defines color to use when rendering overlay */
  20809. _this.overlayColor = BABYLON.Color3.Red();
  20810. /** Defines alpha to use when rendering overlay */
  20811. _this.overlayAlpha = 0.5;
  20812. _this._hasVertexAlpha = false;
  20813. _this._useVertexColors = true;
  20814. _this._computeBonesUsingShaders = true;
  20815. _this._numBoneInfluencers = 4;
  20816. _this._applyFog = true;
  20817. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  20818. _this.useOctreeForRenderingSelection = true;
  20819. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  20820. _this.useOctreeForPicking = true;
  20821. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  20822. _this.useOctreeForCollisions = true;
  20823. _this._layerMask = 0x0FFFFFFF;
  20824. /**
  20825. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  20826. */
  20827. _this.alwaysSelectAsActiveMesh = false;
  20828. /**
  20829. * Gets or sets the current action manager
  20830. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  20831. */
  20832. _this.actionManager = null;
  20833. // Collisions
  20834. _this._checkCollisions = false;
  20835. _this._collisionMask = -1;
  20836. _this._collisionGroup = -1;
  20837. /**
  20838. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  20839. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20840. */
  20841. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  20842. /**
  20843. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  20844. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20845. */
  20846. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  20847. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  20848. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  20849. // Edges
  20850. /**
  20851. * Defines edge width used when edgesRenderer is enabled
  20852. * @see https://www.babylonjs-playground.com/#10OJSG#13
  20853. */
  20854. _this.edgesWidth = 1;
  20855. /**
  20856. * Defines edge color used when edgesRenderer is enabled
  20857. * @see https://www.babylonjs-playground.com/#10OJSG#13
  20858. */
  20859. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  20860. /** @hidden */
  20861. _this._renderId = 0;
  20862. /** @hidden */
  20863. _this._intersectionsInProgress = new Array();
  20864. /** @hidden */
  20865. _this._unIndexed = false;
  20866. /** @hidden */
  20867. _this._lightSources = new Array();
  20868. /**
  20869. * An event triggered when the mesh is rebuilt.
  20870. */
  20871. _this.onRebuildObservable = new BABYLON.Observable();
  20872. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  20873. if (collidedMesh === void 0) { collidedMesh = null; }
  20874. //TODO move this to the collision coordinator!
  20875. if (_this.getScene().workerCollisions) {
  20876. newPosition.multiplyInPlace(_this._collider._radius);
  20877. }
  20878. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  20879. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  20880. _this.position.addInPlace(_this._diffPositionForCollisions);
  20881. }
  20882. if (collidedMesh) {
  20883. _this.onCollideObservable.notifyObservers(collidedMesh);
  20884. }
  20885. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  20886. };
  20887. _this.getScene().addMesh(_this);
  20888. _this._resyncLightSources();
  20889. return _this;
  20890. }
  20891. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  20892. /**
  20893. * No billboard
  20894. */
  20895. get: function () {
  20896. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  20897. },
  20898. enumerable: true,
  20899. configurable: true
  20900. });
  20901. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  20902. /** Billboard on X axis */
  20903. get: function () {
  20904. return BABYLON.TransformNode.BILLBOARDMODE_X;
  20905. },
  20906. enumerable: true,
  20907. configurable: true
  20908. });
  20909. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  20910. /** Billboard on Y axis */
  20911. get: function () {
  20912. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  20913. },
  20914. enumerable: true,
  20915. configurable: true
  20916. });
  20917. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  20918. /** Billboard on Z axis */
  20919. get: function () {
  20920. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  20921. },
  20922. enumerable: true,
  20923. configurable: true
  20924. });
  20925. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  20926. /** Billboard on all axes */
  20927. get: function () {
  20928. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  20929. },
  20930. enumerable: true,
  20931. configurable: true
  20932. });
  20933. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  20934. /**
  20935. * Gets the number of facets in the mesh
  20936. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  20937. */
  20938. get: function () {
  20939. return this._facetData.facetNb;
  20940. },
  20941. enumerable: true,
  20942. configurable: true
  20943. });
  20944. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  20945. /**
  20946. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  20947. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  20948. */
  20949. get: function () {
  20950. return this._facetData.partitioningSubdivisions;
  20951. },
  20952. set: function (nb) {
  20953. this._facetData.partitioningSubdivisions = nb;
  20954. },
  20955. enumerable: true,
  20956. configurable: true
  20957. });
  20958. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  20959. /**
  20960. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  20961. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  20962. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  20963. */
  20964. get: function () {
  20965. return this._facetData.partitioningBBoxRatio;
  20966. },
  20967. set: function (ratio) {
  20968. this._facetData.partitioningBBoxRatio = ratio;
  20969. },
  20970. enumerable: true,
  20971. configurable: true
  20972. });
  20973. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  20974. /**
  20975. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  20976. * Works only for updatable meshes.
  20977. * Doesn't work with multi-materials
  20978. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  20979. */
  20980. get: function () {
  20981. return this._facetData.facetDepthSort;
  20982. },
  20983. set: function (sort) {
  20984. this._facetData.facetDepthSort = sort;
  20985. },
  20986. enumerable: true,
  20987. configurable: true
  20988. });
  20989. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  20990. /**
  20991. * The location (Vector3) where the facet depth sort must be computed from.
  20992. * By default, the active camera position.
  20993. * Used only when facet depth sort is enabled
  20994. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  20995. */
  20996. get: function () {
  20997. return this._facetData.facetDepthSortFrom;
  20998. },
  20999. set: function (location) {
  21000. this._facetData.facetDepthSortFrom = location;
  21001. },
  21002. enumerable: true,
  21003. configurable: true
  21004. });
  21005. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  21006. /**
  21007. * gets a boolean indicating if facetData is enabled
  21008. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  21009. */
  21010. get: function () {
  21011. return this._facetData.facetDataEnabled;
  21012. },
  21013. enumerable: true,
  21014. configurable: true
  21015. });
  21016. /** @hidden */
  21017. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  21018. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  21019. return false;
  21020. }
  21021. this._markSubMeshesAsMiscDirty();
  21022. return true;
  21023. };
  21024. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  21025. /** Set a function to call when this mesh collides with another one */
  21026. set: function (callback) {
  21027. if (this._onCollideObserver) {
  21028. this.onCollideObservable.remove(this._onCollideObserver);
  21029. }
  21030. this._onCollideObserver = this.onCollideObservable.add(callback);
  21031. },
  21032. enumerable: true,
  21033. configurable: true
  21034. });
  21035. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  21036. /** Set a function to call when the collision's position changes */
  21037. set: function (callback) {
  21038. if (this._onCollisionPositionChangeObserver) {
  21039. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  21040. }
  21041. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  21042. },
  21043. enumerable: true,
  21044. configurable: true
  21045. });
  21046. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  21047. /**
  21048. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  21049. */
  21050. get: function () {
  21051. return this._visibility;
  21052. },
  21053. /**
  21054. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  21055. */
  21056. set: function (value) {
  21057. if (this._visibility === value) {
  21058. return;
  21059. }
  21060. this._visibility = value;
  21061. this._markSubMeshesAsMiscDirty();
  21062. },
  21063. enumerable: true,
  21064. configurable: true
  21065. });
  21066. Object.defineProperty(AbstractMesh.prototype, "material", {
  21067. /** Gets or sets current material */
  21068. get: function () {
  21069. return this._material;
  21070. },
  21071. set: function (value) {
  21072. if (this._material === value) {
  21073. return;
  21074. }
  21075. this._material = value;
  21076. if (this.onMaterialChangedObservable.hasObservers) {
  21077. this.onMaterialChangedObservable.notifyObservers(this);
  21078. }
  21079. if (!this.subMeshes) {
  21080. return;
  21081. }
  21082. this._unBindEffect();
  21083. },
  21084. enumerable: true,
  21085. configurable: true
  21086. });
  21087. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  21088. /**
  21089. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  21090. * @see http://doc.babylonjs.com/babylon101/shadows
  21091. */
  21092. get: function () {
  21093. return this._receiveShadows;
  21094. },
  21095. set: function (value) {
  21096. if (this._receiveShadows === value) {
  21097. return;
  21098. }
  21099. this._receiveShadows = value;
  21100. this._markSubMeshesAsLightDirty();
  21101. },
  21102. enumerable: true,
  21103. configurable: true
  21104. });
  21105. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  21106. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  21107. get: function () {
  21108. return this._hasVertexAlpha;
  21109. },
  21110. set: function (value) {
  21111. if (this._hasVertexAlpha === value) {
  21112. return;
  21113. }
  21114. this._hasVertexAlpha = value;
  21115. this._markSubMeshesAsAttributesDirty();
  21116. this._markSubMeshesAsMiscDirty();
  21117. },
  21118. enumerable: true,
  21119. configurable: true
  21120. });
  21121. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  21122. /** 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) */
  21123. get: function () {
  21124. return this._useVertexColors;
  21125. },
  21126. set: function (value) {
  21127. if (this._useVertexColors === value) {
  21128. return;
  21129. }
  21130. this._useVertexColors = value;
  21131. this._markSubMeshesAsAttributesDirty();
  21132. },
  21133. enumerable: true,
  21134. configurable: true
  21135. });
  21136. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  21137. /**
  21138. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  21139. */
  21140. get: function () {
  21141. return this._computeBonesUsingShaders;
  21142. },
  21143. set: function (value) {
  21144. if (this._computeBonesUsingShaders === value) {
  21145. return;
  21146. }
  21147. this._computeBonesUsingShaders = value;
  21148. this._markSubMeshesAsAttributesDirty();
  21149. },
  21150. enumerable: true,
  21151. configurable: true
  21152. });
  21153. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  21154. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  21155. get: function () {
  21156. return this._numBoneInfluencers;
  21157. },
  21158. set: function (value) {
  21159. if (this._numBoneInfluencers === value) {
  21160. return;
  21161. }
  21162. this._numBoneInfluencers = value;
  21163. this._markSubMeshesAsAttributesDirty();
  21164. },
  21165. enumerable: true,
  21166. configurable: true
  21167. });
  21168. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  21169. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  21170. get: function () {
  21171. return this._applyFog;
  21172. },
  21173. set: function (value) {
  21174. if (this._applyFog === value) {
  21175. return;
  21176. }
  21177. this._applyFog = value;
  21178. this._markSubMeshesAsMiscDirty();
  21179. },
  21180. enumerable: true,
  21181. configurable: true
  21182. });
  21183. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  21184. /**
  21185. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  21186. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  21187. */
  21188. get: function () {
  21189. return this._layerMask;
  21190. },
  21191. set: function (value) {
  21192. if (value === this._layerMask) {
  21193. return;
  21194. }
  21195. this._layerMask = value;
  21196. this._resyncLightSources();
  21197. },
  21198. enumerable: true,
  21199. configurable: true
  21200. });
  21201. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  21202. /**
  21203. * Gets or sets a collision mask used to mask collisions (default is -1).
  21204. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  21205. */
  21206. get: function () {
  21207. return this._collisionMask;
  21208. },
  21209. set: function (mask) {
  21210. this._collisionMask = !isNaN(mask) ? mask : -1;
  21211. },
  21212. enumerable: true,
  21213. configurable: true
  21214. });
  21215. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  21216. /**
  21217. * Gets or sets the current collision group mask (-1 by default).
  21218. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  21219. */
  21220. get: function () {
  21221. return this._collisionGroup;
  21222. },
  21223. set: function (mask) {
  21224. this._collisionGroup = !isNaN(mask) ? mask : -1;
  21225. },
  21226. enumerable: true,
  21227. configurable: true
  21228. });
  21229. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  21230. /** @hidden */
  21231. get: function () {
  21232. return null;
  21233. },
  21234. enumerable: true,
  21235. configurable: true
  21236. });
  21237. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  21238. get: function () {
  21239. return this._skeleton;
  21240. },
  21241. /**
  21242. * Gets or sets a skeleton to apply skining transformations
  21243. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  21244. */
  21245. set: function (value) {
  21246. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  21247. this._skeleton._unregisterMeshWithPoseMatrix(this);
  21248. }
  21249. if (value && value.needInitialSkinMatrix) {
  21250. value._registerMeshWithPoseMatrix(this);
  21251. }
  21252. this._skeleton = value;
  21253. if (!this._skeleton) {
  21254. this._bonesTransformMatrices = null;
  21255. }
  21256. this._markSubMeshesAsAttributesDirty();
  21257. },
  21258. enumerable: true,
  21259. configurable: true
  21260. });
  21261. /**
  21262. * Returns the string "AbstractMesh"
  21263. * @returns "AbstractMesh"
  21264. */
  21265. AbstractMesh.prototype.getClassName = function () {
  21266. return "AbstractMesh";
  21267. };
  21268. /**
  21269. * Gets a string representation of the current mesh
  21270. * @param fullDetails defines a boolean indicating if full details must be included
  21271. * @returns a string representation of the current mesh
  21272. */
  21273. AbstractMesh.prototype.toString = function (fullDetails) {
  21274. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  21275. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  21276. if (this._skeleton) {
  21277. ret += ", skeleton: " + this._skeleton.name;
  21278. }
  21279. if (fullDetails) {
  21280. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  21281. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  21282. }
  21283. return ret;
  21284. };
  21285. /** @hidden */
  21286. AbstractMesh.prototype._rebuild = function () {
  21287. this.onRebuildObservable.notifyObservers(this);
  21288. if (this._occlusionQuery) {
  21289. this._occlusionQuery = null;
  21290. }
  21291. if (!this.subMeshes) {
  21292. return;
  21293. }
  21294. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21295. var subMesh = _a[_i];
  21296. subMesh._rebuild();
  21297. }
  21298. };
  21299. /** @hidden */
  21300. AbstractMesh.prototype._resyncLightSources = function () {
  21301. this._lightSources.length = 0;
  21302. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  21303. var light = _a[_i];
  21304. if (!light.isEnabled()) {
  21305. continue;
  21306. }
  21307. if (light.canAffectMesh(this)) {
  21308. this._lightSources.push(light);
  21309. }
  21310. }
  21311. this._markSubMeshesAsLightDirty();
  21312. };
  21313. /** @hidden */
  21314. AbstractMesh.prototype._resyncLighSource = function (light) {
  21315. var isIn = light.isEnabled() && light.canAffectMesh(this);
  21316. var index = this._lightSources.indexOf(light);
  21317. if (index === -1) {
  21318. if (!isIn) {
  21319. return;
  21320. }
  21321. this._lightSources.push(light);
  21322. }
  21323. else {
  21324. if (isIn) {
  21325. return;
  21326. }
  21327. this._lightSources.splice(index, 1);
  21328. }
  21329. this._markSubMeshesAsLightDirty();
  21330. };
  21331. /** @hidden */
  21332. AbstractMesh.prototype._unBindEffect = function () {
  21333. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21334. var subMesh = _a[_i];
  21335. subMesh.setEffect(null);
  21336. }
  21337. };
  21338. /** @hidden */
  21339. AbstractMesh.prototype._removeLightSource = function (light) {
  21340. var index = this._lightSources.indexOf(light);
  21341. if (index === -1) {
  21342. return;
  21343. }
  21344. this._lightSources.splice(index, 1);
  21345. this._markSubMeshesAsLightDirty();
  21346. };
  21347. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  21348. if (!this.subMeshes) {
  21349. return;
  21350. }
  21351. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21352. var subMesh = _a[_i];
  21353. if (subMesh._materialDefines) {
  21354. func(subMesh._materialDefines);
  21355. }
  21356. }
  21357. };
  21358. /** @hidden */
  21359. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  21360. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  21361. };
  21362. /** @hidden */
  21363. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  21364. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  21365. };
  21366. /** @hidden */
  21367. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  21368. if (!this.subMeshes) {
  21369. return;
  21370. }
  21371. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21372. var subMesh = _a[_i];
  21373. var material = subMesh.getMaterial();
  21374. if (material) {
  21375. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  21376. }
  21377. }
  21378. };
  21379. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  21380. /**
  21381. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  21382. */
  21383. get: function () {
  21384. return this._scaling;
  21385. },
  21386. set: function (newScaling) {
  21387. this._scaling = newScaling;
  21388. if (this.physicsImpostor) {
  21389. this.physicsImpostor.forceUpdate();
  21390. }
  21391. },
  21392. enumerable: true,
  21393. configurable: true
  21394. });
  21395. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  21396. // Methods
  21397. /**
  21398. * Returns true if the mesh is blocked. Implemented by child classes
  21399. */
  21400. get: function () {
  21401. return false;
  21402. },
  21403. enumerable: true,
  21404. configurable: true
  21405. });
  21406. /**
  21407. * Returns the mesh itself by default. Implemented by child classes
  21408. * @param camera defines the camera to use to pick the right LOD level
  21409. * @returns the currentAbstractMesh
  21410. */
  21411. AbstractMesh.prototype.getLOD = function (camera) {
  21412. return this;
  21413. };
  21414. /**
  21415. * Returns 0 by default. Implemented by child classes
  21416. * @returns an integer
  21417. */
  21418. AbstractMesh.prototype.getTotalVertices = function () {
  21419. return 0;
  21420. };
  21421. /**
  21422. * Returns null by default. Implemented by child classes
  21423. * @returns null
  21424. */
  21425. AbstractMesh.prototype.getIndices = function () {
  21426. return null;
  21427. };
  21428. /**
  21429. * Returns the array of the requested vertex data kind. Implemented by child classes
  21430. * @param kind defines the vertex data kind to use
  21431. * @returns null
  21432. */
  21433. AbstractMesh.prototype.getVerticesData = function (kind) {
  21434. return null;
  21435. };
  21436. /**
  21437. * Sets the vertex data of the mesh geometry for the requested `kind`.
  21438. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  21439. * Note that a new underlying VertexBuffer object is created each call.
  21440. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  21441. * @param kind defines vertex data kind:
  21442. * * BABYLON.VertexBuffer.PositionKind
  21443. * * BABYLON.VertexBuffer.UVKind
  21444. * * BABYLON.VertexBuffer.UV2Kind
  21445. * * BABYLON.VertexBuffer.UV3Kind
  21446. * * BABYLON.VertexBuffer.UV4Kind
  21447. * * BABYLON.VertexBuffer.UV5Kind
  21448. * * BABYLON.VertexBuffer.UV6Kind
  21449. * * BABYLON.VertexBuffer.ColorKind
  21450. * * BABYLON.VertexBuffer.MatricesIndicesKind
  21451. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21452. * * BABYLON.VertexBuffer.MatricesWeightsKind
  21453. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21454. * @param data defines the data source
  21455. * @param updatable defines if the data must be flagged as updatable (or static)
  21456. * @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
  21457. * @returns the current mesh
  21458. */
  21459. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  21460. return this;
  21461. };
  21462. /**
  21463. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  21464. * If the mesh has no geometry, it is simply returned as it is.
  21465. * @param kind defines vertex data kind:
  21466. * * BABYLON.VertexBuffer.PositionKind
  21467. * * BABYLON.VertexBuffer.UVKind
  21468. * * BABYLON.VertexBuffer.UV2Kind
  21469. * * BABYLON.VertexBuffer.UV3Kind
  21470. * * BABYLON.VertexBuffer.UV4Kind
  21471. * * BABYLON.VertexBuffer.UV5Kind
  21472. * * BABYLON.VertexBuffer.UV6Kind
  21473. * * BABYLON.VertexBuffer.ColorKind
  21474. * * BABYLON.VertexBuffer.MatricesIndicesKind
  21475. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21476. * * BABYLON.VertexBuffer.MatricesWeightsKind
  21477. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21478. * @param data defines the data source
  21479. * @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
  21480. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  21481. * @returns the current mesh
  21482. */
  21483. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  21484. return this;
  21485. };
  21486. /**
  21487. * Sets the mesh indices,
  21488. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  21489. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  21490. * @param totalVertices Defines the total number of vertices
  21491. * @returns the current mesh
  21492. */
  21493. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  21494. return this;
  21495. };
  21496. /**
  21497. * Gets a boolean indicating if specific vertex data is present
  21498. * @param kind defines the vertex data kind to use
  21499. * @returns true is data kind is present
  21500. */
  21501. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  21502. return false;
  21503. };
  21504. /**
  21505. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  21506. * @returns a BoundingInfo
  21507. */
  21508. AbstractMesh.prototype.getBoundingInfo = function () {
  21509. if (this._masterMesh) {
  21510. return this._masterMesh.getBoundingInfo();
  21511. }
  21512. if (!this._boundingInfo) {
  21513. // this._boundingInfo is being created here
  21514. this._updateBoundingInfo();
  21515. }
  21516. // cannot be null.
  21517. return this._boundingInfo;
  21518. };
  21519. /**
  21520. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  21521. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  21522. * @returns the current mesh
  21523. */
  21524. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  21525. if (includeDescendants === void 0) { includeDescendants = true; }
  21526. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  21527. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  21528. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  21529. if (maxDimension === 0) {
  21530. return this;
  21531. }
  21532. var scale = 1 / maxDimension;
  21533. this.scaling.scaleInPlace(scale);
  21534. return this;
  21535. };
  21536. /**
  21537. * Overwrite the current bounding info
  21538. * @param boundingInfo defines the new bounding info
  21539. * @returns the current mesh
  21540. */
  21541. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  21542. this._boundingInfo = boundingInfo;
  21543. return this;
  21544. };
  21545. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  21546. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  21547. get: function () {
  21548. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  21549. },
  21550. enumerable: true,
  21551. configurable: true
  21552. });
  21553. /** @hidden */
  21554. AbstractMesh.prototype._preActivate = function () {
  21555. };
  21556. /** @hidden */
  21557. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  21558. };
  21559. /** @hidden */
  21560. AbstractMesh.prototype._activate = function (renderId) {
  21561. this._renderId = renderId;
  21562. };
  21563. /**
  21564. * Gets the current world matrix
  21565. * @returns a Matrix
  21566. */
  21567. AbstractMesh.prototype.getWorldMatrix = function () {
  21568. if (this._masterMesh) {
  21569. return this._masterMesh.getWorldMatrix();
  21570. }
  21571. return _super.prototype.getWorldMatrix.call(this);
  21572. };
  21573. /** @hidden */
  21574. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  21575. if (this._masterMesh) {
  21576. return this._masterMesh._getWorldMatrixDeterminant();
  21577. }
  21578. return _super.prototype._getWorldMatrixDeterminant.call(this);
  21579. };
  21580. // ================================== Point of View Movement =================================
  21581. /**
  21582. * Perform relative position change from the point of view of behind the front of the mesh.
  21583. * This is performed taking into account the meshes current rotation, so you do not have to care.
  21584. * Supports definition of mesh facing forward or backward
  21585. * @param amountRight defines the distance on the right axis
  21586. * @param amountUp defines the distance on the up axis
  21587. * @param amountForward defines the distance on the forward axis
  21588. * @returns the current mesh
  21589. */
  21590. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  21591. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  21592. return this;
  21593. };
  21594. /**
  21595. * Calculate relative position change from the point of view of behind the front of the mesh.
  21596. * This is performed taking into account the meshes current rotation, so you do not have to care.
  21597. * Supports definition of mesh facing forward or backward
  21598. * @param amountRight defines the distance on the right axis
  21599. * @param amountUp defines the distance on the up axis
  21600. * @param amountForward defines the distance on the forward axis
  21601. * @returns the new displacement vector
  21602. */
  21603. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  21604. var rotMatrix = new BABYLON.Matrix();
  21605. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  21606. rotQuaternion.toRotationMatrix(rotMatrix);
  21607. var translationDelta = BABYLON.Vector3.Zero();
  21608. var defForwardMult = this.definedFacingForward ? -1 : 1;
  21609. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  21610. return translationDelta;
  21611. };
  21612. // ================================== Point of View Rotation =================================
  21613. /**
  21614. * Perform relative rotation change from the point of view of behind the front of the mesh.
  21615. * Supports definition of mesh facing forward or backward
  21616. * @param flipBack defines the flip
  21617. * @param twirlClockwise defines the twirl
  21618. * @param tiltRight defines the tilt
  21619. * @returns the current mesh
  21620. */
  21621. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  21622. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  21623. return this;
  21624. };
  21625. /**
  21626. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  21627. * Supports definition of mesh facing forward or backward.
  21628. * @param flipBack defines the flip
  21629. * @param twirlClockwise defines the twirl
  21630. * @param tiltRight defines the tilt
  21631. * @returns the new rotation vector
  21632. */
  21633. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  21634. var defForwardMult = this.definedFacingForward ? 1 : -1;
  21635. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  21636. };
  21637. /**
  21638. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  21639. * @param includeDescendants Include bounding info from descendants as well (true by default)
  21640. * @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
  21641. * @returns the new bounding vectors
  21642. */
  21643. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  21644. if (includeDescendants === void 0) { includeDescendants = true; }
  21645. if (predicate === void 0) { predicate = null; }
  21646. // Ensures that all world matrix will be recomputed.
  21647. this.getScene().incrementRenderId();
  21648. this.computeWorldMatrix(true);
  21649. var min;
  21650. var max;
  21651. var boundingInfo = this.getBoundingInfo();
  21652. if (!this.subMeshes) {
  21653. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21654. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  21655. }
  21656. else {
  21657. min = boundingInfo.boundingBox.minimumWorld;
  21658. max = boundingInfo.boundingBox.maximumWorld;
  21659. }
  21660. if (includeDescendants) {
  21661. var descendants = this.getDescendants(false);
  21662. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  21663. var descendant = descendants_1[_i];
  21664. var childMesh = descendant;
  21665. childMesh.computeWorldMatrix(true);
  21666. // Filters meshes based on custom predicate function.
  21667. if (predicate && !predicate(childMesh)) {
  21668. continue;
  21669. }
  21670. //make sure we have the needed params to get mix and max
  21671. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  21672. continue;
  21673. }
  21674. var childBoundingInfo = childMesh.getBoundingInfo();
  21675. var boundingBox = childBoundingInfo.boundingBox;
  21676. var minBox = boundingBox.minimumWorld;
  21677. var maxBox = boundingBox.maximumWorld;
  21678. BABYLON.Tools.CheckExtends(minBox, min, max);
  21679. BABYLON.Tools.CheckExtends(maxBox, min, max);
  21680. }
  21681. }
  21682. return {
  21683. min: min,
  21684. max: max
  21685. };
  21686. };
  21687. /** @hidden */
  21688. AbstractMesh.prototype._updateBoundingInfo = function () {
  21689. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  21690. this._boundingInfo.update(this.worldMatrixFromCache);
  21691. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  21692. return this;
  21693. };
  21694. /** @hidden */
  21695. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  21696. if (!this.subMeshes) {
  21697. return this;
  21698. }
  21699. var count = this.subMeshes.length;
  21700. for (var subIndex = 0; subIndex < count; subIndex++) {
  21701. var subMesh = this.subMeshes[subIndex];
  21702. if (count > 1 || !subMesh.IsGlobal) {
  21703. subMesh.updateBoundingInfo(matrix);
  21704. }
  21705. }
  21706. return this;
  21707. };
  21708. /** @hidden */
  21709. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  21710. // Bounding info
  21711. this._updateBoundingInfo();
  21712. };
  21713. /**
  21714. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  21715. * A mesh is in the frustum if its bounding box intersects the frustum
  21716. * @param frustumPlanes defines the frustum to test
  21717. * @returns true if the mesh is in the frustum planes
  21718. */
  21719. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  21720. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);
  21721. };
  21722. /**
  21723. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  21724. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  21725. * @param frustumPlanes defines the frustum to test
  21726. * @returns true if the mesh is completely in the frustum planes
  21727. */
  21728. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  21729. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  21730. };
  21731. /**
  21732. * True if the mesh intersects another mesh or a SolidParticle object
  21733. * @param mesh defines a target mesh or SolidParticle to test
  21734. * @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)
  21735. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  21736. * @returns true if there is an intersection
  21737. */
  21738. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  21739. if (precise === void 0) { precise = false; }
  21740. if (!this._boundingInfo || !mesh._boundingInfo) {
  21741. return false;
  21742. }
  21743. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  21744. return true;
  21745. }
  21746. if (includeDescendants) {
  21747. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  21748. var child = _a[_i];
  21749. if (child.intersectsMesh(mesh, precise, true)) {
  21750. return true;
  21751. }
  21752. }
  21753. }
  21754. return false;
  21755. };
  21756. /**
  21757. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  21758. * @param point defines the point to test
  21759. * @returns true if there is an intersection
  21760. */
  21761. AbstractMesh.prototype.intersectsPoint = function (point) {
  21762. if (!this._boundingInfo) {
  21763. return false;
  21764. }
  21765. return this._boundingInfo.intersectsPoint(point);
  21766. };
  21767. /**
  21768. * Gets the position of the current mesh in camera space
  21769. * @param camera defines the camera to use
  21770. * @returns a position
  21771. */
  21772. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  21773. if (camera === void 0) { camera = null; }
  21774. if (!camera) {
  21775. camera = this.getScene().activeCamera;
  21776. }
  21777. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  21778. };
  21779. /**
  21780. * Returns the distance from the mesh to the active camera
  21781. * @param camera defines the camera to use
  21782. * @returns the distance
  21783. */
  21784. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  21785. if (camera === void 0) { camera = null; }
  21786. if (!camera) {
  21787. camera = this.getScene().activeCamera;
  21788. }
  21789. return this.absolutePosition.subtract(camera.position).length();
  21790. };
  21791. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  21792. // Collisions
  21793. /**
  21794. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  21795. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21796. */
  21797. get: function () {
  21798. return this._checkCollisions;
  21799. },
  21800. set: function (collisionEnabled) {
  21801. this._checkCollisions = collisionEnabled;
  21802. if (this.getScene().workerCollisions) {
  21803. this.getScene().collisionCoordinator.onMeshUpdated(this);
  21804. }
  21805. },
  21806. enumerable: true,
  21807. configurable: true
  21808. });
  21809. Object.defineProperty(AbstractMesh.prototype, "collider", {
  21810. /**
  21811. * Gets Collider object used to compute collisions (not physics)
  21812. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21813. */
  21814. get: function () {
  21815. return this._collider;
  21816. },
  21817. enumerable: true,
  21818. configurable: true
  21819. });
  21820. /**
  21821. * Move the mesh using collision engine
  21822. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21823. * @param displacement defines the requested displacement vector
  21824. * @returns the current mesh
  21825. */
  21826. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  21827. var globalPosition = this.getAbsolutePosition();
  21828. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  21829. if (!this._collider) {
  21830. this._collider = new BABYLON.Collider();
  21831. }
  21832. this._collider._radius = this.ellipsoid;
  21833. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  21834. return this;
  21835. };
  21836. // Collisions
  21837. /** @hidden */
  21838. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  21839. this._generatePointsArray();
  21840. if (!this._positions) {
  21841. return this;
  21842. }
  21843. // Transformation
  21844. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  21845. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  21846. subMesh._lastColliderWorldVertices = [];
  21847. subMesh._trianglePlanes = [];
  21848. var start = subMesh.verticesStart;
  21849. var end = (subMesh.verticesStart + subMesh.verticesCount);
  21850. for (var i = start; i < end; i++) {
  21851. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  21852. }
  21853. }
  21854. // Collide
  21855. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  21856. if (collider.collisionFound) {
  21857. collider.collidedMesh = this;
  21858. }
  21859. return this;
  21860. };
  21861. /** @hidden */
  21862. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  21863. var subMeshes = this._scene.getCollidingSubMeshCandidates(this, collider);
  21864. var len = subMeshes.length;
  21865. for (var index = 0; index < len; index++) {
  21866. var subMesh = subMeshes.data[index];
  21867. // Bounding test
  21868. if (len > 1 && !subMesh._checkCollision(collider)) {
  21869. continue;
  21870. }
  21871. this._collideForSubMesh(subMesh, transformMatrix, collider);
  21872. }
  21873. return this;
  21874. };
  21875. /** @hidden */
  21876. AbstractMesh.prototype._checkCollision = function (collider) {
  21877. // Bounding box test
  21878. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider)) {
  21879. return this;
  21880. }
  21881. // Transformation matrix
  21882. var collisionsScalingMatrix = BABYLON.Tmp.Matrix[0];
  21883. var collisionsTransformMatrix = BABYLON.Tmp.Matrix[1];
  21884. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, collisionsScalingMatrix);
  21885. this.worldMatrixFromCache.multiplyToRef(collisionsScalingMatrix, collisionsTransformMatrix);
  21886. this._processCollisionsForSubMeshes(collider, collisionsTransformMatrix);
  21887. return this;
  21888. };
  21889. // Picking
  21890. /** @hidden */
  21891. AbstractMesh.prototype._generatePointsArray = function () {
  21892. return false;
  21893. };
  21894. /**
  21895. * Checks if the passed Ray intersects with the mesh
  21896. * @param ray defines the ray to use
  21897. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  21898. * @returns the picking info
  21899. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  21900. */
  21901. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  21902. var pickingInfo = new BABYLON.PickingInfo();
  21903. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  21904. return pickingInfo;
  21905. }
  21906. if (!this._generatePointsArray()) {
  21907. return pickingInfo;
  21908. }
  21909. var intersectInfo = null;
  21910. var subMeshes = this._scene.getIntersectingSubMeshCandidates(this, ray);
  21911. var len = subMeshes.length;
  21912. for (var index = 0; index < len; index++) {
  21913. var subMesh = subMeshes.data[index];
  21914. // Bounding test
  21915. if (len > 1 && !subMesh.canIntersects(ray)) {
  21916. continue;
  21917. }
  21918. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  21919. if (currentIntersectInfo) {
  21920. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  21921. intersectInfo = currentIntersectInfo;
  21922. intersectInfo.subMeshId = index;
  21923. if (fastCheck) {
  21924. break;
  21925. }
  21926. }
  21927. }
  21928. }
  21929. if (intersectInfo) {
  21930. // Get picked point
  21931. var world = this.getWorldMatrix();
  21932. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  21933. var direction = ray.direction.clone();
  21934. direction = direction.scale(intersectInfo.distance);
  21935. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  21936. var pickedPoint = worldOrigin.add(worldDirection);
  21937. // Return result
  21938. pickingInfo.hit = true;
  21939. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  21940. pickingInfo.pickedPoint = pickedPoint;
  21941. pickingInfo.pickedMesh = this;
  21942. pickingInfo.bu = intersectInfo.bu || 0;
  21943. pickingInfo.bv = intersectInfo.bv || 0;
  21944. pickingInfo.faceId = intersectInfo.faceId;
  21945. pickingInfo.subMeshId = intersectInfo.subMeshId;
  21946. return pickingInfo;
  21947. }
  21948. return pickingInfo;
  21949. };
  21950. /**
  21951. * Clones the current mesh
  21952. * @param name defines the mesh name
  21953. * @param newParent defines the new mesh parent
  21954. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  21955. * @returns the new mesh
  21956. */
  21957. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  21958. return null;
  21959. };
  21960. /**
  21961. * Disposes all the submeshes of the current meshnp
  21962. * @returns the current mesh
  21963. */
  21964. AbstractMesh.prototype.releaseSubMeshes = function () {
  21965. if (this.subMeshes) {
  21966. while (this.subMeshes.length) {
  21967. this.subMeshes[0].dispose();
  21968. }
  21969. }
  21970. else {
  21971. this.subMeshes = new Array();
  21972. }
  21973. return this;
  21974. };
  21975. /**
  21976. * Releases resources associated with this abstract mesh.
  21977. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21978. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21979. */
  21980. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21981. var _this = this;
  21982. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21983. var index;
  21984. // Smart Array Retainers.
  21985. this.getScene().freeActiveMeshes();
  21986. this.getScene().freeRenderingGroups();
  21987. // Action manager
  21988. if (this.actionManager !== undefined && this.actionManager !== null) {
  21989. this.actionManager.dispose();
  21990. this.actionManager = null;
  21991. }
  21992. // Skeleton
  21993. this._skeleton = null;
  21994. // Intersections in progress
  21995. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  21996. var other = this._intersectionsInProgress[index];
  21997. var pos = other._intersectionsInProgress.indexOf(this);
  21998. other._intersectionsInProgress.splice(pos, 1);
  21999. }
  22000. this._intersectionsInProgress = [];
  22001. // Lights
  22002. var lights = this.getScene().lights;
  22003. lights.forEach(function (light) {
  22004. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  22005. if (meshIndex !== -1) {
  22006. light.includedOnlyMeshes.splice(meshIndex, 1);
  22007. }
  22008. meshIndex = light.excludedMeshes.indexOf(_this);
  22009. if (meshIndex !== -1) {
  22010. light.excludedMeshes.splice(meshIndex, 1);
  22011. }
  22012. // Shadow generators
  22013. var generator = light.getShadowGenerator();
  22014. if (generator) {
  22015. var shadowMap = generator.getShadowMap();
  22016. if (shadowMap && shadowMap.renderList) {
  22017. meshIndex = shadowMap.renderList.indexOf(_this);
  22018. if (meshIndex !== -1) {
  22019. shadowMap.renderList.splice(meshIndex, 1);
  22020. }
  22021. }
  22022. }
  22023. });
  22024. // SubMeshes
  22025. if (this.getClassName() !== "InstancedMesh") {
  22026. this.releaseSubMeshes();
  22027. }
  22028. // Query
  22029. var engine = this.getScene().getEngine();
  22030. if (this._occlusionQuery) {
  22031. this.isOcclusionQueryInProgress = false;
  22032. engine.deleteQuery(this._occlusionQuery);
  22033. this._occlusionQuery = null;
  22034. }
  22035. // Engine
  22036. engine.wipeCaches();
  22037. // Remove from scene
  22038. this.getScene().removeMesh(this);
  22039. if (disposeMaterialAndTextures) {
  22040. if (this.material) {
  22041. this.material.dispose(false, true);
  22042. }
  22043. }
  22044. if (!doNotRecurse) {
  22045. // Particles
  22046. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  22047. if (this.getScene().particleSystems[index].emitter === this) {
  22048. this.getScene().particleSystems[index].dispose();
  22049. index--;
  22050. }
  22051. }
  22052. }
  22053. // facet data
  22054. if (this._facetData.facetDataEnabled) {
  22055. this.disableFacetData();
  22056. }
  22057. this.onAfterWorldMatrixUpdateObservable.clear();
  22058. this.onCollideObservable.clear();
  22059. this.onCollisionPositionChangeObservable.clear();
  22060. this.onRebuildObservable.clear();
  22061. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22062. };
  22063. /**
  22064. * Adds the passed mesh as a child to the current mesh
  22065. * @param mesh defines the child mesh
  22066. * @returns the current mesh
  22067. */
  22068. AbstractMesh.prototype.addChild = function (mesh) {
  22069. mesh.setParent(this);
  22070. return this;
  22071. };
  22072. /**
  22073. * Removes the passed mesh from the current mesh children list
  22074. * @param mesh defines the child mesh
  22075. * @returns the current mesh
  22076. */
  22077. AbstractMesh.prototype.removeChild = function (mesh) {
  22078. mesh.setParent(null);
  22079. return this;
  22080. };
  22081. // Facet data
  22082. /** @hidden */
  22083. AbstractMesh.prototype._initFacetData = function () {
  22084. var data = this._facetData;
  22085. if (!data.facetNormals) {
  22086. data.facetNormals = new Array();
  22087. }
  22088. if (!data.facetPositions) {
  22089. data.facetPositions = new Array();
  22090. }
  22091. if (!data.facetPartitioning) {
  22092. data.facetPartitioning = new Array();
  22093. }
  22094. data.facetNb = (this.getIndices().length / 3) | 0;
  22095. data.partitioningSubdivisions = (data.partitioningSubdivisions) ? data.partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  22096. data.partitioningBBoxRatio = (data.partitioningBBoxRatio) ? data.partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  22097. for (var f = 0; f < data.facetNb; f++) {
  22098. data.facetNormals[f] = BABYLON.Vector3.Zero();
  22099. data.facetPositions[f] = BABYLON.Vector3.Zero();
  22100. }
  22101. data.facetDataEnabled = true;
  22102. return this;
  22103. };
  22104. /**
  22105. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  22106. * This method can be called within the render loop.
  22107. * 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
  22108. * @returns the current mesh
  22109. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22110. */
  22111. AbstractMesh.prototype.updateFacetData = function () {
  22112. var data = this._facetData;
  22113. if (!data.facetDataEnabled) {
  22114. this._initFacetData();
  22115. }
  22116. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22117. var indices = this.getIndices();
  22118. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22119. var bInfo = this.getBoundingInfo();
  22120. if (data.facetDepthSort && !data.facetDepthSortEnabled) {
  22121. // init arrays, matrix and sort function on first call
  22122. data.facetDepthSortEnabled = true;
  22123. if (indices instanceof Uint16Array) {
  22124. data.depthSortedIndices = new Uint16Array(indices);
  22125. }
  22126. else if (indices instanceof Uint32Array) {
  22127. data.depthSortedIndices = new Uint32Array(indices);
  22128. }
  22129. else {
  22130. var needs32bits = false;
  22131. for (var i = 0; i < indices.length; i++) {
  22132. if (indices[i] > 65535) {
  22133. needs32bits = true;
  22134. break;
  22135. }
  22136. }
  22137. if (needs32bits) {
  22138. data.depthSortedIndices = new Uint32Array(indices);
  22139. }
  22140. else {
  22141. data.depthSortedIndices = new Uint16Array(indices);
  22142. }
  22143. }
  22144. data.facetDepthSortFunction = function (f1, f2) {
  22145. return (f2.sqDistance - f1.sqDistance);
  22146. };
  22147. if (!data.facetDepthSortFrom) {
  22148. var camera = this.getScene().activeCamera;
  22149. data.facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  22150. }
  22151. data.depthSortedFacets = [];
  22152. for (var f = 0; f < data.facetNb; f++) {
  22153. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  22154. data.depthSortedFacets.push(depthSortedFacet);
  22155. }
  22156. data.invertedMatrix = BABYLON.Matrix.Identity();
  22157. data.facetDepthSortOrigin = BABYLON.Vector3.Zero();
  22158. }
  22159. data.bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  22160. data.bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  22161. data.bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  22162. var bbSizeMax = (data.bbSize.x > data.bbSize.y) ? data.bbSize.x : data.bbSize.y;
  22163. bbSizeMax = (bbSizeMax > data.bbSize.z) ? bbSizeMax : data.bbSize.z;
  22164. data.subDiv.max = data.partitioningSubdivisions;
  22165. data.subDiv.X = Math.floor(data.subDiv.max * data.bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  22166. data.subDiv.Y = Math.floor(data.subDiv.max * data.bbSize.y / bbSizeMax); // according to each bbox size per axis
  22167. data.subDiv.Z = Math.floor(data.subDiv.max * data.bbSize.z / bbSizeMax);
  22168. data.subDiv.X = data.subDiv.X < 1 ? 1 : data.subDiv.X; // at least one subdivision
  22169. data.subDiv.Y = data.subDiv.Y < 1 ? 1 : data.subDiv.Y;
  22170. data.subDiv.Z = data.subDiv.Z < 1 ? 1 : data.subDiv.Z;
  22171. // set the parameters for ComputeNormals()
  22172. data.facetParameters.facetNormals = this.getFacetLocalNormals();
  22173. data.facetParameters.facetPositions = this.getFacetLocalPositions();
  22174. data.facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  22175. data.facetParameters.bInfo = bInfo;
  22176. data.facetParameters.bbSize = data.bbSize;
  22177. data.facetParameters.subDiv = data.subDiv;
  22178. data.facetParameters.ratio = this.partitioningBBoxRatio;
  22179. data.facetParameters.depthSort = data.facetDepthSort;
  22180. if (data.facetDepthSort && data.facetDepthSortEnabled) {
  22181. this.computeWorldMatrix(true);
  22182. this._worldMatrix.invertToRef(data.invertedMatrix);
  22183. BABYLON.Vector3.TransformCoordinatesToRef(data.facetDepthSortFrom, data.invertedMatrix, data.facetDepthSortOrigin);
  22184. data.facetParameters.distanceTo = data.facetDepthSortOrigin;
  22185. }
  22186. data.facetParameters.depthSortedFacets = data.depthSortedFacets;
  22187. BABYLON.VertexData.ComputeNormals(positions, indices, normals, data.facetParameters);
  22188. if (data.facetDepthSort && data.facetDepthSortEnabled) {
  22189. data.depthSortedFacets.sort(data.facetDepthSortFunction);
  22190. var l = (data.depthSortedIndices.length / 3) | 0;
  22191. for (var f = 0; f < l; f++) {
  22192. var sind = data.depthSortedFacets[f].ind;
  22193. data.depthSortedIndices[f * 3] = indices[sind];
  22194. data.depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  22195. data.depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  22196. }
  22197. this.updateIndices(data.depthSortedIndices);
  22198. }
  22199. return this;
  22200. };
  22201. /**
  22202. * Returns the facetLocalNormals array.
  22203. * The normals are expressed in the mesh local spac
  22204. * @returns an array of Vector3
  22205. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22206. */
  22207. AbstractMesh.prototype.getFacetLocalNormals = function () {
  22208. if (!this._facetData.facetNormals) {
  22209. this.updateFacetData();
  22210. }
  22211. return this._facetData.facetNormals;
  22212. };
  22213. /**
  22214. * Returns the facetLocalPositions array.
  22215. * The facet positions are expressed in the mesh local space
  22216. * @returns an array of Vector3
  22217. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22218. */
  22219. AbstractMesh.prototype.getFacetLocalPositions = function () {
  22220. if (!this._facetData.facetPositions) {
  22221. this.updateFacetData();
  22222. }
  22223. return this._facetData.facetPositions;
  22224. };
  22225. /**
  22226. * Returns the facetLocalPartioning array
  22227. * @returns an array of array of numbers
  22228. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22229. */
  22230. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  22231. if (!this._facetData.facetPartitioning) {
  22232. this.updateFacetData();
  22233. }
  22234. return this._facetData.facetPartitioning;
  22235. };
  22236. /**
  22237. * Returns the i-th facet position in the world system.
  22238. * This method allocates a new Vector3 per call
  22239. * @param i defines the facet index
  22240. * @returns a new Vector3
  22241. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22242. */
  22243. AbstractMesh.prototype.getFacetPosition = function (i) {
  22244. var pos = BABYLON.Vector3.Zero();
  22245. this.getFacetPositionToRef(i, pos);
  22246. return pos;
  22247. };
  22248. /**
  22249. * Sets the reference Vector3 with the i-th facet position in the world system
  22250. * @param i defines the facet index
  22251. * @param ref defines the target vector
  22252. * @returns the current mesh
  22253. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22254. */
  22255. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  22256. var localPos = (this.getFacetLocalPositions())[i];
  22257. var world = this.getWorldMatrix();
  22258. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  22259. return this;
  22260. };
  22261. /**
  22262. * Returns the i-th facet normal in the world system.
  22263. * This method allocates a new Vector3 per call
  22264. * @param i defines the facet index
  22265. * @returns a new Vector3
  22266. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22267. */
  22268. AbstractMesh.prototype.getFacetNormal = function (i) {
  22269. var norm = BABYLON.Vector3.Zero();
  22270. this.getFacetNormalToRef(i, norm);
  22271. return norm;
  22272. };
  22273. /**
  22274. * Sets the reference Vector3 with the i-th facet normal in the world system
  22275. * @param i defines the facet index
  22276. * @param ref defines the target vector
  22277. * @returns the current mesh
  22278. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22279. */
  22280. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  22281. var localNorm = (this.getFacetLocalNormals())[i];
  22282. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  22283. return this;
  22284. };
  22285. /**
  22286. * 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)
  22287. * @param x defines x coordinate
  22288. * @param y defines y coordinate
  22289. * @param z defines z coordinate
  22290. * @returns the array of facet indexes
  22291. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22292. */
  22293. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  22294. var bInfo = this.getBoundingInfo();
  22295. var data = this._facetData;
  22296. var ox = Math.floor((x - bInfo.minimum.x * data.partitioningBBoxRatio) * data.subDiv.X * data.partitioningBBoxRatio / data.bbSize.x);
  22297. var oy = Math.floor((y - bInfo.minimum.y * data.partitioningBBoxRatio) * data.subDiv.Y * data.partitioningBBoxRatio / data.bbSize.y);
  22298. var oz = Math.floor((z - bInfo.minimum.z * data.partitioningBBoxRatio) * data.subDiv.Z * data.partitioningBBoxRatio / data.bbSize.z);
  22299. if (ox < 0 || ox > data.subDiv.max || oy < 0 || oy > data.subDiv.max || oz < 0 || oz > data.subDiv.max) {
  22300. return null;
  22301. }
  22302. return data.facetPartitioning[ox + data.subDiv.max * oy + data.subDiv.max * data.subDiv.max * oz];
  22303. };
  22304. /**
  22305. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  22306. * @param projected sets as the (x,y,z) world projection on the facet
  22307. * @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
  22308. * @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
  22309. * @param x defines x coordinate
  22310. * @param y defines y coordinate
  22311. * @param z defines z coordinate
  22312. * @returns the face index if found (or null instead)
  22313. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22314. */
  22315. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  22316. if (checkFace === void 0) { checkFace = false; }
  22317. if (facing === void 0) { facing = true; }
  22318. var world = this.getWorldMatrix();
  22319. var invMat = BABYLON.Tmp.Matrix[5];
  22320. world.invertToRef(invMat);
  22321. var invVect = BABYLON.Tmp.Vector3[8];
  22322. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  22323. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  22324. if (projected) {
  22325. // tranform the local computed projected vector to world coordinates
  22326. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  22327. }
  22328. return closest;
  22329. };
  22330. /**
  22331. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  22332. * @param projected sets as the (x,y,z) local projection on the facet
  22333. * @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
  22334. * @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
  22335. * @param x defines x coordinate
  22336. * @param y defines y coordinate
  22337. * @param z defines z coordinate
  22338. * @returns the face index if found (or null instead)
  22339. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22340. */
  22341. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  22342. if (checkFace === void 0) { checkFace = false; }
  22343. if (facing === void 0) { facing = true; }
  22344. var closest = null;
  22345. var tmpx = 0.0;
  22346. var tmpy = 0.0;
  22347. var tmpz = 0.0;
  22348. var d = 0.0; // tmp dot facet normal * facet position
  22349. var t0 = 0.0;
  22350. var projx = 0.0;
  22351. var projy = 0.0;
  22352. var projz = 0.0;
  22353. // Get all the facets in the same partitioning block than (x, y, z)
  22354. var facetPositions = this.getFacetLocalPositions();
  22355. var facetNormals = this.getFacetLocalNormals();
  22356. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  22357. if (!facetsInBlock) {
  22358. return null;
  22359. }
  22360. // Get the closest facet to (x, y, z)
  22361. var shortest = Number.MAX_VALUE; // init distance vars
  22362. var tmpDistance = shortest;
  22363. var fib; // current facet in the block
  22364. var norm; // current facet normal
  22365. var p0; // current facet barycenter position
  22366. // loop on all the facets in the current partitioning block
  22367. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  22368. fib = facetsInBlock[idx];
  22369. norm = facetNormals[fib];
  22370. p0 = facetPositions[fib];
  22371. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  22372. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  22373. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  22374. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  22375. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  22376. projx = x + norm.x * t0;
  22377. projy = y + norm.y * t0;
  22378. projz = z + norm.z * t0;
  22379. tmpx = projx - x;
  22380. tmpy = projy - y;
  22381. tmpz = projz - z;
  22382. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  22383. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  22384. shortest = tmpDistance;
  22385. closest = fib;
  22386. if (projected) {
  22387. projected.x = projx;
  22388. projected.y = projy;
  22389. projected.z = projz;
  22390. }
  22391. }
  22392. }
  22393. }
  22394. return closest;
  22395. };
  22396. /**
  22397. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  22398. * @returns the parameters
  22399. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22400. */
  22401. AbstractMesh.prototype.getFacetDataParameters = function () {
  22402. return this._facetData.facetParameters;
  22403. };
  22404. /**
  22405. * Disables the feature FacetData and frees the related memory
  22406. * @returns the current mesh
  22407. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22408. */
  22409. AbstractMesh.prototype.disableFacetData = function () {
  22410. if (this._facetData.facetDataEnabled) {
  22411. this._facetData.facetDataEnabled = false;
  22412. this._facetData.facetPositions = new Array();
  22413. this._facetData.facetNormals = new Array();
  22414. this._facetData.facetPartitioning = new Array();
  22415. this._facetData.facetParameters = null;
  22416. this._facetData.depthSortedIndices = new Uint32Array(0);
  22417. }
  22418. return this;
  22419. };
  22420. /**
  22421. * Updates the AbstractMesh indices array
  22422. * @param indices defines the data source
  22423. * @returns the current mesh
  22424. */
  22425. AbstractMesh.prototype.updateIndices = function (indices) {
  22426. return this;
  22427. };
  22428. /**
  22429. * Creates new normals data for the mesh
  22430. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  22431. * @returns the current mesh
  22432. */
  22433. AbstractMesh.prototype.createNormals = function (updatable) {
  22434. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22435. var indices = this.getIndices();
  22436. var normals;
  22437. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22438. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22439. }
  22440. else {
  22441. normals = [];
  22442. }
  22443. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  22444. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  22445. return this;
  22446. };
  22447. /**
  22448. * Align the mesh with a normal
  22449. * @param normal defines the normal to use
  22450. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  22451. * @returns the current mesh
  22452. */
  22453. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  22454. if (!upDirection) {
  22455. upDirection = BABYLON.Axis.Y;
  22456. }
  22457. var axisX = BABYLON.Tmp.Vector3[0];
  22458. var axisZ = BABYLON.Tmp.Vector3[1];
  22459. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  22460. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  22461. if (this.rotationQuaternion) {
  22462. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  22463. }
  22464. else {
  22465. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  22466. }
  22467. return this;
  22468. };
  22469. /** @hidden */
  22470. AbstractMesh.prototype._checkOcclusionQuery = function () {
  22471. return false;
  22472. };
  22473. /** No occlusion */
  22474. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  22475. /** Occlusion set to optimisitic */
  22476. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  22477. /** Occlusion set to strict */
  22478. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  22479. /** Use an accurante occlusion algorithm */
  22480. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  22481. /** Use a conservative occlusion algorithm */
  22482. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  22483. /** Default culling strategy with bounding box and bounding sphere and then frustum culling */
  22484. AbstractMesh.CULLINGSTRATEGY_STANDARD = 0;
  22485. /** Culling strategy with bounding sphere only and then frustum culling */
  22486. AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
  22487. return AbstractMesh;
  22488. }(BABYLON.TransformNode));
  22489. BABYLON.AbstractMesh = AbstractMesh;
  22490. })(BABYLON || (BABYLON = {}));
  22491. //# sourceMappingURL=babylon.abstractMesh.js.map
  22492. var BABYLON;
  22493. (function (BABYLON) {
  22494. /**
  22495. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  22496. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  22497. * 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.
  22498. */
  22499. var Light = /** @class */ (function (_super) {
  22500. __extends(Light, _super);
  22501. /**
  22502. * Creates a Light object in the scene.
  22503. * Documentation : http://doc.babylonjs.com/tutorials/lights
  22504. * @param name The firendly name of the light
  22505. * @param scene The scene the light belongs too
  22506. */
  22507. function Light(name, scene) {
  22508. var _this = _super.call(this, name, scene) || this;
  22509. /**
  22510. * Diffuse gives the basic color to an object.
  22511. */
  22512. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  22513. /**
  22514. * Specular produces a highlight color on an object.
  22515. * Note: This is note affecting PBR materials.
  22516. */
  22517. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  22518. /**
  22519. * Defines the falloff type for this light. This lets overrriding how punctual light are
  22520. * falling off base on range or angle.
  22521. * This can be set to any values in Light.FALLOFF_x.
  22522. *
  22523. * Note: This is only usefull for PBR Materials at the moment. This could be extended if required to
  22524. * other types of materials.
  22525. */
  22526. _this.falloffType = Light.FALLOFF_DEFAULT;
  22527. /**
  22528. * Strength of the light.
  22529. * Note: By default it is define in the framework own unit.
  22530. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  22531. */
  22532. _this.intensity = 1.0;
  22533. _this._range = Number.MAX_VALUE;
  22534. _this._inverseSquaredRange = 0;
  22535. /**
  22536. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  22537. * of light.
  22538. */
  22539. _this._photometricScale = 1.0;
  22540. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  22541. _this._radius = 0.00001;
  22542. /**
  22543. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  22544. * exceeding the number allowed of the materials.
  22545. */
  22546. _this.renderPriority = 0;
  22547. _this._shadowEnabled = true;
  22548. _this._excludeWithLayerMask = 0;
  22549. _this._includeOnlyWithLayerMask = 0;
  22550. _this._lightmapMode = 0;
  22551. /**
  22552. * @hidden Internal use only.
  22553. */
  22554. _this._excludedMeshesIds = new Array();
  22555. /**
  22556. * @hidden Internal use only.
  22557. */
  22558. _this._includedOnlyMeshesIds = new Array();
  22559. _this.getScene().addLight(_this);
  22560. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  22561. _this._buildUniformLayout();
  22562. _this.includedOnlyMeshes = new Array();
  22563. _this.excludedMeshes = new Array();
  22564. _this._resyncMeshes();
  22565. return _this;
  22566. }
  22567. Object.defineProperty(Light.prototype, "range", {
  22568. /**
  22569. * Defines how far from the source the light is impacting in scene units.
  22570. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  22571. */
  22572. get: function () {
  22573. return this._range;
  22574. },
  22575. /**
  22576. * Defines how far from the source the light is impacting in scene units.
  22577. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  22578. */
  22579. set: function (value) {
  22580. this._range = value;
  22581. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  22582. },
  22583. enumerable: true,
  22584. configurable: true
  22585. });
  22586. Object.defineProperty(Light.prototype, "intensityMode", {
  22587. /**
  22588. * Gets the photometric scale used to interpret the intensity.
  22589. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  22590. */
  22591. get: function () {
  22592. return this._intensityMode;
  22593. },
  22594. /**
  22595. * Sets the photometric scale used to interpret the intensity.
  22596. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  22597. */
  22598. set: function (value) {
  22599. this._intensityMode = value;
  22600. this._computePhotometricScale();
  22601. },
  22602. enumerable: true,
  22603. configurable: true
  22604. });
  22605. Object.defineProperty(Light.prototype, "radius", {
  22606. /**
  22607. * Gets the light radius used by PBR Materials to simulate soft area lights.
  22608. */
  22609. get: function () {
  22610. return this._radius;
  22611. },
  22612. /**
  22613. * sets the light radius used by PBR Materials to simulate soft area lights.
  22614. */
  22615. set: function (value) {
  22616. this._radius = value;
  22617. this._computePhotometricScale();
  22618. },
  22619. enumerable: true,
  22620. configurable: true
  22621. });
  22622. Object.defineProperty(Light.prototype, "shadowEnabled", {
  22623. /**
  22624. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  22625. * the current shadow generator.
  22626. */
  22627. get: function () {
  22628. return this._shadowEnabled;
  22629. },
  22630. /**
  22631. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  22632. * the current shadow generator.
  22633. */
  22634. set: function (value) {
  22635. if (this._shadowEnabled === value) {
  22636. return;
  22637. }
  22638. this._shadowEnabled = value;
  22639. this._markMeshesAsLightDirty();
  22640. },
  22641. enumerable: true,
  22642. configurable: true
  22643. });
  22644. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  22645. /**
  22646. * Gets the only meshes impacted by this light.
  22647. */
  22648. get: function () {
  22649. return this._includedOnlyMeshes;
  22650. },
  22651. /**
  22652. * Sets the only meshes impacted by this light.
  22653. */
  22654. set: function (value) {
  22655. this._includedOnlyMeshes = value;
  22656. this._hookArrayForIncludedOnly(value);
  22657. },
  22658. enumerable: true,
  22659. configurable: true
  22660. });
  22661. Object.defineProperty(Light.prototype, "excludedMeshes", {
  22662. /**
  22663. * Gets the meshes not impacted by this light.
  22664. */
  22665. get: function () {
  22666. return this._excludedMeshes;
  22667. },
  22668. /**
  22669. * Sets the meshes not impacted by this light.
  22670. */
  22671. set: function (value) {
  22672. this._excludedMeshes = value;
  22673. this._hookArrayForExcluded(value);
  22674. },
  22675. enumerable: true,
  22676. configurable: true
  22677. });
  22678. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  22679. /**
  22680. * Gets the layer id use to find what meshes are not impacted by the light.
  22681. * Inactive if 0
  22682. */
  22683. get: function () {
  22684. return this._excludeWithLayerMask;
  22685. },
  22686. /**
  22687. * Sets the layer id use to find what meshes are not impacted by the light.
  22688. * Inactive if 0
  22689. */
  22690. set: function (value) {
  22691. this._excludeWithLayerMask = value;
  22692. this._resyncMeshes();
  22693. },
  22694. enumerable: true,
  22695. configurable: true
  22696. });
  22697. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  22698. /**
  22699. * Gets the layer id use to find what meshes are impacted by the light.
  22700. * Inactive if 0
  22701. */
  22702. get: function () {
  22703. return this._includeOnlyWithLayerMask;
  22704. },
  22705. /**
  22706. * Sets the layer id use to find what meshes are impacted by the light.
  22707. * Inactive if 0
  22708. */
  22709. set: function (value) {
  22710. this._includeOnlyWithLayerMask = value;
  22711. this._resyncMeshes();
  22712. },
  22713. enumerable: true,
  22714. configurable: true
  22715. });
  22716. Object.defineProperty(Light.prototype, "lightmapMode", {
  22717. /**
  22718. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  22719. */
  22720. get: function () {
  22721. return this._lightmapMode;
  22722. },
  22723. /**
  22724. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  22725. */
  22726. set: function (value) {
  22727. if (this._lightmapMode === value) {
  22728. return;
  22729. }
  22730. this._lightmapMode = value;
  22731. this._markMeshesAsLightDirty();
  22732. },
  22733. enumerable: true,
  22734. configurable: true
  22735. });
  22736. /**
  22737. * Returns the string "Light".
  22738. * @returns the class name
  22739. */
  22740. Light.prototype.getClassName = function () {
  22741. return "Light";
  22742. };
  22743. /**
  22744. * Converts the light information to a readable string for debug purpose.
  22745. * @param fullDetails Supports for multiple levels of logging within scene loading
  22746. * @returns the human readable light info
  22747. */
  22748. Light.prototype.toString = function (fullDetails) {
  22749. var ret = "Name: " + this.name;
  22750. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  22751. if (this.animations) {
  22752. for (var i = 0; i < this.animations.length; i++) {
  22753. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22754. }
  22755. }
  22756. if (fullDetails) {
  22757. }
  22758. return ret;
  22759. };
  22760. /** @hidden */
  22761. Light.prototype._syncParentEnabledState = function () {
  22762. _super.prototype._syncParentEnabledState.call(this);
  22763. this._resyncMeshes();
  22764. };
  22765. /**
  22766. * Set the enabled state of this node.
  22767. * @param value - the new enabled state
  22768. */
  22769. Light.prototype.setEnabled = function (value) {
  22770. _super.prototype.setEnabled.call(this, value);
  22771. this._resyncMeshes();
  22772. };
  22773. /**
  22774. * Returns the Light associated shadow generator if any.
  22775. * @return the associated shadow generator.
  22776. */
  22777. Light.prototype.getShadowGenerator = function () {
  22778. return this._shadowGenerator;
  22779. };
  22780. /**
  22781. * Returns a Vector3, the absolute light position in the World.
  22782. * @returns the world space position of the light
  22783. */
  22784. Light.prototype.getAbsolutePosition = function () {
  22785. return BABYLON.Vector3.Zero();
  22786. };
  22787. /**
  22788. * Specifies if the light will affect the passed mesh.
  22789. * @param mesh The mesh to test against the light
  22790. * @return true the mesh is affected otherwise, false.
  22791. */
  22792. Light.prototype.canAffectMesh = function (mesh) {
  22793. if (!mesh) {
  22794. return true;
  22795. }
  22796. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  22797. return false;
  22798. }
  22799. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  22800. return false;
  22801. }
  22802. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  22803. return false;
  22804. }
  22805. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  22806. return false;
  22807. }
  22808. return true;
  22809. };
  22810. /**
  22811. * Sort function to order lights for rendering.
  22812. * @param a First Light object to compare to second.
  22813. * @param b Second Light object to compare first.
  22814. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  22815. */
  22816. Light.CompareLightsPriority = function (a, b) {
  22817. //shadow-casting lights have priority over non-shadow-casting lights
  22818. //the renderPrioirty is a secondary sort criterion
  22819. if (a.shadowEnabled !== b.shadowEnabled) {
  22820. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  22821. }
  22822. return b.renderPriority - a.renderPriority;
  22823. };
  22824. /**
  22825. * Releases resources associated with this node.
  22826. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22827. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22828. */
  22829. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22830. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22831. if (this._shadowGenerator) {
  22832. this._shadowGenerator.dispose();
  22833. this._shadowGenerator = null;
  22834. }
  22835. // Animations
  22836. this.getScene().stopAnimation(this);
  22837. // Remove from meshes
  22838. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22839. var mesh = _a[_i];
  22840. mesh._removeLightSource(this);
  22841. }
  22842. this._uniformBuffer.dispose();
  22843. // Remove from scene
  22844. this.getScene().removeLight(this);
  22845. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22846. };
  22847. /**
  22848. * Returns the light type ID (integer).
  22849. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  22850. */
  22851. Light.prototype.getTypeID = function () {
  22852. return 0;
  22853. };
  22854. /**
  22855. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  22856. * @returns the scaled intensity in intensity mode unit
  22857. */
  22858. Light.prototype.getScaledIntensity = function () {
  22859. return this._photometricScale * this.intensity;
  22860. };
  22861. /**
  22862. * Returns a new Light object, named "name", from the current one.
  22863. * @param name The name of the cloned light
  22864. * @returns the new created light
  22865. */
  22866. Light.prototype.clone = function (name) {
  22867. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  22868. if (!constructor) {
  22869. return null;
  22870. }
  22871. return BABYLON.SerializationHelper.Clone(constructor, this);
  22872. };
  22873. /**
  22874. * Serializes the current light into a Serialization object.
  22875. * @returns the serialized object.
  22876. */
  22877. Light.prototype.serialize = function () {
  22878. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22879. // Type
  22880. serializationObject.type = this.getTypeID();
  22881. // Parent
  22882. if (this.parent) {
  22883. serializationObject.parentId = this.parent.id;
  22884. }
  22885. // Inclusion / exclusions
  22886. if (this.excludedMeshes.length > 0) {
  22887. serializationObject.excludedMeshesIds = [];
  22888. this.excludedMeshes.forEach(function (mesh) {
  22889. serializationObject.excludedMeshesIds.push(mesh.id);
  22890. });
  22891. }
  22892. if (this.includedOnlyMeshes.length > 0) {
  22893. serializationObject.includedOnlyMeshesIds = [];
  22894. this.includedOnlyMeshes.forEach(function (mesh) {
  22895. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  22896. });
  22897. }
  22898. // Animations
  22899. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22900. serializationObject.ranges = this.serializeAnimationRanges();
  22901. return serializationObject;
  22902. };
  22903. /**
  22904. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  22905. * This new light is named "name" and added to the passed scene.
  22906. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  22907. * @param name The friendly name of the light
  22908. * @param scene The scene the new light will belong to
  22909. * @returns the constructor function
  22910. */
  22911. Light.GetConstructorFromName = function (type, name, scene) {
  22912. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  22913. if (constructorFunc) {
  22914. return constructorFunc;
  22915. }
  22916. // Default to no light for none present once.
  22917. return null;
  22918. };
  22919. /**
  22920. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  22921. * @param parsedLight The JSON representation of the light
  22922. * @param scene The scene to create the parsed light in
  22923. * @returns the created light after parsing
  22924. */
  22925. Light.Parse = function (parsedLight, scene) {
  22926. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  22927. if (!constructor) {
  22928. return null;
  22929. }
  22930. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  22931. // Inclusion / exclusions
  22932. if (parsedLight.excludedMeshesIds) {
  22933. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  22934. }
  22935. if (parsedLight.includedOnlyMeshesIds) {
  22936. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  22937. }
  22938. // Parent
  22939. if (parsedLight.parentId) {
  22940. light._waitingParentId = parsedLight.parentId;
  22941. }
  22942. // Animations
  22943. if (parsedLight.animations) {
  22944. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  22945. var parsedAnimation = parsedLight.animations[animationIndex];
  22946. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22947. }
  22948. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  22949. }
  22950. if (parsedLight.autoAnimate) {
  22951. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  22952. }
  22953. return light;
  22954. };
  22955. Light.prototype._hookArrayForExcluded = function (array) {
  22956. var _this = this;
  22957. var oldPush = array.push;
  22958. array.push = function () {
  22959. var items = [];
  22960. for (var _i = 0; _i < arguments.length; _i++) {
  22961. items[_i] = arguments[_i];
  22962. }
  22963. var result = oldPush.apply(array, items);
  22964. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  22965. var item = items_1[_a];
  22966. item._resyncLighSource(_this);
  22967. }
  22968. return result;
  22969. };
  22970. var oldSplice = array.splice;
  22971. array.splice = function (index, deleteCount) {
  22972. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22973. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  22974. var item = deleted_1[_i];
  22975. item._resyncLighSource(_this);
  22976. }
  22977. return deleted;
  22978. };
  22979. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  22980. var item = array_1[_i];
  22981. item._resyncLighSource(this);
  22982. }
  22983. };
  22984. Light.prototype._hookArrayForIncludedOnly = function (array) {
  22985. var _this = this;
  22986. var oldPush = array.push;
  22987. array.push = function () {
  22988. var items = [];
  22989. for (var _i = 0; _i < arguments.length; _i++) {
  22990. items[_i] = arguments[_i];
  22991. }
  22992. var result = oldPush.apply(array, items);
  22993. _this._resyncMeshes();
  22994. return result;
  22995. };
  22996. var oldSplice = array.splice;
  22997. array.splice = function (index, deleteCount) {
  22998. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22999. _this._resyncMeshes();
  23000. return deleted;
  23001. };
  23002. this._resyncMeshes();
  23003. };
  23004. Light.prototype._resyncMeshes = function () {
  23005. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  23006. var mesh = _a[_i];
  23007. mesh._resyncLighSource(this);
  23008. }
  23009. };
  23010. /**
  23011. * Forces the meshes to update their light related information in their rendering used effects
  23012. * @hidden Internal Use Only
  23013. */
  23014. Light.prototype._markMeshesAsLightDirty = function () {
  23015. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  23016. var mesh = _a[_i];
  23017. if (mesh._lightSources.indexOf(this) !== -1) {
  23018. mesh._markSubMeshesAsLightDirty();
  23019. }
  23020. }
  23021. };
  23022. /**
  23023. * Recomputes the cached photometric scale if needed.
  23024. */
  23025. Light.prototype._computePhotometricScale = function () {
  23026. this._photometricScale = this._getPhotometricScale();
  23027. this.getScene().resetCachedMaterial();
  23028. };
  23029. /**
  23030. * Returns the Photometric Scale according to the light type and intensity mode.
  23031. */
  23032. Light.prototype._getPhotometricScale = function () {
  23033. var photometricScale = 0.0;
  23034. var lightTypeID = this.getTypeID();
  23035. //get photometric mode
  23036. var photometricMode = this.intensityMode;
  23037. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  23038. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  23039. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  23040. }
  23041. else {
  23042. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  23043. }
  23044. }
  23045. //compute photometric scale
  23046. switch (lightTypeID) {
  23047. case Light.LIGHTTYPEID_POINTLIGHT:
  23048. case Light.LIGHTTYPEID_SPOTLIGHT:
  23049. switch (photometricMode) {
  23050. case Light.INTENSITYMODE_LUMINOUSPOWER:
  23051. photometricScale = 1.0 / (4.0 * Math.PI);
  23052. break;
  23053. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  23054. photometricScale = 1.0;
  23055. break;
  23056. case Light.INTENSITYMODE_LUMINANCE:
  23057. photometricScale = this.radius * this.radius;
  23058. break;
  23059. }
  23060. break;
  23061. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  23062. switch (photometricMode) {
  23063. case Light.INTENSITYMODE_ILLUMINANCE:
  23064. photometricScale = 1.0;
  23065. break;
  23066. case Light.INTENSITYMODE_LUMINANCE:
  23067. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  23068. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  23069. var apexAngleRadians = this.radius;
  23070. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  23071. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  23072. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  23073. photometricScale = solidAngle;
  23074. break;
  23075. }
  23076. break;
  23077. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  23078. // No fall off in hemisperic light.
  23079. photometricScale = 1.0;
  23080. break;
  23081. }
  23082. return photometricScale;
  23083. };
  23084. /**
  23085. * Reorder the light in the scene according to their defined priority.
  23086. * @hidden Internal Use Only
  23087. */
  23088. Light.prototype._reorderLightsInScene = function () {
  23089. var scene = this.getScene();
  23090. if (this._renderPriority != 0) {
  23091. scene.requireLightSorting = true;
  23092. }
  23093. this.getScene().sortLightsByPriority();
  23094. };
  23095. /**
  23096. * Falloff Default: light is falling off following the material specification:
  23097. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  23098. */
  23099. Light.FALLOFF_DEFAULT = 0;
  23100. /**
  23101. * Falloff Physical: light is falling off following the inverse squared distance law.
  23102. */
  23103. Light.FALLOFF_PHYSICAL = 1;
  23104. /**
  23105. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  23106. * to enhance interoperability with other engines.
  23107. */
  23108. Light.FALLOFF_GLTF = 2;
  23109. /**
  23110. * Falloff Standard: light is falling off like in the standard material
  23111. * to enhance interoperability with other materials.
  23112. */
  23113. Light.FALLOFF_STANDARD = 3;
  23114. //lightmapMode Consts
  23115. /**
  23116. * If every light affecting the material is in this lightmapMode,
  23117. * material.lightmapTexture adds or multiplies
  23118. * (depends on material.useLightmapAsShadowmap)
  23119. * after every other light calculations.
  23120. */
  23121. Light.LIGHTMAP_DEFAULT = 0;
  23122. /**
  23123. * material.lightmapTexture as only diffuse lighting from this light
  23124. * adds only specular lighting from this light
  23125. * adds dynamic shadows
  23126. */
  23127. Light.LIGHTMAP_SPECULAR = 1;
  23128. /**
  23129. * material.lightmapTexture as only lighting
  23130. * no light calculation from this light
  23131. * only adds dynamic shadows from this light
  23132. */
  23133. Light.LIGHTMAP_SHADOWSONLY = 2;
  23134. // Intensity Mode Consts
  23135. /**
  23136. * Each light type uses the default quantity according to its type:
  23137. * point/spot lights use luminous intensity
  23138. * directional lights use illuminance
  23139. */
  23140. Light.INTENSITYMODE_AUTOMATIC = 0;
  23141. /**
  23142. * lumen (lm)
  23143. */
  23144. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  23145. /**
  23146. * candela (lm/sr)
  23147. */
  23148. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  23149. /**
  23150. * lux (lm/m^2)
  23151. */
  23152. Light.INTENSITYMODE_ILLUMINANCE = 3;
  23153. /**
  23154. * nit (cd/m^2)
  23155. */
  23156. Light.INTENSITYMODE_LUMINANCE = 4;
  23157. // Light types ids const.
  23158. /**
  23159. * Light type const id of the point light.
  23160. */
  23161. Light.LIGHTTYPEID_POINTLIGHT = 0;
  23162. /**
  23163. * Light type const id of the directional light.
  23164. */
  23165. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  23166. /**
  23167. * Light type const id of the spot light.
  23168. */
  23169. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  23170. /**
  23171. * Light type const id of the hemispheric light.
  23172. */
  23173. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  23174. __decorate([
  23175. BABYLON.serializeAsColor3()
  23176. ], Light.prototype, "diffuse", void 0);
  23177. __decorate([
  23178. BABYLON.serializeAsColor3()
  23179. ], Light.prototype, "specular", void 0);
  23180. __decorate([
  23181. BABYLON.serialize()
  23182. ], Light.prototype, "falloffType", void 0);
  23183. __decorate([
  23184. BABYLON.serialize()
  23185. ], Light.prototype, "intensity", void 0);
  23186. __decorate([
  23187. BABYLON.serialize()
  23188. ], Light.prototype, "range", null);
  23189. __decorate([
  23190. BABYLON.serialize()
  23191. ], Light.prototype, "intensityMode", null);
  23192. __decorate([
  23193. BABYLON.serialize()
  23194. ], Light.prototype, "radius", null);
  23195. __decorate([
  23196. BABYLON.serialize()
  23197. ], Light.prototype, "_renderPriority", void 0);
  23198. __decorate([
  23199. BABYLON.expandToProperty("_reorderLightsInScene")
  23200. ], Light.prototype, "renderPriority", void 0);
  23201. __decorate([
  23202. BABYLON.serialize("shadowEnabled")
  23203. ], Light.prototype, "_shadowEnabled", void 0);
  23204. __decorate([
  23205. BABYLON.serialize("excludeWithLayerMask")
  23206. ], Light.prototype, "_excludeWithLayerMask", void 0);
  23207. __decorate([
  23208. BABYLON.serialize("includeOnlyWithLayerMask")
  23209. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  23210. __decorate([
  23211. BABYLON.serialize("lightmapMode")
  23212. ], Light.prototype, "_lightmapMode", void 0);
  23213. return Light;
  23214. }(BABYLON.Node));
  23215. BABYLON.Light = Light;
  23216. })(BABYLON || (BABYLON = {}));
  23217. //# sourceMappingURL=babylon.light.js.map
  23218. var BABYLON;
  23219. (function (BABYLON) {
  23220. /**
  23221. * This is the base class of all the camera used in the application.
  23222. * @see http://doc.babylonjs.com/features/cameras
  23223. */
  23224. var Camera = /** @class */ (function (_super) {
  23225. __extends(Camera, _super);
  23226. /**
  23227. * Instantiates a new camera object.
  23228. * This should not be used directly but through the inherited cameras: ArcRotate, Free...
  23229. * @see http://doc.babylonjs.com/features/cameras
  23230. * @param name Defines the name of the camera in the scene
  23231. * @param position Defines the position of the camera
  23232. * @param scene Defines the scene the camera belongs too
  23233. * @param setActiveOnSceneIfNoneActive Defines if the camera should be set as active after creation if no other camera have been defined in the scene
  23234. */
  23235. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  23236. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  23237. var _this = _super.call(this, name, scene) || this;
  23238. /**
  23239. * The vector the camera should consider as up.
  23240. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  23241. */
  23242. _this.upVector = BABYLON.Vector3.Up();
  23243. /**
  23244. * Define the current limit on the left side for an orthographic camera
  23245. * In scene unit
  23246. */
  23247. _this.orthoLeft = null;
  23248. /**
  23249. * Define the current limit on the right side for an orthographic camera
  23250. * In scene unit
  23251. */
  23252. _this.orthoRight = null;
  23253. /**
  23254. * Define the current limit on the bottom side for an orthographic camera
  23255. * In scene unit
  23256. */
  23257. _this.orthoBottom = null;
  23258. /**
  23259. * Define the current limit on the top side for an orthographic camera
  23260. * In scene unit
  23261. */
  23262. _this.orthoTop = null;
  23263. /**
  23264. * Field Of View is set in Radians. (default is 0.8)
  23265. */
  23266. _this.fov = 0.8;
  23267. /**
  23268. * Define the minimum distance the camera can see from.
  23269. * This is important to note that the depth buffer are not infinite and the closer it starts
  23270. * the more your scene might encounter depth fighting issue.
  23271. */
  23272. _this.minZ = 1;
  23273. /**
  23274. * Define the maximum distance the camera can see to.
  23275. * This is important to note that the depth buffer are not infinite and the further it end
  23276. * the more your scene might encounter depth fighting issue.
  23277. */
  23278. _this.maxZ = 10000.0;
  23279. /**
  23280. * Define the default inertia of the camera.
  23281. * This helps giving a smooth feeling to the camera movement.
  23282. */
  23283. _this.inertia = 0.9;
  23284. /**
  23285. * Define the mode of the camera (Camera.PERSPECTIVE_CAMERA or Camera.PERSPECTIVE_ORTHOGRAPHIC)
  23286. */
  23287. _this.mode = Camera.PERSPECTIVE_CAMERA;
  23288. /**
  23289. * Define wether the camera is intermediate.
  23290. * This is usefull to not present the output directly to the screen in case of rig without post process for instance
  23291. */
  23292. _this.isIntermediate = false;
  23293. /**
  23294. * Define the viewport of the camera.
  23295. * This correspond to the portion of the screen the camera will render to in normalized 0 to 1 unit.
  23296. */
  23297. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  23298. /**
  23299. * Restricts the camera to viewing objects with the same layerMask.
  23300. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  23301. */
  23302. _this.layerMask = 0x0FFFFFFF;
  23303. /**
  23304. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  23305. */
  23306. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  23307. /**
  23308. * Rig mode of the camera.
  23309. * This is usefull to create the camera with two "eyes" instead of one to create VR or stereoscopic scenes.
  23310. * This is normally controlled byt the camera themselves as internal use.
  23311. */
  23312. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  23313. /**
  23314. * Defines the list of custom render target the camera should render to.
  23315. * This is pretty helpfull if you wish to make a camera render to a texture you could reuse somewhere
  23316. * else in the scene.
  23317. */
  23318. _this.customRenderTargets = new Array();
  23319. /**
  23320. * Observable triggered when the camera view matrix has changed.
  23321. */
  23322. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  23323. /**
  23324. * Observable triggered when the camera Projection matrix has changed.
  23325. */
  23326. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  23327. /**
  23328. * Observable triggered when the inputs have been processed.
  23329. */
  23330. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  23331. /**
  23332. * Observable triggered when reset has been called and applied to the camera.
  23333. */
  23334. _this.onRestoreStateObservable = new BABYLON.Observable();
  23335. /** @hidden */
  23336. _this._rigCameras = new Array();
  23337. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  23338. /** @hidden */
  23339. _this._skipRendering = false;
  23340. /** @hidden */
  23341. _this._projectionMatrix = new BABYLON.Matrix();
  23342. /** @hidden */
  23343. _this._postProcesses = new Array();
  23344. /** @hidden */
  23345. _this._activeMeshes = new BABYLON.SmartArray(256);
  23346. _this._globalPosition = BABYLON.Vector3.Zero();
  23347. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  23348. _this._doNotComputeProjectionMatrix = false;
  23349. _this._transformMatrix = BABYLON.Matrix.Zero();
  23350. _this._refreshFrustumPlanes = true;
  23351. _this.getScene().addCamera(_this);
  23352. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  23353. _this.getScene().activeCamera = _this;
  23354. }
  23355. _this.position = position;
  23356. return _this;
  23357. }
  23358. /**
  23359. * Store current camera state (fov, position, etc..)
  23360. * @returns the camera
  23361. */
  23362. Camera.prototype.storeState = function () {
  23363. this._stateStored = true;
  23364. this._storedFov = this.fov;
  23365. return this;
  23366. };
  23367. /**
  23368. * Restores the camera state values if it has been stored. You must call storeState() first
  23369. */
  23370. Camera.prototype._restoreStateValues = function () {
  23371. if (!this._stateStored) {
  23372. return false;
  23373. }
  23374. this.fov = this._storedFov;
  23375. return true;
  23376. };
  23377. /**
  23378. * Restored camera state. You must call storeState() first.
  23379. * @returns true if restored and false otherwise
  23380. */
  23381. Camera.prototype.restoreState = function () {
  23382. if (this._restoreStateValues()) {
  23383. this.onRestoreStateObservable.notifyObservers(this);
  23384. return true;
  23385. }
  23386. return false;
  23387. };
  23388. /**
  23389. * Gets the class name of the camera.
  23390. * @returns the class name
  23391. */
  23392. Camera.prototype.getClassName = function () {
  23393. return "Camera";
  23394. };
  23395. /**
  23396. * Gets a string representation of the camera usefull for debug purpose.
  23397. * @param fullDetails Defines that a more verboe level of logging is required
  23398. * @returns the string representation
  23399. */
  23400. Camera.prototype.toString = function (fullDetails) {
  23401. var ret = "Name: " + this.name;
  23402. ret += ", type: " + this.getClassName();
  23403. if (this.animations) {
  23404. for (var i = 0; i < this.animations.length; i++) {
  23405. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  23406. }
  23407. }
  23408. if (fullDetails) {
  23409. }
  23410. return ret;
  23411. };
  23412. Object.defineProperty(Camera.prototype, "globalPosition", {
  23413. /**
  23414. * Gets the current world space position of the camera.
  23415. */
  23416. get: function () {
  23417. return this._globalPosition;
  23418. },
  23419. enumerable: true,
  23420. configurable: true
  23421. });
  23422. /**
  23423. * Gets the list of active meshes this frame (meshes no culled or excluded by lod s in the frame)
  23424. * @returns the active meshe list
  23425. */
  23426. Camera.prototype.getActiveMeshes = function () {
  23427. return this._activeMeshes;
  23428. };
  23429. /**
  23430. * Check wether a mesh is part of the current active mesh list of the camera
  23431. * @param mesh Defines the mesh to check
  23432. * @returns true if active, false otherwise
  23433. */
  23434. Camera.prototype.isActiveMesh = function (mesh) {
  23435. return (this._activeMeshes.indexOf(mesh) !== -1);
  23436. };
  23437. /**
  23438. * Is this camera ready to be used/rendered
  23439. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  23440. * @return true if the camera is ready
  23441. */
  23442. Camera.prototype.isReady = function (completeCheck) {
  23443. if (completeCheck === void 0) { completeCheck = false; }
  23444. if (completeCheck) {
  23445. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  23446. var pp = _a[_i];
  23447. if (pp && !pp.isReady()) {
  23448. return false;
  23449. }
  23450. }
  23451. }
  23452. return _super.prototype.isReady.call(this, completeCheck);
  23453. };
  23454. /** @hidden */
  23455. Camera.prototype._initCache = function () {
  23456. _super.prototype._initCache.call(this);
  23457. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  23458. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  23459. this._cache.mode = undefined;
  23460. this._cache.minZ = undefined;
  23461. this._cache.maxZ = undefined;
  23462. this._cache.fov = undefined;
  23463. this._cache.fovMode = undefined;
  23464. this._cache.aspectRatio = undefined;
  23465. this._cache.orthoLeft = undefined;
  23466. this._cache.orthoRight = undefined;
  23467. this._cache.orthoBottom = undefined;
  23468. this._cache.orthoTop = undefined;
  23469. this._cache.renderWidth = undefined;
  23470. this._cache.renderHeight = undefined;
  23471. };
  23472. /** @hidden */
  23473. Camera.prototype._updateCache = function (ignoreParentClass) {
  23474. if (!ignoreParentClass) {
  23475. _super.prototype._updateCache.call(this);
  23476. }
  23477. this._cache.position.copyFrom(this.position);
  23478. this._cache.upVector.copyFrom(this.upVector);
  23479. };
  23480. /** @hidden */
  23481. Camera.prototype._isSynchronized = function () {
  23482. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  23483. };
  23484. /** @hidden */
  23485. Camera.prototype._isSynchronizedViewMatrix = function () {
  23486. if (!_super.prototype._isSynchronized.call(this)) {
  23487. return false;
  23488. }
  23489. return this._cache.position.equals(this.position)
  23490. && this._cache.upVector.equals(this.upVector)
  23491. && this.isSynchronizedWithParent();
  23492. };
  23493. /** @hidden */
  23494. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  23495. var check = this._cache.mode === this.mode
  23496. && this._cache.minZ === this.minZ
  23497. && this._cache.maxZ === this.maxZ;
  23498. if (!check) {
  23499. return false;
  23500. }
  23501. var engine = this.getEngine();
  23502. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  23503. check = this._cache.fov === this.fov
  23504. && this._cache.fovMode === this.fovMode
  23505. && this._cache.aspectRatio === engine.getAspectRatio(this);
  23506. }
  23507. else {
  23508. check = this._cache.orthoLeft === this.orthoLeft
  23509. && this._cache.orthoRight === this.orthoRight
  23510. && this._cache.orthoBottom === this.orthoBottom
  23511. && this._cache.orthoTop === this.orthoTop
  23512. && this._cache.renderWidth === engine.getRenderWidth()
  23513. && this._cache.renderHeight === engine.getRenderHeight();
  23514. }
  23515. return check;
  23516. };
  23517. /**
  23518. * Attach the input controls to a specific dom element to get the input from.
  23519. * @param element Defines the element the controls should be listened from
  23520. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  23521. */
  23522. Camera.prototype.attachControl = function (element, noPreventDefault) {
  23523. };
  23524. /**
  23525. * Detach the current controls from the specified dom element.
  23526. * @param element Defines the element to stop listening the inputs from
  23527. */
  23528. Camera.prototype.detachControl = function (element) {
  23529. };
  23530. /**
  23531. * Update the camera state according to the different inputs gathered during the frame.
  23532. */
  23533. Camera.prototype.update = function () {
  23534. this._checkInputs();
  23535. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23536. this._updateRigCameras();
  23537. }
  23538. };
  23539. /** @hidden */
  23540. Camera.prototype._checkInputs = function () {
  23541. this.onAfterCheckInputsObservable.notifyObservers(this);
  23542. };
  23543. Object.defineProperty(Camera.prototype, "rigCameras", {
  23544. /** @hidden */
  23545. get: function () {
  23546. return this._rigCameras;
  23547. },
  23548. enumerable: true,
  23549. configurable: true
  23550. });
  23551. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  23552. /**
  23553. * Gets the post process used by the rig cameras
  23554. */
  23555. get: function () {
  23556. return this._rigPostProcess;
  23557. },
  23558. enumerable: true,
  23559. configurable: true
  23560. });
  23561. /**
  23562. * Internal, gets the first post proces.
  23563. * @returns the first post process to be run on this camera.
  23564. */
  23565. Camera.prototype._getFirstPostProcess = function () {
  23566. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  23567. if (this._postProcesses[ppIndex] !== null) {
  23568. return this._postProcesses[ppIndex];
  23569. }
  23570. }
  23571. return null;
  23572. };
  23573. Camera.prototype._cascadePostProcessesToRigCams = function () {
  23574. // invalidate framebuffer
  23575. var firstPostProcess = this._getFirstPostProcess();
  23576. if (firstPostProcess) {
  23577. firstPostProcess.markTextureDirty();
  23578. }
  23579. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  23580. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  23581. var cam = this._rigCameras[i];
  23582. var rigPostProcess = cam._rigPostProcess;
  23583. // for VR rig, there does not have to be a post process
  23584. if (rigPostProcess) {
  23585. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  23586. if (isPass) {
  23587. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  23588. cam.isIntermediate = this._postProcesses.length === 0;
  23589. }
  23590. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  23591. rigPostProcess.markTextureDirty();
  23592. }
  23593. else {
  23594. cam._postProcesses = this._postProcesses.slice(0);
  23595. }
  23596. }
  23597. };
  23598. /**
  23599. * Attach a post process to the camera.
  23600. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  23601. * @param postProcess The post process to attach to the camera
  23602. * @param insertAt The position of the post process in case several of them are in use in the scene
  23603. * @returns the position the post process has been inserted at
  23604. */
  23605. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  23606. if (insertAt === void 0) { insertAt = null; }
  23607. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  23608. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  23609. return 0;
  23610. }
  23611. if (insertAt == null || insertAt < 0) {
  23612. this._postProcesses.push(postProcess);
  23613. }
  23614. else if (this._postProcesses[insertAt] === null) {
  23615. this._postProcesses[insertAt] = postProcess;
  23616. }
  23617. else {
  23618. this._postProcesses.splice(insertAt, 0, postProcess);
  23619. }
  23620. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  23621. return this._postProcesses.indexOf(postProcess);
  23622. };
  23623. /**
  23624. * Detach a post process to the camera.
  23625. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  23626. * @param postProcess The post process to detach from the camera
  23627. */
  23628. Camera.prototype.detachPostProcess = function (postProcess) {
  23629. var idx = this._postProcesses.indexOf(postProcess);
  23630. if (idx !== -1) {
  23631. this._postProcesses[idx] = null;
  23632. }
  23633. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  23634. };
  23635. /**
  23636. * Gets the current world matrix of the camera
  23637. */
  23638. Camera.prototype.getWorldMatrix = function () {
  23639. if (this._isSynchronizedViewMatrix()) {
  23640. return this._worldMatrix;
  23641. }
  23642. // Getting the the view matrix will also compute the world matrix.
  23643. this.getViewMatrix();
  23644. return this._worldMatrix;
  23645. };
  23646. /** @hidden */
  23647. Camera.prototype._getViewMatrix = function () {
  23648. return BABYLON.Matrix.Identity();
  23649. };
  23650. /**
  23651. * Gets the current view matrix of the camera.
  23652. * @param force forces the camera to recompute the matrix without looking at the cached state
  23653. * @returns the view matrix
  23654. */
  23655. Camera.prototype.getViewMatrix = function (force) {
  23656. if (!force && this._isSynchronizedViewMatrix()) {
  23657. return this._computedViewMatrix;
  23658. }
  23659. this.updateCache();
  23660. this._computedViewMatrix = this._getViewMatrix();
  23661. this._currentRenderId = this.getScene().getRenderId();
  23662. this._childRenderId = this._currentRenderId;
  23663. this._refreshFrustumPlanes = true;
  23664. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  23665. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  23666. }
  23667. this.onViewMatrixChangedObservable.notifyObservers(this);
  23668. this._computedViewMatrix.invertToRef(this._worldMatrix);
  23669. return this._computedViewMatrix;
  23670. };
  23671. /**
  23672. * Freeze the projection matrix.
  23673. * It will prevent the cache check of the camera projection compute and can speed up perf
  23674. * if no parameter of the camera are meant to change
  23675. * @param projection Defines manually a projection if necessary
  23676. */
  23677. Camera.prototype.freezeProjectionMatrix = function (projection) {
  23678. this._doNotComputeProjectionMatrix = true;
  23679. if (projection !== undefined) {
  23680. this._projectionMatrix = projection;
  23681. }
  23682. };
  23683. /**
  23684. * Unfreeze the projection matrix if it has previously been freezed by freezeProjectionMatrix.
  23685. */
  23686. Camera.prototype.unfreezeProjectionMatrix = function () {
  23687. this._doNotComputeProjectionMatrix = false;
  23688. };
  23689. /**
  23690. * Gets the current projection matrix of the camera.
  23691. * @param force forces the camera to recompute the matrix without looking at the cached state
  23692. * @returns the projection matrix
  23693. */
  23694. Camera.prototype.getProjectionMatrix = function (force) {
  23695. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  23696. return this._projectionMatrix;
  23697. }
  23698. // Cache
  23699. this._cache.mode = this.mode;
  23700. this._cache.minZ = this.minZ;
  23701. this._cache.maxZ = this.maxZ;
  23702. // Matrix
  23703. this._refreshFrustumPlanes = true;
  23704. var engine = this.getEngine();
  23705. var scene = this.getScene();
  23706. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  23707. this._cache.fov = this.fov;
  23708. this._cache.fovMode = this.fovMode;
  23709. this._cache.aspectRatio = engine.getAspectRatio(this);
  23710. if (this.minZ <= 0) {
  23711. this.minZ = 0.1;
  23712. }
  23713. if (scene.useRightHandedSystem) {
  23714. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  23715. }
  23716. else {
  23717. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  23718. }
  23719. }
  23720. else {
  23721. var halfWidth = engine.getRenderWidth() / 2.0;
  23722. var halfHeight = engine.getRenderHeight() / 2.0;
  23723. if (scene.useRightHandedSystem) {
  23724. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  23725. }
  23726. else {
  23727. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  23728. }
  23729. this._cache.orthoLeft = this.orthoLeft;
  23730. this._cache.orthoRight = this.orthoRight;
  23731. this._cache.orthoBottom = this.orthoBottom;
  23732. this._cache.orthoTop = this.orthoTop;
  23733. this._cache.renderWidth = engine.getRenderWidth();
  23734. this._cache.renderHeight = engine.getRenderHeight();
  23735. }
  23736. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  23737. return this._projectionMatrix;
  23738. };
  23739. /**
  23740. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  23741. * @returns a Matrix
  23742. */
  23743. Camera.prototype.getTransformationMatrix = function () {
  23744. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23745. return this._transformMatrix;
  23746. };
  23747. Camera.prototype._updateFrustumPlanes = function () {
  23748. if (!this._refreshFrustumPlanes) {
  23749. return;
  23750. }
  23751. this.getTransformationMatrix();
  23752. if (!this._frustumPlanes) {
  23753. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23754. }
  23755. else {
  23756. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23757. }
  23758. this._refreshFrustumPlanes = false;
  23759. };
  23760. /**
  23761. * Checks if a cullable object (mesh...) is in the camera frustum
  23762. * This checks the bounding box center. See isCompletelyInFrustum for a full bounding check
  23763. * @param target The object to check
  23764. * @returns true if the object is in frustum otherwise false
  23765. */
  23766. Camera.prototype.isInFrustum = function (target) {
  23767. this._updateFrustumPlanes();
  23768. return target.isInFrustum(this._frustumPlanes);
  23769. };
  23770. /**
  23771. * Checks if a cullable object (mesh...) is in the camera frustum
  23772. * Unlike isInFrustum this cheks the full bounding box
  23773. * @param target The object to check
  23774. * @returns true if the object is in frustum otherwise false
  23775. */
  23776. Camera.prototype.isCompletelyInFrustum = function (target) {
  23777. this._updateFrustumPlanes();
  23778. return target.isCompletelyInFrustum(this._frustumPlanes);
  23779. };
  23780. /**
  23781. * Gets a ray in the forward direction from the camera.
  23782. * @param length Defines the length of the ray to create
  23783. * @param transform Defines the transform to apply to the ray, by default the world matrx is used to create a workd space ray
  23784. * @param origin Defines the start point of the ray which defaults to the camera position
  23785. * @returns the forward ray
  23786. */
  23787. Camera.prototype.getForwardRay = function (length, transform, origin) {
  23788. if (length === void 0) { length = 100; }
  23789. if (!transform) {
  23790. transform = this.getWorldMatrix();
  23791. }
  23792. if (!origin) {
  23793. origin = this.position;
  23794. }
  23795. var forward = this._scene.useRightHandedSystem ? new BABYLON.Vector3(0, 0, -1) : new BABYLON.Vector3(0, 0, 1);
  23796. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  23797. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  23798. return new BABYLON.Ray(origin, direction, length);
  23799. };
  23800. /**
  23801. * Releases resources associated with this node.
  23802. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  23803. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  23804. */
  23805. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  23806. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  23807. // Observables
  23808. this.onViewMatrixChangedObservable.clear();
  23809. this.onProjectionMatrixChangedObservable.clear();
  23810. this.onAfterCheckInputsObservable.clear();
  23811. this.onRestoreStateObservable.clear();
  23812. // Inputs
  23813. if (this.inputs) {
  23814. this.inputs.clear();
  23815. }
  23816. // Animations
  23817. this.getScene().stopAnimation(this);
  23818. // Remove from scene
  23819. this.getScene().removeCamera(this);
  23820. while (this._rigCameras.length > 0) {
  23821. var camera = this._rigCameras.pop();
  23822. if (camera) {
  23823. camera.dispose();
  23824. }
  23825. }
  23826. // Postprocesses
  23827. if (this._rigPostProcess) {
  23828. this._rigPostProcess.dispose(this);
  23829. this._rigPostProcess = null;
  23830. this._postProcesses = [];
  23831. }
  23832. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23833. this._rigPostProcess = null;
  23834. this._postProcesses = [];
  23835. }
  23836. else {
  23837. var i = this._postProcesses.length;
  23838. while (--i >= 0) {
  23839. var postProcess = this._postProcesses[i];
  23840. if (postProcess) {
  23841. postProcess.dispose(this);
  23842. }
  23843. }
  23844. }
  23845. // Render targets
  23846. var i = this.customRenderTargets.length;
  23847. while (--i >= 0) {
  23848. this.customRenderTargets[i].dispose();
  23849. }
  23850. this.customRenderTargets = [];
  23851. // Active Meshes
  23852. this._activeMeshes.dispose();
  23853. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  23854. };
  23855. Object.defineProperty(Camera.prototype, "leftCamera", {
  23856. /**
  23857. * Gets the left camera of a rig setup in case of Rigged Camera
  23858. */
  23859. get: function () {
  23860. if (this._rigCameras.length < 1) {
  23861. return null;
  23862. }
  23863. return this._rigCameras[0];
  23864. },
  23865. enumerable: true,
  23866. configurable: true
  23867. });
  23868. Object.defineProperty(Camera.prototype, "rightCamera", {
  23869. /**
  23870. * Gets the right camera of a rig setup in case of Rigged Camera
  23871. */
  23872. get: function () {
  23873. if (this._rigCameras.length < 2) {
  23874. return null;
  23875. }
  23876. return this._rigCameras[1];
  23877. },
  23878. enumerable: true,
  23879. configurable: true
  23880. });
  23881. /**
  23882. * Gets the left camera target of a rig setup in case of Rigged Camera
  23883. * @returns the target position
  23884. */
  23885. Camera.prototype.getLeftTarget = function () {
  23886. if (this._rigCameras.length < 1) {
  23887. return null;
  23888. }
  23889. return this._rigCameras[0].getTarget();
  23890. };
  23891. /**
  23892. * Gets the right camera target of a rig setup in case of Rigged Camera
  23893. * @returns the target position
  23894. */
  23895. Camera.prototype.getRightTarget = function () {
  23896. if (this._rigCameras.length < 2) {
  23897. return null;
  23898. }
  23899. return this._rigCameras[1].getTarget();
  23900. };
  23901. /**
  23902. * @hidden
  23903. */
  23904. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  23905. if (this.cameraRigMode === mode) {
  23906. return;
  23907. }
  23908. while (this._rigCameras.length > 0) {
  23909. var camera = this._rigCameras.pop();
  23910. if (camera) {
  23911. camera.dispose();
  23912. }
  23913. }
  23914. this.cameraRigMode = mode;
  23915. this._cameraRigParams = {};
  23916. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  23917. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  23918. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  23919. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  23920. // create the rig cameras, unless none
  23921. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23922. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  23923. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  23924. if (leftCamera && rightCamera) {
  23925. this._rigCameras.push(leftCamera);
  23926. this._rigCameras.push(rightCamera);
  23927. }
  23928. }
  23929. switch (this.cameraRigMode) {
  23930. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  23931. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  23932. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  23933. break;
  23934. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  23935. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  23936. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  23937. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  23938. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  23939. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  23940. break;
  23941. case Camera.RIG_MODE_VR:
  23942. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  23943. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  23944. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23945. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23946. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  23947. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  23948. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  23949. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  23950. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23951. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23952. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  23953. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  23954. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  23955. if (metrics.compensateDistortion) {
  23956. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  23957. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  23958. }
  23959. break;
  23960. case Camera.RIG_MODE_WEBVR:
  23961. if (rigParams.vrDisplay) {
  23962. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  23963. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  23964. //Left eye
  23965. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23966. this._rigCameras[0].setCameraRigParameter("left", true);
  23967. //leaving this for future reference
  23968. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  23969. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  23970. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  23971. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23972. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23973. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23974. this._rigCameras[0].parent = this;
  23975. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  23976. //Right eye
  23977. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23978. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  23979. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  23980. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  23981. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23982. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23983. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23984. this._rigCameras[1].parent = this;
  23985. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  23986. if (Camera.UseAlternateWebVRRendering) {
  23987. this._rigCameras[1]._skipRendering = true;
  23988. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  23989. }
  23990. }
  23991. break;
  23992. }
  23993. this._cascadePostProcessesToRigCams();
  23994. this.update();
  23995. };
  23996. Camera.prototype._getVRProjectionMatrix = function () {
  23997. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  23998. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  23999. return this._projectionMatrix;
  24000. };
  24001. Camera.prototype._updateCameraRotationMatrix = function () {
  24002. //Here for WebVR
  24003. };
  24004. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  24005. //Here for WebVR
  24006. };
  24007. /**
  24008. * This function MUST be overwritten by the different WebVR cameras available.
  24009. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  24010. */
  24011. Camera.prototype._getWebVRProjectionMatrix = function () {
  24012. return BABYLON.Matrix.Identity();
  24013. };
  24014. /**
  24015. * This function MUST be overwritten by the different WebVR cameras available.
  24016. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  24017. */
  24018. Camera.prototype._getWebVRViewMatrix = function () {
  24019. return BABYLON.Matrix.Identity();
  24020. };
  24021. /** @hidden */
  24022. Camera.prototype.setCameraRigParameter = function (name, value) {
  24023. if (!this._cameraRigParams) {
  24024. this._cameraRigParams = {};
  24025. }
  24026. this._cameraRigParams[name] = value;
  24027. //provisionnally:
  24028. if (name === "interaxialDistance") {
  24029. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  24030. }
  24031. };
  24032. /**
  24033. * needs to be overridden by children so sub has required properties to be copied
  24034. * @hidden
  24035. */
  24036. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  24037. return null;
  24038. };
  24039. /**
  24040. * May need to be overridden by children
  24041. * @hidden
  24042. */
  24043. Camera.prototype._updateRigCameras = function () {
  24044. for (var i = 0; i < this._rigCameras.length; i++) {
  24045. this._rigCameras[i].minZ = this.minZ;
  24046. this._rigCameras[i].maxZ = this.maxZ;
  24047. this._rigCameras[i].fov = this.fov;
  24048. }
  24049. // only update viewport when ANAGLYPH
  24050. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  24051. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  24052. }
  24053. };
  24054. /** @hidden */
  24055. Camera.prototype._setupInputs = function () {
  24056. };
  24057. /**
  24058. * Serialiaze the camera setup to a json represention
  24059. * @returns the JSON representation
  24060. */
  24061. Camera.prototype.serialize = function () {
  24062. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  24063. // Type
  24064. serializationObject.type = this.getClassName();
  24065. // Parent
  24066. if (this.parent) {
  24067. serializationObject.parentId = this.parent.id;
  24068. }
  24069. if (this.inputs) {
  24070. this.inputs.serialize(serializationObject);
  24071. }
  24072. // Animations
  24073. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24074. serializationObject.ranges = this.serializeAnimationRanges();
  24075. return serializationObject;
  24076. };
  24077. /**
  24078. * Clones the current camera.
  24079. * @param name The cloned camera name
  24080. * @returns the cloned camera
  24081. */
  24082. Camera.prototype.clone = function (name) {
  24083. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  24084. };
  24085. /**
  24086. * Gets the direction of the camera relative to a given local axis.
  24087. * @param localAxis Defines the reference axis to provide a relative direction.
  24088. * @return the direction
  24089. */
  24090. Camera.prototype.getDirection = function (localAxis) {
  24091. var result = BABYLON.Vector3.Zero();
  24092. this.getDirectionToRef(localAxis, result);
  24093. return result;
  24094. };
  24095. /**
  24096. * Gets the direction of the camera relative to a given local axis into a passed vector.
  24097. * @param localAxis Defines the reference axis to provide a relative direction.
  24098. * @param result Defines the vector to store the result in
  24099. */
  24100. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  24101. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  24102. };
  24103. /**
  24104. * Gets a camera constructor for a given camera type
  24105. * @param type The type of the camera to construct (should be equal to one of the camera class name)
  24106. * @param name The name of the camera the result will be able to instantiate
  24107. * @param scene The scene the result will construct the camera in
  24108. * @param interaxial_distance In case of stereoscopic setup, the distance between both eyes
  24109. * @param isStereoscopicSideBySide In case of stereoscopic setup, should the sereo be side b side
  24110. * @returns a factory method to construc the camera
  24111. */
  24112. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  24113. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  24114. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  24115. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  24116. interaxial_distance: interaxial_distance,
  24117. isStereoscopicSideBySide: isStereoscopicSideBySide
  24118. });
  24119. if (constructorFunc) {
  24120. return constructorFunc;
  24121. }
  24122. // Default to universal camera
  24123. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  24124. };
  24125. /**
  24126. * Compute the world matrix of the camera.
  24127. * @returns the camera workd matrix
  24128. */
  24129. Camera.prototype.computeWorldMatrix = function () {
  24130. return this.getWorldMatrix();
  24131. };
  24132. /**
  24133. * Parse a JSON and creates the camera from the parsed information
  24134. * @param parsedCamera The JSON to parse
  24135. * @param scene The scene to instantiate the camera in
  24136. * @returns the newly constructed camera
  24137. */
  24138. Camera.Parse = function (parsedCamera, scene) {
  24139. var type = parsedCamera.type;
  24140. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  24141. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  24142. // Parent
  24143. if (parsedCamera.parentId) {
  24144. camera._waitingParentId = parsedCamera.parentId;
  24145. }
  24146. //If camera has an input manager, let it parse inputs settings
  24147. if (camera.inputs) {
  24148. camera.inputs.parse(parsedCamera);
  24149. camera._setupInputs();
  24150. }
  24151. if (camera.setPosition) { // need to force position
  24152. camera.position.copyFromFloats(0, 0, 0);
  24153. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  24154. }
  24155. // Target
  24156. if (parsedCamera.target) {
  24157. if (camera.setTarget) {
  24158. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  24159. }
  24160. }
  24161. // Apply 3d rig, when found
  24162. if (parsedCamera.cameraRigMode) {
  24163. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  24164. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  24165. }
  24166. // Animations
  24167. if (parsedCamera.animations) {
  24168. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  24169. var parsedAnimation = parsedCamera.animations[animationIndex];
  24170. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24171. }
  24172. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  24173. }
  24174. if (parsedCamera.autoAnimate) {
  24175. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  24176. }
  24177. return camera;
  24178. };
  24179. /**
  24180. * This is the default projection mode used by the cameras.
  24181. * It helps recreating a feeling of perspective and better appreciate depth.
  24182. * This is the best way to simulate real life cameras.
  24183. */
  24184. Camera.PERSPECTIVE_CAMERA = 0;
  24185. /**
  24186. * This helps creating camera with an orthographic mode.
  24187. * 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.
  24188. */
  24189. Camera.ORTHOGRAPHIC_CAMERA = 1;
  24190. /**
  24191. * This is the default FOV mode for perspective cameras.
  24192. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  24193. */
  24194. Camera.FOVMODE_VERTICAL_FIXED = 0;
  24195. /**
  24196. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  24197. */
  24198. Camera.FOVMODE_HORIZONTAL_FIXED = 1;
  24199. /**
  24200. * This specifies ther is no need for a camera rig.
  24201. * Basically only one eye is rendered corresponding to the camera.
  24202. */
  24203. Camera.RIG_MODE_NONE = 0;
  24204. /**
  24205. * Simulates a camera Rig with one blue eye and one red eye.
  24206. * This can be use with 3d blue and red glasses.
  24207. */
  24208. Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  24209. /**
  24210. * Defines that both eyes of the camera will be rendered side by side with a parallel target.
  24211. */
  24212. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  24213. /**
  24214. * Defines that both eyes of the camera will be rendered side by side with a none parallel target.
  24215. */
  24216. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  24217. /**
  24218. * Defines that both eyes of the camera will be rendered over under each other.
  24219. */
  24220. Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  24221. /**
  24222. * Defines that both eyes of the camera should be renderered in a VR mode (carbox).
  24223. */
  24224. Camera.RIG_MODE_VR = 20;
  24225. /**
  24226. * Defines that both eyes of the camera should be renderered in a VR mode (webVR).
  24227. */
  24228. Camera.RIG_MODE_WEBVR = 21;
  24229. /**
  24230. * Defines if by default attaching controls should prevent the default javascript event to continue.
  24231. */
  24232. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  24233. /**
  24234. * @hidden
  24235. * Might be removed once multiview will be a thing
  24236. */
  24237. Camera.UseAlternateWebVRRendering = false;
  24238. __decorate([
  24239. BABYLON.serializeAsVector3()
  24240. ], Camera.prototype, "position", void 0);
  24241. __decorate([
  24242. BABYLON.serializeAsVector3()
  24243. ], Camera.prototype, "upVector", void 0);
  24244. __decorate([
  24245. BABYLON.serialize()
  24246. ], Camera.prototype, "orthoLeft", void 0);
  24247. __decorate([
  24248. BABYLON.serialize()
  24249. ], Camera.prototype, "orthoRight", void 0);
  24250. __decorate([
  24251. BABYLON.serialize()
  24252. ], Camera.prototype, "orthoBottom", void 0);
  24253. __decorate([
  24254. BABYLON.serialize()
  24255. ], Camera.prototype, "orthoTop", void 0);
  24256. __decorate([
  24257. BABYLON.serialize()
  24258. ], Camera.prototype, "fov", void 0);
  24259. __decorate([
  24260. BABYLON.serialize()
  24261. ], Camera.prototype, "minZ", void 0);
  24262. __decorate([
  24263. BABYLON.serialize()
  24264. ], Camera.prototype, "maxZ", void 0);
  24265. __decorate([
  24266. BABYLON.serialize()
  24267. ], Camera.prototype, "inertia", void 0);
  24268. __decorate([
  24269. BABYLON.serialize()
  24270. ], Camera.prototype, "mode", void 0);
  24271. __decorate([
  24272. BABYLON.serialize()
  24273. ], Camera.prototype, "layerMask", void 0);
  24274. __decorate([
  24275. BABYLON.serialize()
  24276. ], Camera.prototype, "fovMode", void 0);
  24277. __decorate([
  24278. BABYLON.serialize()
  24279. ], Camera.prototype, "cameraRigMode", void 0);
  24280. __decorate([
  24281. BABYLON.serialize()
  24282. ], Camera.prototype, "interaxialDistance", void 0);
  24283. __decorate([
  24284. BABYLON.serialize()
  24285. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  24286. return Camera;
  24287. }(BABYLON.Node));
  24288. BABYLON.Camera = Camera;
  24289. })(BABYLON || (BABYLON = {}));
  24290. //# sourceMappingURL=babylon.camera.js.map
  24291. var BABYLON;
  24292. (function (BABYLON) {
  24293. /**
  24294. * This is the manager responsible of all the rendering for meshes sprites and particles.
  24295. * It is enable to manage the different groups as well as the different necessary sort functions.
  24296. * This should not be used directly aside of the few static configurations
  24297. */
  24298. var RenderingManager = /** @class */ (function () {
  24299. /**
  24300. * Instantiates a new rendering group for a particular scene
  24301. * @param scene Defines the scene the groups belongs to
  24302. */
  24303. function RenderingManager(scene) {
  24304. /**
  24305. * @hidden
  24306. */
  24307. this._useSceneAutoClearSetup = false;
  24308. this._renderingGroups = new Array();
  24309. this._autoClearDepthStencil = {};
  24310. this._customOpaqueSortCompareFn = {};
  24311. this._customAlphaTestSortCompareFn = {};
  24312. this._customTransparentSortCompareFn = {};
  24313. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  24314. this._scene = scene;
  24315. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  24316. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  24317. }
  24318. }
  24319. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  24320. if (depth === void 0) { depth = true; }
  24321. if (stencil === void 0) { stencil = true; }
  24322. if (this._depthStencilBufferAlreadyCleaned) {
  24323. return;
  24324. }
  24325. this._scene.getEngine().clear(null, false, depth, stencil);
  24326. this._depthStencilBufferAlreadyCleaned = true;
  24327. };
  24328. /**
  24329. * Renders the entire managed groups. This is used by the scene or the different rennder targets.
  24330. * @hidden
  24331. */
  24332. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  24333. // Update the observable context (not null as it only goes away on dispose)
  24334. var info = this._renderingGroupInfo;
  24335. info.scene = this._scene;
  24336. info.camera = this._scene.activeCamera;
  24337. // Dispatch sprites
  24338. if (this._scene.spriteManagers && renderSprites) {
  24339. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  24340. var manager = this._scene.spriteManagers[index];
  24341. this.dispatchSprites(manager);
  24342. }
  24343. }
  24344. // Render
  24345. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24346. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  24347. var renderingGroup = this._renderingGroups[index];
  24348. if (!renderingGroup) {
  24349. continue;
  24350. }
  24351. var renderingGroupMask = Math.pow(2, index);
  24352. info.renderingGroupId = index;
  24353. // Before Observable
  24354. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  24355. // Clear depth/stencil if needed
  24356. if (RenderingManager.AUTOCLEAR) {
  24357. var autoClear = this._useSceneAutoClearSetup ?
  24358. this._scene.getAutoClearDepthStencilSetup(index) :
  24359. this._autoClearDepthStencil[index];
  24360. if (autoClear && autoClear.autoClear) {
  24361. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  24362. }
  24363. }
  24364. // Render
  24365. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  24366. var step = _a[_i];
  24367. step.action(index);
  24368. }
  24369. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  24370. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  24371. var step = _c[_b];
  24372. step.action(index);
  24373. }
  24374. // After Observable
  24375. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  24376. }
  24377. };
  24378. /**
  24379. * Resets the different information of the group to prepare a new frame
  24380. * @hidden
  24381. */
  24382. RenderingManager.prototype.reset = function () {
  24383. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24384. var renderingGroup = this._renderingGroups[index];
  24385. if (renderingGroup) {
  24386. renderingGroup.prepare();
  24387. }
  24388. }
  24389. };
  24390. /**
  24391. * Dispose and release the group and its associated resources.
  24392. * @hidden
  24393. */
  24394. RenderingManager.prototype.dispose = function () {
  24395. this.freeRenderingGroups();
  24396. this._renderingGroups.length = 0;
  24397. this._renderingGroupInfo = null;
  24398. };
  24399. /**
  24400. * Clear the info related to rendering groups preventing retention points during dispose.
  24401. */
  24402. RenderingManager.prototype.freeRenderingGroups = function () {
  24403. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24404. var renderingGroup = this._renderingGroups[index];
  24405. if (renderingGroup) {
  24406. renderingGroup.dispose();
  24407. }
  24408. }
  24409. };
  24410. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  24411. if (this._renderingGroups[renderingGroupId] === undefined) {
  24412. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  24413. }
  24414. };
  24415. /**
  24416. * Add a sprite manager to the rendering manager in order to render it this frame.
  24417. * @param spriteManager Define the sprite manager to render
  24418. */
  24419. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  24420. var renderingGroupId = spriteManager.renderingGroupId || 0;
  24421. this._prepareRenderingGroup(renderingGroupId);
  24422. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  24423. };
  24424. /**
  24425. * Add a particle system to the rendering manager in order to render it this frame.
  24426. * @param particleSystem Define the particle system to render
  24427. */
  24428. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  24429. var renderingGroupId = particleSystem.renderingGroupId || 0;
  24430. this._prepareRenderingGroup(renderingGroupId);
  24431. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  24432. };
  24433. /**
  24434. * Add a submesh to the manager in order to render it this frame
  24435. * @param subMesh The submesh to dispatch
  24436. * @param mesh Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  24437. * @param material Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  24438. */
  24439. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  24440. if (mesh === undefined) {
  24441. mesh = subMesh.getMesh();
  24442. }
  24443. var renderingGroupId = mesh.renderingGroupId || 0;
  24444. this._prepareRenderingGroup(renderingGroupId);
  24445. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  24446. };
  24447. /**
  24448. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  24449. * This allowed control for front to back rendering or reversly depending of the special needs.
  24450. *
  24451. * @param renderingGroupId The rendering group id corresponding to its index
  24452. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  24453. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  24454. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  24455. */
  24456. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24457. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24458. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24459. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24460. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  24461. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  24462. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  24463. if (this._renderingGroups[renderingGroupId]) {
  24464. var group = this._renderingGroups[renderingGroupId];
  24465. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  24466. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  24467. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  24468. }
  24469. };
  24470. /**
  24471. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  24472. *
  24473. * @param renderingGroupId The rendering group id corresponding to its index
  24474. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  24475. * @param depth Automatically clears depth between groups if true and autoClear is true.
  24476. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  24477. */
  24478. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  24479. if (depth === void 0) { depth = true; }
  24480. if (stencil === void 0) { stencil = true; }
  24481. this._autoClearDepthStencil[renderingGroupId] = {
  24482. autoClear: autoClearDepthStencil,
  24483. depth: depth,
  24484. stencil: stencil
  24485. };
  24486. };
  24487. /**
  24488. * Gets the current auto clear configuration for one rendering group of the rendering
  24489. * manager.
  24490. * @param index the rendering group index to get the information for
  24491. * @returns The auto clear setup for the requested rendering group
  24492. */
  24493. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  24494. return this._autoClearDepthStencil[index];
  24495. };
  24496. /**
  24497. * The max id used for rendering groups (not included)
  24498. */
  24499. RenderingManager.MAX_RENDERINGGROUPS = 4;
  24500. /**
  24501. * The min id used for rendering groups (included)
  24502. */
  24503. RenderingManager.MIN_RENDERINGGROUPS = 0;
  24504. /**
  24505. * Used to globally prevent autoclearing scenes.
  24506. */
  24507. RenderingManager.AUTOCLEAR = true;
  24508. return RenderingManager;
  24509. }());
  24510. BABYLON.RenderingManager = RenderingManager;
  24511. })(BABYLON || (BABYLON = {}));
  24512. //# sourceMappingURL=babylon.renderingManager.js.map
  24513. var BABYLON;
  24514. (function (BABYLON) {
  24515. /**
  24516. * This represents the object necessary to create a rendering group.
  24517. * This is exclusively used and created by the rendering manager.
  24518. * To modify the behavior, you use the available helpers in your scene or meshes.
  24519. * @hidden
  24520. */
  24521. var RenderingGroup = /** @class */ (function () {
  24522. /**
  24523. * Creates a new rendering group.
  24524. * @param index The rendering group index
  24525. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  24526. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  24527. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  24528. */
  24529. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24530. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24531. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24532. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24533. this.index = index;
  24534. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  24535. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  24536. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  24537. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  24538. this._particleSystems = new BABYLON.SmartArray(256);
  24539. this._spriteManagers = new BABYLON.SmartArray(256);
  24540. this._edgesRenderers = new BABYLON.SmartArray(16);
  24541. this._scene = scene;
  24542. this.opaqueSortCompareFn = opaqueSortCompareFn;
  24543. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  24544. this.transparentSortCompareFn = transparentSortCompareFn;
  24545. }
  24546. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  24547. /**
  24548. * Set the opaque sort comparison function.
  24549. * If null the sub meshes will be render in the order they were created
  24550. */
  24551. set: function (value) {
  24552. this._opaqueSortCompareFn = value;
  24553. if (value) {
  24554. this._renderOpaque = this.renderOpaqueSorted;
  24555. }
  24556. else {
  24557. this._renderOpaque = RenderingGroup.renderUnsorted;
  24558. }
  24559. },
  24560. enumerable: true,
  24561. configurable: true
  24562. });
  24563. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  24564. /**
  24565. * Set the alpha test sort comparison function.
  24566. * If null the sub meshes will be render in the order they were created
  24567. */
  24568. set: function (value) {
  24569. this._alphaTestSortCompareFn = value;
  24570. if (value) {
  24571. this._renderAlphaTest = this.renderAlphaTestSorted;
  24572. }
  24573. else {
  24574. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  24575. }
  24576. },
  24577. enumerable: true,
  24578. configurable: true
  24579. });
  24580. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  24581. /**
  24582. * Set the transparent sort comparison function.
  24583. * If null the sub meshes will be render in the order they were created
  24584. */
  24585. set: function (value) {
  24586. if (value) {
  24587. this._transparentSortCompareFn = value;
  24588. }
  24589. else {
  24590. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  24591. }
  24592. this._renderTransparent = this.renderTransparentSorted;
  24593. },
  24594. enumerable: true,
  24595. configurable: true
  24596. });
  24597. /**
  24598. * Render all the sub meshes contained in the group.
  24599. * @param customRenderFunction Used to override the default render behaviour of the group.
  24600. * @returns true if rendered some submeshes.
  24601. */
  24602. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  24603. if (customRenderFunction) {
  24604. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  24605. return;
  24606. }
  24607. var engine = this._scene.getEngine();
  24608. // Depth only
  24609. if (this._depthOnlySubMeshes.length !== 0) {
  24610. engine.setColorWrite(false);
  24611. this._renderAlphaTest(this._depthOnlySubMeshes);
  24612. engine.setColorWrite(true);
  24613. }
  24614. // Opaque
  24615. if (this._opaqueSubMeshes.length !== 0) {
  24616. this._renderOpaque(this._opaqueSubMeshes);
  24617. }
  24618. // Alpha test
  24619. if (this._alphaTestSubMeshes.length !== 0) {
  24620. this._renderAlphaTest(this._alphaTestSubMeshes);
  24621. }
  24622. var stencilState = engine.getStencilBuffer();
  24623. engine.setStencilBuffer(false);
  24624. // Sprites
  24625. if (renderSprites) {
  24626. this._renderSprites();
  24627. }
  24628. // Particles
  24629. if (renderParticles) {
  24630. this._renderParticles(activeMeshes);
  24631. }
  24632. if (this.onBeforeTransparentRendering) {
  24633. this.onBeforeTransparentRendering();
  24634. }
  24635. // Transparent
  24636. if (this._transparentSubMeshes.length !== 0) {
  24637. this._renderTransparent(this._transparentSubMeshes);
  24638. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24639. }
  24640. // Set back stencil to false in case it changes before the edge renderer.
  24641. engine.setStencilBuffer(false);
  24642. // Edges
  24643. if (this._edgesRenderers.length) {
  24644. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  24645. this._edgesRenderers.data[edgesRendererIndex].render();
  24646. }
  24647. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24648. }
  24649. // Restore Stencil state.
  24650. engine.setStencilBuffer(stencilState);
  24651. };
  24652. /**
  24653. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  24654. * @param subMeshes The submeshes to render
  24655. */
  24656. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  24657. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  24658. };
  24659. /**
  24660. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  24661. * @param subMeshes The submeshes to render
  24662. */
  24663. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  24664. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  24665. };
  24666. /**
  24667. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  24668. * @param subMeshes The submeshes to render
  24669. */
  24670. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  24671. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  24672. };
  24673. /**
  24674. * Renders the submeshes in a specified order.
  24675. * @param subMeshes The submeshes to sort before render
  24676. * @param sortCompareFn The comparison function use to sort
  24677. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  24678. * @param transparent Specifies to activate blending if true
  24679. */
  24680. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  24681. var subIndex = 0;
  24682. var subMesh;
  24683. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  24684. for (; subIndex < subMeshes.length; subIndex++) {
  24685. subMesh = subMeshes.data[subIndex];
  24686. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  24687. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  24688. }
  24689. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  24690. if (sortCompareFn) {
  24691. sortedArray.sort(sortCompareFn);
  24692. }
  24693. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  24694. subMesh = sortedArray[subIndex];
  24695. if (transparent) {
  24696. var material = subMesh.getMaterial();
  24697. if (material && material.needDepthPrePass) {
  24698. var engine = material.getScene().getEngine();
  24699. engine.setColorWrite(false);
  24700. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24701. subMesh.render(false);
  24702. engine.setColorWrite(true);
  24703. }
  24704. }
  24705. subMesh.render(transparent);
  24706. }
  24707. };
  24708. /**
  24709. * Renders the submeshes in the order they were dispatched (no sort applied).
  24710. * @param subMeshes The submeshes to render
  24711. */
  24712. RenderingGroup.renderUnsorted = function (subMeshes) {
  24713. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  24714. var submesh = subMeshes.data[subIndex];
  24715. submesh.render(false);
  24716. }
  24717. };
  24718. /**
  24719. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24720. * are rendered back to front if in the same alpha index.
  24721. *
  24722. * @param a The first submesh
  24723. * @param b The second submesh
  24724. * @returns The result of the comparison
  24725. */
  24726. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  24727. // Alpha index first
  24728. if (a._alphaIndex > b._alphaIndex) {
  24729. return 1;
  24730. }
  24731. if (a._alphaIndex < b._alphaIndex) {
  24732. return -1;
  24733. }
  24734. // Then distance to camera
  24735. return RenderingGroup.backToFrontSortCompare(a, b);
  24736. };
  24737. /**
  24738. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24739. * are rendered back to front.
  24740. *
  24741. * @param a The first submesh
  24742. * @param b The second submesh
  24743. * @returns The result of the comparison
  24744. */
  24745. RenderingGroup.backToFrontSortCompare = function (a, b) {
  24746. // Then distance to camera
  24747. if (a._distanceToCamera < b._distanceToCamera) {
  24748. return 1;
  24749. }
  24750. if (a._distanceToCamera > b._distanceToCamera) {
  24751. return -1;
  24752. }
  24753. return 0;
  24754. };
  24755. /**
  24756. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24757. * are rendered front to back (prevent overdraw).
  24758. *
  24759. * @param a The first submesh
  24760. * @param b The second submesh
  24761. * @returns The result of the comparison
  24762. */
  24763. RenderingGroup.frontToBackSortCompare = function (a, b) {
  24764. // Then distance to camera
  24765. if (a._distanceToCamera < b._distanceToCamera) {
  24766. return -1;
  24767. }
  24768. if (a._distanceToCamera > b._distanceToCamera) {
  24769. return 1;
  24770. }
  24771. return 0;
  24772. };
  24773. /**
  24774. * Resets the different lists of submeshes to prepare a new frame.
  24775. */
  24776. RenderingGroup.prototype.prepare = function () {
  24777. this._opaqueSubMeshes.reset();
  24778. this._transparentSubMeshes.reset();
  24779. this._alphaTestSubMeshes.reset();
  24780. this._depthOnlySubMeshes.reset();
  24781. this._particleSystems.reset();
  24782. this._spriteManagers.reset();
  24783. this._edgesRenderers.reset();
  24784. };
  24785. RenderingGroup.prototype.dispose = function () {
  24786. this._opaqueSubMeshes.dispose();
  24787. this._transparentSubMeshes.dispose();
  24788. this._alphaTestSubMeshes.dispose();
  24789. this._depthOnlySubMeshes.dispose();
  24790. this._particleSystems.dispose();
  24791. this._spriteManagers.dispose();
  24792. this._edgesRenderers.dispose();
  24793. };
  24794. /**
  24795. * Inserts the submesh in its correct queue depending on its material.
  24796. * @param subMesh The submesh to dispatch
  24797. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  24798. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  24799. */
  24800. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  24801. // Get mesh and materials if not provided
  24802. if (mesh === undefined) {
  24803. mesh = subMesh.getMesh();
  24804. }
  24805. if (material === undefined) {
  24806. material = subMesh.getMaterial();
  24807. }
  24808. if (material === null || material === undefined) {
  24809. return;
  24810. }
  24811. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  24812. this._transparentSubMeshes.push(subMesh);
  24813. }
  24814. else if (material.needAlphaTesting()) { // Alpha test
  24815. if (material.needDepthPrePass) {
  24816. this._depthOnlySubMeshes.push(subMesh);
  24817. }
  24818. this._alphaTestSubMeshes.push(subMesh);
  24819. }
  24820. else {
  24821. if (material.needDepthPrePass) {
  24822. this._depthOnlySubMeshes.push(subMesh);
  24823. }
  24824. this._opaqueSubMeshes.push(subMesh); // Opaque
  24825. }
  24826. if (mesh._edgesRenderer && mesh._edgesRenderer.isEnabled) {
  24827. this._edgesRenderers.push(mesh._edgesRenderer);
  24828. }
  24829. };
  24830. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  24831. this._spriteManagers.push(spriteManager);
  24832. };
  24833. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  24834. this._particleSystems.push(particleSystem);
  24835. };
  24836. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  24837. if (this._particleSystems.length === 0) {
  24838. return;
  24839. }
  24840. // Particles
  24841. var activeCamera = this._scene.activeCamera;
  24842. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  24843. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  24844. var particleSystem = this._particleSystems.data[particleIndex];
  24845. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  24846. continue;
  24847. }
  24848. var emitter = particleSystem.emitter;
  24849. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  24850. this._scene._activeParticles.addCount(particleSystem.render(), false);
  24851. }
  24852. }
  24853. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  24854. };
  24855. RenderingGroup.prototype._renderSprites = function () {
  24856. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  24857. return;
  24858. }
  24859. // Sprites
  24860. var activeCamera = this._scene.activeCamera;
  24861. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  24862. for (var id = 0; id < this._spriteManagers.length; id++) {
  24863. var spriteManager = this._spriteManagers.data[id];
  24864. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  24865. spriteManager.render();
  24866. }
  24867. }
  24868. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  24869. };
  24870. return RenderingGroup;
  24871. }());
  24872. BABYLON.RenderingGroup = RenderingGroup;
  24873. })(BABYLON || (BABYLON = {}));
  24874. //# sourceMappingURL=babylon.renderingGroup.js.map
  24875. var BABYLON;
  24876. (function (BABYLON) {
  24877. /**
  24878. * Groups all the scene component constants in one place to ease maintenance.
  24879. * @hidden
  24880. */
  24881. var SceneComponentConstants = /** @class */ (function () {
  24882. function SceneComponentConstants() {
  24883. }
  24884. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  24885. SceneComponentConstants.NAME_LAYER = "Layer";
  24886. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  24887. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  24888. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  24889. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  24890. SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue";
  24891. SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer";
  24892. SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer";
  24893. SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager";
  24894. SceneComponentConstants.NAME_SPRITE = "Sprite";
  24895. SceneComponentConstants.NAME_OUTLINERENDERER = "Outline";
  24896. SceneComponentConstants.NAME_PROCEDURALTEXTURE = "ProceduralTexture";
  24897. SceneComponentConstants.NAME_SHADOWGENERATOR = "ShadowGenerator";
  24898. SceneComponentConstants.NAME_OCTREE = "Octree";
  24899. SceneComponentConstants.NAME_PHYSICSENGINE = "PhysicsEngine";
  24900. SceneComponentConstants.NAME_AUDIO = "Audio";
  24901. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  24902. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  24903. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  24904. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  24905. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  24906. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  24907. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  24908. SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE = 0;
  24909. SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE = 0;
  24910. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  24911. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER = 1;
  24912. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;
  24913. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;
  24914. SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0;
  24915. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  24916. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  24917. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 2;
  24918. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 3;
  24919. SceneComponentConstants.STEP_AFTERRENDER_AUDIO = 0;
  24920. SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 0;
  24921. SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1;
  24922. SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 2;
  24923. SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3;
  24924. SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER = 0;
  24925. SceneComponentConstants.STEP_POINTERMOVE_SPRITE = 0;
  24926. SceneComponentConstants.STEP_POINTERDOWN_SPRITE = 0;
  24927. SceneComponentConstants.STEP_POINTERUP_SPRITE = 0;
  24928. return SceneComponentConstants;
  24929. }());
  24930. BABYLON.SceneComponentConstants = SceneComponentConstants;
  24931. /**
  24932. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  24933. * @hidden
  24934. */
  24935. var Stage = /** @class */ (function (_super) {
  24936. __extends(Stage, _super);
  24937. /**
  24938. * Hide ctor from the rest of the world.
  24939. * @param items The items to add.
  24940. */
  24941. function Stage(items) {
  24942. return _super.apply(this, items) || this;
  24943. }
  24944. /**
  24945. * Creates a new Stage.
  24946. * @returns A new instance of a Stage
  24947. */
  24948. Stage.Create = function () {
  24949. return Object.create(Stage.prototype);
  24950. };
  24951. /**
  24952. * Registers a step in an ordered way in the targeted stage.
  24953. * @param index Defines the position to register the step in
  24954. * @param component Defines the component attached to the step
  24955. * @param action Defines the action to launch during the step
  24956. */
  24957. Stage.prototype.registerStep = function (index, component, action) {
  24958. var i = 0;
  24959. var maxIndex = Number.MAX_VALUE;
  24960. for (; i < this.length; i++) {
  24961. var step = this[i];
  24962. maxIndex = step.index;
  24963. if (index < maxIndex) {
  24964. break;
  24965. }
  24966. }
  24967. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  24968. };
  24969. /**
  24970. * Clears all the steps from the stage.
  24971. */
  24972. Stage.prototype.clear = function () {
  24973. this.length = 0;
  24974. };
  24975. return Stage;
  24976. }(Array));
  24977. BABYLON.Stage = Stage;
  24978. })(BABYLON || (BABYLON = {}));
  24979. //# sourceMappingURL=babylon.sceneComponent.js.map
  24980. var BABYLON;
  24981. (function (BABYLON) {
  24982. /**
  24983. * Base class of the scene acting as a container for the different elements composing a scene.
  24984. * This class is dynamically extended by the different components of the scene increasing
  24985. * flexibility and reducing coupling
  24986. */
  24987. var AbstractScene = /** @class */ (function () {
  24988. function AbstractScene() {
  24989. /**
  24990. * Gets the list of root nodes (ie. nodes with no parent)
  24991. */
  24992. this.rootNodes = new Array();
  24993. /** All of the cameras added to this scene
  24994. * @see http://doc.babylonjs.com/babylon101/cameras
  24995. */
  24996. this.cameras = new Array();
  24997. /**
  24998. * All of the lights added to this scene
  24999. * @see http://doc.babylonjs.com/babylon101/lights
  25000. */
  25001. this.lights = new Array();
  25002. /**
  25003. * All of the (abstract) meshes added to this scene
  25004. */
  25005. this.meshes = new Array();
  25006. /**
  25007. * The list of skeletons added to the scene
  25008. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  25009. */
  25010. this.skeletons = new Array();
  25011. /**
  25012. * All of the particle systems added to this scene
  25013. * @see http://doc.babylonjs.com/babylon101/particles
  25014. */
  25015. this.particleSystems = new Array();
  25016. /**
  25017. * Gets a list of Animations associated with the scene
  25018. */
  25019. this.animations = [];
  25020. /**
  25021. * All of the animation groups added to this scene
  25022. * @see http://doc.babylonjs.com/how_to/group
  25023. */
  25024. this.animationGroups = new Array();
  25025. /**
  25026. * All of the multi-materials added to this scene
  25027. * @see http://doc.babylonjs.com/how_to/multi_materials
  25028. */
  25029. this.multiMaterials = new Array();
  25030. /**
  25031. * All of the materials added to this scene
  25032. * @see http://doc.babylonjs.com/babylon101/materials
  25033. */
  25034. this.materials = new Array();
  25035. /**
  25036. * The list of morph target managers added to the scene
  25037. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  25038. */
  25039. this.morphTargetManagers = new Array();
  25040. /**
  25041. * The list of geometries used in the scene.
  25042. */
  25043. this.geometries = new Array();
  25044. /**
  25045. * All of the tranform nodes added to this scene
  25046. * @see http://doc.babylonjs.com/how_to/transformnode
  25047. */
  25048. this.transformNodes = new Array();
  25049. /**
  25050. * ActionManagers available on the scene.
  25051. */
  25052. this.actionManagers = new Array();
  25053. /**
  25054. * Textures to keep.
  25055. */
  25056. this.textures = new Array();
  25057. }
  25058. /**
  25059. * Adds a parser in the list of available ones
  25060. * @param name Defines the name of the parser
  25061. * @param parser Defines the parser to add
  25062. */
  25063. AbstractScene.AddParser = function (name, parser) {
  25064. this._BabylonFileParsers[name] = parser;
  25065. };
  25066. /**
  25067. * Gets a general parser from the list of avaialble ones
  25068. * @param name Defines the name of the parser
  25069. * @returns the requested parser or null
  25070. */
  25071. AbstractScene.GetParser = function (name) {
  25072. if (this._BabylonFileParsers[name]) {
  25073. return this._BabylonFileParsers[name];
  25074. }
  25075. return null;
  25076. };
  25077. /**
  25078. * Adds n individual parser in the list of available ones
  25079. * @param name Defines the name of the parser
  25080. * @param parser Defines the parser to add
  25081. */
  25082. AbstractScene.AddIndividualParser = function (name, parser) {
  25083. this._IndividualBabylonFileParsers[name] = parser;
  25084. };
  25085. /**
  25086. * Gets an individual parser from the list of avaialble ones
  25087. * @param name Defines the name of the parser
  25088. * @returns the requested parser or null
  25089. */
  25090. AbstractScene.GetIndividualParser = function (name) {
  25091. if (this._IndividualBabylonFileParsers[name]) {
  25092. return this._IndividualBabylonFileParsers[name];
  25093. }
  25094. return null;
  25095. };
  25096. /**
  25097. * Parser json data and populate both a scene and its associated container object
  25098. * @param jsonData Defines the data to parse
  25099. * @param scene Defines the scene to parse the data for
  25100. * @param container Defines the container attached to the parsing sequence
  25101. * @param rootUrl Defines the root url of the data
  25102. */
  25103. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  25104. for (var parserName in this._BabylonFileParsers) {
  25105. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  25106. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  25107. }
  25108. }
  25109. };
  25110. /**
  25111. * Stores the list of available parsers in the application.
  25112. */
  25113. AbstractScene._BabylonFileParsers = {};
  25114. /**
  25115. * Stores the list of available individual parsers in the application.
  25116. */
  25117. AbstractScene._IndividualBabylonFileParsers = {};
  25118. return AbstractScene;
  25119. }());
  25120. BABYLON.AbstractScene = AbstractScene;
  25121. })(BABYLON || (BABYLON = {}));
  25122. //# sourceMappingURL=babylon.abstractScene.js.map
  25123. var BABYLON;
  25124. (function (BABYLON) {
  25125. /** @hidden */
  25126. var ClickInfo = /** @class */ (function () {
  25127. function ClickInfo() {
  25128. this._singleClick = false;
  25129. this._doubleClick = false;
  25130. this._hasSwiped = false;
  25131. this._ignore = false;
  25132. }
  25133. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  25134. get: function () {
  25135. return this._singleClick;
  25136. },
  25137. set: function (b) {
  25138. this._singleClick = b;
  25139. },
  25140. enumerable: true,
  25141. configurable: true
  25142. });
  25143. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  25144. get: function () {
  25145. return this._doubleClick;
  25146. },
  25147. set: function (b) {
  25148. this._doubleClick = b;
  25149. },
  25150. enumerable: true,
  25151. configurable: true
  25152. });
  25153. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  25154. get: function () {
  25155. return this._hasSwiped;
  25156. },
  25157. set: function (b) {
  25158. this._hasSwiped = b;
  25159. },
  25160. enumerable: true,
  25161. configurable: true
  25162. });
  25163. Object.defineProperty(ClickInfo.prototype, "ignore", {
  25164. get: function () {
  25165. return this._ignore;
  25166. },
  25167. set: function (b) {
  25168. this._ignore = b;
  25169. },
  25170. enumerable: true,
  25171. configurable: true
  25172. });
  25173. return ClickInfo;
  25174. }());
  25175. /**
  25176. * This class is used by the onRenderingGroupObservable
  25177. */
  25178. var RenderingGroupInfo = /** @class */ (function () {
  25179. function RenderingGroupInfo() {
  25180. }
  25181. return RenderingGroupInfo;
  25182. }());
  25183. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  25184. /**
  25185. * Represents a scene to be rendered by the engine.
  25186. * @see http://doc.babylonjs.com/features/scene
  25187. */
  25188. var Scene = /** @class */ (function (_super) {
  25189. __extends(Scene, _super);
  25190. /**
  25191. * Creates a new Scene
  25192. * @param engine defines the engine to use to render this scene
  25193. */
  25194. function Scene(engine) {
  25195. var _this = _super.call(this) || this;
  25196. // Members
  25197. /**
  25198. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  25199. */
  25200. _this.autoClear = true;
  25201. /**
  25202. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  25203. */
  25204. _this.autoClearDepthAndStencil = true;
  25205. /**
  25206. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  25207. */
  25208. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  25209. /**
  25210. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  25211. */
  25212. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  25213. _this._forceWireframe = false;
  25214. _this._forcePointsCloud = false;
  25215. /**
  25216. * Gets or sets a boolean indicating if animations are enabled
  25217. */
  25218. _this.animationsEnabled = true;
  25219. _this._animationPropertiesOverride = null;
  25220. /**
  25221. * Gets or sets a boolean indicating if a constant deltatime has to be used
  25222. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  25223. */
  25224. _this.useConstantAnimationDeltaTime = false;
  25225. /**
  25226. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  25227. * Please note that it requires to run a ray cast through the scene on every frame
  25228. */
  25229. _this.constantlyUpdateMeshUnderPointer = false;
  25230. /**
  25231. * Defines the HTML cursor to use when hovering over interactive elements
  25232. */
  25233. _this.hoverCursor = "pointer";
  25234. /**
  25235. * Defines the HTML default cursor to use (empty by default)
  25236. */
  25237. _this.defaultCursor = "";
  25238. /**
  25239. * This is used to call preventDefault() on pointer down
  25240. * in order to block unwanted artifacts like system double clicks
  25241. */
  25242. _this.preventDefaultOnPointerDown = true;
  25243. // Metadata
  25244. /**
  25245. * Gets or sets user defined metadata
  25246. */
  25247. _this.metadata = null;
  25248. /**
  25249. * Use this array to add regular expressions used to disable offline support for specific urls
  25250. */
  25251. _this.disableOfflineSupportExceptionRules = new Array();
  25252. /**
  25253. * An event triggered when the scene is disposed.
  25254. */
  25255. _this.onDisposeObservable = new BABYLON.Observable();
  25256. _this._onDisposeObserver = null;
  25257. /**
  25258. * An event triggered before rendering the scene (right after animations and physics)
  25259. */
  25260. _this.onBeforeRenderObservable = new BABYLON.Observable();
  25261. _this._onBeforeRenderObserver = null;
  25262. /**
  25263. * An event triggered after rendering the scene
  25264. */
  25265. _this.onAfterRenderObservable = new BABYLON.Observable();
  25266. _this._onAfterRenderObserver = null;
  25267. /**
  25268. * An event triggered before animating the scene
  25269. */
  25270. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  25271. /**
  25272. * An event triggered after animations processing
  25273. */
  25274. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  25275. /**
  25276. * An event triggered before draw calls are ready to be sent
  25277. */
  25278. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  25279. /**
  25280. * An event triggered after draw calls have been sent
  25281. */
  25282. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  25283. /**
  25284. * An event triggered when the scene is ready
  25285. */
  25286. _this.onReadyObservable = new BABYLON.Observable();
  25287. /**
  25288. * An event triggered before rendering a camera
  25289. */
  25290. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  25291. _this._onBeforeCameraRenderObserver = null;
  25292. /**
  25293. * An event triggered after rendering a camera
  25294. */
  25295. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  25296. _this._onAfterCameraRenderObserver = null;
  25297. /**
  25298. * An event triggered when active meshes evaluation is about to start
  25299. */
  25300. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  25301. /**
  25302. * An event triggered when active meshes evaluation is done
  25303. */
  25304. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  25305. /**
  25306. * An event triggered when particles rendering is about to start
  25307. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  25308. */
  25309. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  25310. /**
  25311. * An event triggered when particles rendering is done
  25312. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  25313. */
  25314. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  25315. /**
  25316. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  25317. */
  25318. _this.onDataLoadedObservable = new BABYLON.Observable();
  25319. /**
  25320. * An event triggered when a camera is created
  25321. */
  25322. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  25323. /**
  25324. * An event triggered when a camera is removed
  25325. */
  25326. _this.onCameraRemovedObservable = new BABYLON.Observable();
  25327. /**
  25328. * An event triggered when a light is created
  25329. */
  25330. _this.onNewLightAddedObservable = new BABYLON.Observable();
  25331. /**
  25332. * An event triggered when a light is removed
  25333. */
  25334. _this.onLightRemovedObservable = new BABYLON.Observable();
  25335. /**
  25336. * An event triggered when a geometry is created
  25337. */
  25338. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  25339. /**
  25340. * An event triggered when a geometry is removed
  25341. */
  25342. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  25343. /**
  25344. * An event triggered when a transform node is created
  25345. */
  25346. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  25347. /**
  25348. * An event triggered when a transform node is removed
  25349. */
  25350. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  25351. /**
  25352. * An event triggered when a mesh is created
  25353. */
  25354. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  25355. /**
  25356. * An event triggered when a mesh is removed
  25357. */
  25358. _this.onMeshRemovedObservable = new BABYLON.Observable();
  25359. /**
  25360. * An event triggered when a material is created
  25361. */
  25362. _this.onNewMaterialAddedObservable = new BABYLON.Observable();
  25363. /**
  25364. * An event triggered when a material is removed
  25365. */
  25366. _this.onMaterialRemovedObservable = new BABYLON.Observable();
  25367. /**
  25368. * An event triggered when a texture is created
  25369. */
  25370. _this.onNewTextureAddedObservable = new BABYLON.Observable();
  25371. /**
  25372. * An event triggered when a texture is removed
  25373. */
  25374. _this.onTextureRemovedObservable = new BABYLON.Observable();
  25375. /**
  25376. * An event triggered when render targets are about to be rendered
  25377. * Can happen multiple times per frame.
  25378. */
  25379. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  25380. /**
  25381. * An event triggered when render targets were rendered.
  25382. * Can happen multiple times per frame.
  25383. */
  25384. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  25385. /**
  25386. * An event triggered before calculating deterministic simulation step
  25387. */
  25388. _this.onBeforeStepObservable = new BABYLON.Observable();
  25389. /**
  25390. * An event triggered after calculating deterministic simulation step
  25391. */
  25392. _this.onAfterStepObservable = new BABYLON.Observable();
  25393. /**
  25394. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  25395. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  25396. * 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)
  25397. */
  25398. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  25399. /**
  25400. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  25401. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  25402. * 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)
  25403. */
  25404. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  25405. /**
  25406. * This Observable will when a mesh has been imported into the scene.
  25407. */
  25408. _this.onMeshImportedObservable = new BABYLON.Observable();
  25409. // Animations
  25410. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  25411. /**
  25412. * 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).
  25413. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  25414. */
  25415. _this.onPrePointerObservable = new BABYLON.Observable();
  25416. /**
  25417. * Observable event triggered each time an input event is received from the rendering canvas
  25418. */
  25419. _this.onPointerObservable = new BABYLON.Observable();
  25420. _this._meshPickProceed = false;
  25421. _this._currentPickResult = null;
  25422. _this._previousPickResult = null;
  25423. _this._totalPointersPressed = 0;
  25424. _this._doubleClickOccured = false;
  25425. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  25426. _this.cameraToUseForPointers = null;
  25427. _this._pointerX = 0;
  25428. _this._pointerY = 0;
  25429. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  25430. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  25431. _this._startingPointerTime = 0;
  25432. _this._previousStartingPointerTime = 0;
  25433. _this._pointerCaptures = {};
  25434. // Deterministic lockstep
  25435. _this._timeAccumulator = 0;
  25436. _this._currentStepId = 0;
  25437. _this._currentInternalStep = 0;
  25438. // Keyboard
  25439. /**
  25440. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  25441. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  25442. */
  25443. _this.onPreKeyboardObservable = new BABYLON.Observable();
  25444. /**
  25445. * Observable event triggered each time an keyboard event is received from the hosting window
  25446. */
  25447. _this.onKeyboardObservable = new BABYLON.Observable();
  25448. // Coordinates system
  25449. _this._useRightHandedSystem = false;
  25450. // Fog
  25451. _this._fogEnabled = true;
  25452. _this._fogMode = Scene.FOGMODE_NONE;
  25453. /**
  25454. * Gets or sets the fog color to use
  25455. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25456. * (Default is Color3(0.2, 0.2, 0.3))
  25457. */
  25458. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  25459. /**
  25460. * Gets or sets the fog density to use
  25461. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25462. * (Default is 0.1)
  25463. */
  25464. _this.fogDensity = 0.1;
  25465. /**
  25466. * Gets or sets the fog start distance to use
  25467. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25468. * (Default is 0)
  25469. */
  25470. _this.fogStart = 0;
  25471. /**
  25472. * Gets or sets the fog end distance to use
  25473. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25474. * (Default is 1000)
  25475. */
  25476. _this.fogEnd = 1000.0;
  25477. // Lights
  25478. _this._shadowsEnabled = true;
  25479. _this._lightsEnabled = true;
  25480. /** All of the active cameras added to this scene. */
  25481. _this.activeCameras = new Array();
  25482. // Textures
  25483. _this._texturesEnabled = true;
  25484. // Particles
  25485. /**
  25486. * Gets or sets a boolean indicating if particles are enabled on this scene
  25487. */
  25488. _this.particlesEnabled = true;
  25489. // Sprites
  25490. /**
  25491. * Gets or sets a boolean indicating if sprites are enabled on this scene
  25492. */
  25493. _this.spritesEnabled = true;
  25494. // Skeletons
  25495. _this._skeletonsEnabled = true;
  25496. // Lens flares
  25497. /**
  25498. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  25499. */
  25500. _this.lensFlaresEnabled = true;
  25501. // Collisions
  25502. /**
  25503. * Gets or sets a boolean indicating if collisions are enabled on this scene
  25504. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  25505. */
  25506. _this.collisionsEnabled = true;
  25507. /**
  25508. * Defines the gravity applied to this scene (used only for collisions)
  25509. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  25510. */
  25511. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  25512. // Postprocesses
  25513. /**
  25514. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  25515. */
  25516. _this.postProcessesEnabled = true;
  25517. /**
  25518. * The list of postprocesses added to the scene
  25519. */
  25520. _this.postProcesses = new Array();
  25521. // Customs render targets
  25522. /**
  25523. * Gets or sets a boolean indicating if render targets are enabled on this scene
  25524. */
  25525. _this.renderTargetsEnabled = true;
  25526. /**
  25527. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  25528. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  25529. */
  25530. _this.dumpNextRenderTargets = false;
  25531. /**
  25532. * The list of user defined render targets added to the scene
  25533. */
  25534. _this.customRenderTargets = new Array();
  25535. /**
  25536. * Gets the list of meshes imported to the scene through SceneLoader
  25537. */
  25538. _this.importedMeshesFiles = new Array();
  25539. // Probes
  25540. /**
  25541. * Gets or sets a boolean indicating if probes are enabled on this scene
  25542. */
  25543. _this.probesEnabled = true;
  25544. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  25545. // Procedural textures
  25546. /**
  25547. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  25548. */
  25549. _this.proceduralTexturesEnabled = true;
  25550. // Performance counters
  25551. _this._totalVertices = new BABYLON.PerfCounter();
  25552. /** @hidden */
  25553. _this._activeIndices = new BABYLON.PerfCounter();
  25554. /** @hidden */
  25555. _this._activeParticles = new BABYLON.PerfCounter();
  25556. /** @hidden */
  25557. _this._activeBones = new BABYLON.PerfCounter();
  25558. _this._animationTime = 0;
  25559. /**
  25560. * Gets or sets a general scale for animation speed
  25561. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  25562. */
  25563. _this.animationTimeScale = 1;
  25564. _this._renderId = 0;
  25565. _this._frameId = 0;
  25566. _this._executeWhenReadyTimeoutId = -1;
  25567. _this._intermediateRendering = false;
  25568. _this._viewUpdateFlag = -1;
  25569. _this._projectionUpdateFlag = -1;
  25570. _this._alternateViewUpdateFlag = -1;
  25571. _this._alternateProjectionUpdateFlag = -1;
  25572. /** @hidden */
  25573. _this._toBeDisposed = new Array(256);
  25574. _this._activeRequests = new Array();
  25575. _this._pendingData = new Array();
  25576. _this._isDisposed = false;
  25577. /**
  25578. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  25579. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  25580. */
  25581. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  25582. _this._activeMeshes = new BABYLON.SmartArray(256);
  25583. _this._processedMaterials = new BABYLON.SmartArray(256);
  25584. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  25585. /** @hidden */
  25586. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  25587. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  25588. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  25589. /** @hidden */
  25590. _this._activeAnimatables = new Array();
  25591. _this._transformMatrix = BABYLON.Matrix.Zero();
  25592. _this._useAlternateCameraConfiguration = false;
  25593. _this._alternateRendering = false;
  25594. /**
  25595. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  25596. * This is useful if there are more lights that the maximum simulteanous authorized
  25597. */
  25598. _this.requireLightSorting = false;
  25599. /**
  25600. * @hidden
  25601. * Backing store of defined scene components.
  25602. */
  25603. _this._components = [];
  25604. /**
  25605. * @hidden
  25606. * Backing store of defined scene components.
  25607. */
  25608. _this._serializableComponents = [];
  25609. /**
  25610. * List of components to register on the next registration step.
  25611. */
  25612. _this._transientComponents = [];
  25613. /**
  25614. * @hidden
  25615. * Defines the actions happening before camera updates.
  25616. */
  25617. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  25618. /**
  25619. * @hidden
  25620. * Defines the actions happening before clear the canvas.
  25621. */
  25622. _this._beforeClearStage = BABYLON.Stage.Create();
  25623. /**
  25624. * @hidden
  25625. * Defines the actions when collecting render targets for the frame.
  25626. */
  25627. _this._gatherRenderTargetsStage = BABYLON.Stage.Create();
  25628. /**
  25629. * @hidden
  25630. * Defines the actions happening for one camera in the frame.
  25631. */
  25632. _this._gatherActiveCameraRenderTargetsStage = BABYLON.Stage.Create();
  25633. /**
  25634. * @hidden
  25635. * Defines the actions happening during the per mesh ready checks.
  25636. */
  25637. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  25638. /**
  25639. * @hidden
  25640. * Defines the actions happening before evaluate active mesh checks.
  25641. */
  25642. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  25643. /**
  25644. * @hidden
  25645. * Defines the actions happening during the evaluate sub mesh checks.
  25646. */
  25647. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  25648. /**
  25649. * @hidden
  25650. * Defines the actions happening during the active mesh stage.
  25651. */
  25652. _this._activeMeshStage = BABYLON.Stage.Create();
  25653. /**
  25654. * @hidden
  25655. * Defines the actions happening during the per camera render target step.
  25656. */
  25657. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  25658. /**
  25659. * @hidden
  25660. * Defines the actions happening just before the active camera is drawing.
  25661. */
  25662. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  25663. /**
  25664. * @hidden
  25665. * Defines the actions happening just before a rendering group is drawing.
  25666. */
  25667. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  25668. /**
  25669. * @hidden
  25670. * Defines the actions happening just before a mesh is drawing.
  25671. */
  25672. _this._beforeRenderingMeshStage = BABYLON.Stage.Create();
  25673. /**
  25674. * @hidden
  25675. * Defines the actions happening just after a mesh has been drawn.
  25676. */
  25677. _this._afterRenderingMeshStage = BABYLON.Stage.Create();
  25678. /**
  25679. * @hidden
  25680. * Defines the actions happening just after a rendering group has been drawn.
  25681. */
  25682. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  25683. /**
  25684. * @hidden
  25685. * Defines the actions happening just after the active camera has been drawn.
  25686. */
  25687. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  25688. /**
  25689. * @hidden
  25690. * Defines the actions happening just after rendering all cameras and computing intersections.
  25691. */
  25692. _this._afterRenderStage = BABYLON.Stage.Create();
  25693. /**
  25694. * @hidden
  25695. * Defines the actions happening when a pointer move event happens.
  25696. */
  25697. _this._pointerMoveStage = BABYLON.Stage.Create();
  25698. /**
  25699. * @hidden
  25700. * Defines the actions happening when a pointer down event happens.
  25701. */
  25702. _this._pointerDownStage = BABYLON.Stage.Create();
  25703. /**
  25704. * @hidden
  25705. * Defines the actions happening when a pointer up event happens.
  25706. */
  25707. _this._pointerUpStage = BABYLON.Stage.Create();
  25708. _this._defaultMeshCandidates = {
  25709. data: [],
  25710. length: 0
  25711. };
  25712. _this._defaultSubMeshCandidates = {
  25713. data: [],
  25714. length: 0
  25715. };
  25716. _this._activeMeshesFrozen = false;
  25717. /** @hidden */
  25718. _this._allowPostProcessClearColor = true;
  25719. /**
  25720. * User updatable function that will return a deterministic frame time when engine is in deterministic lock step mode
  25721. */
  25722. _this.getDeterministicFrameTime = function () {
  25723. return 1000.0 / 60.0; // frame time in ms
  25724. };
  25725. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  25726. _this._blockMaterialDirtyMechanism = false;
  25727. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  25728. _this._engine.scenes.push(_this);
  25729. _this._uid = null;
  25730. _this._renderingManager = new BABYLON.RenderingManager(_this);
  25731. if (BABYLON.PostProcessManager) {
  25732. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  25733. }
  25734. if (BABYLON.Tools.IsWindowObjectExist()) {
  25735. _this.attachControl();
  25736. }
  25737. //collision coordinator initialization. For now legacy per default.
  25738. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  25739. // Uniform Buffer
  25740. _this._createUbo();
  25741. // Default Image processing definition
  25742. if (BABYLON.ImageProcessingConfiguration) {
  25743. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  25744. }
  25745. _this.setDefaultCandidateProviders();
  25746. return _this;
  25747. }
  25748. Object.defineProperty(Scene.prototype, "environmentTexture", {
  25749. /**
  25750. * Texture used in all pbr material as the reflection texture.
  25751. * As in the majority of the scene they are the same (exception for multi room and so on),
  25752. * this is easier to reference from here than from all the materials.
  25753. */
  25754. get: function () {
  25755. return this._environmentTexture;
  25756. },
  25757. /**
  25758. * Texture used in all pbr material as the reflection texture.
  25759. * As in the majority of the scene they are the same (exception for multi room and so on),
  25760. * this is easier to set here than in all the materials.
  25761. */
  25762. set: function (value) {
  25763. if (this._environmentTexture === value) {
  25764. return;
  25765. }
  25766. this._environmentTexture = value;
  25767. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25768. },
  25769. enumerable: true,
  25770. configurable: true
  25771. });
  25772. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  25773. /**
  25774. * Default image processing configuration used either in the rendering
  25775. * Forward main pass or through the imageProcessingPostProcess if present.
  25776. * As in the majority of the scene they are the same (exception for multi camera),
  25777. * this is easier to reference from here than from all the materials and post process.
  25778. *
  25779. * No setter as we it is a shared configuration, you can set the values instead.
  25780. */
  25781. get: function () {
  25782. return this._imageProcessingConfiguration;
  25783. },
  25784. enumerable: true,
  25785. configurable: true
  25786. });
  25787. Object.defineProperty(Scene.prototype, "forceWireframe", {
  25788. get: function () {
  25789. return this._forceWireframe;
  25790. },
  25791. /**
  25792. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  25793. */
  25794. set: function (value) {
  25795. if (this._forceWireframe === value) {
  25796. return;
  25797. }
  25798. this._forceWireframe = value;
  25799. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25800. },
  25801. enumerable: true,
  25802. configurable: true
  25803. });
  25804. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  25805. get: function () {
  25806. return this._forcePointsCloud;
  25807. },
  25808. /**
  25809. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  25810. */
  25811. set: function (value) {
  25812. if (this._forcePointsCloud === value) {
  25813. return;
  25814. }
  25815. this._forcePointsCloud = value;
  25816. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25817. },
  25818. enumerable: true,
  25819. configurable: true
  25820. });
  25821. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  25822. /**
  25823. * Gets or sets the animation properties override
  25824. */
  25825. get: function () {
  25826. return this._animationPropertiesOverride;
  25827. },
  25828. set: function (value) {
  25829. this._animationPropertiesOverride = value;
  25830. },
  25831. enumerable: true,
  25832. configurable: true
  25833. });
  25834. Object.defineProperty(Scene.prototype, "onDispose", {
  25835. /** Sets a function to be executed when this scene is disposed. */
  25836. set: function (callback) {
  25837. if (this._onDisposeObserver) {
  25838. this.onDisposeObservable.remove(this._onDisposeObserver);
  25839. }
  25840. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25841. },
  25842. enumerable: true,
  25843. configurable: true
  25844. });
  25845. Object.defineProperty(Scene.prototype, "beforeRender", {
  25846. /** Sets a function to be executed before rendering this scene */
  25847. set: function (callback) {
  25848. if (this._onBeforeRenderObserver) {
  25849. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  25850. }
  25851. if (callback) {
  25852. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  25853. }
  25854. },
  25855. enumerable: true,
  25856. configurable: true
  25857. });
  25858. Object.defineProperty(Scene.prototype, "afterRender", {
  25859. /** Sets a function to be executed after rendering this scene */
  25860. set: function (callback) {
  25861. if (this._onAfterRenderObserver) {
  25862. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  25863. }
  25864. if (callback) {
  25865. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  25866. }
  25867. },
  25868. enumerable: true,
  25869. configurable: true
  25870. });
  25871. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  25872. /** Sets a function to be executed before rendering a camera*/
  25873. set: function (callback) {
  25874. if (this._onBeforeCameraRenderObserver) {
  25875. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  25876. }
  25877. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  25878. },
  25879. enumerable: true,
  25880. configurable: true
  25881. });
  25882. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  25883. /** Sets a function to be executed after rendering a camera*/
  25884. set: function (callback) {
  25885. if (this._onAfterCameraRenderObserver) {
  25886. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  25887. }
  25888. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  25889. },
  25890. enumerable: true,
  25891. configurable: true
  25892. });
  25893. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  25894. /**
  25895. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  25896. */
  25897. get: function () {
  25898. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  25899. },
  25900. enumerable: true,
  25901. configurable: true
  25902. });
  25903. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  25904. get: function () {
  25905. return this._useRightHandedSystem;
  25906. },
  25907. /**
  25908. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  25909. */
  25910. set: function (value) {
  25911. if (this._useRightHandedSystem === value) {
  25912. return;
  25913. }
  25914. this._useRightHandedSystem = value;
  25915. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25916. },
  25917. enumerable: true,
  25918. configurable: true
  25919. });
  25920. /**
  25921. * Sets the step Id used by deterministic lock step
  25922. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25923. * @param newStepId defines the step Id
  25924. */
  25925. Scene.prototype.setStepId = function (newStepId) {
  25926. this._currentStepId = newStepId;
  25927. };
  25928. /**
  25929. * Gets the step Id used by deterministic lock step
  25930. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25931. * @returns the step Id
  25932. */
  25933. Scene.prototype.getStepId = function () {
  25934. return this._currentStepId;
  25935. };
  25936. /**
  25937. * Gets the internal step used by deterministic lock step
  25938. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25939. * @returns the internal step
  25940. */
  25941. Scene.prototype.getInternalStep = function () {
  25942. return this._currentInternalStep;
  25943. };
  25944. Object.defineProperty(Scene.prototype, "fogEnabled", {
  25945. get: function () {
  25946. return this._fogEnabled;
  25947. },
  25948. /**
  25949. * Gets or sets a boolean indicating if fog is enabled on this scene
  25950. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25951. * (Default is true)
  25952. */
  25953. set: function (value) {
  25954. if (this._fogEnabled === value) {
  25955. return;
  25956. }
  25957. this._fogEnabled = value;
  25958. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25959. },
  25960. enumerable: true,
  25961. configurable: true
  25962. });
  25963. Object.defineProperty(Scene.prototype, "fogMode", {
  25964. get: function () {
  25965. return this._fogMode;
  25966. },
  25967. /**
  25968. * Gets or sets the fog mode to use
  25969. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25970. * | mode | value |
  25971. * | --- | --- |
  25972. * | FOGMODE_NONE | 0 |
  25973. * | FOGMODE_EXP | 1 |
  25974. * | FOGMODE_EXP2 | 2 |
  25975. * | FOGMODE_LINEAR | 3 |
  25976. */
  25977. set: function (value) {
  25978. if (this._fogMode === value) {
  25979. return;
  25980. }
  25981. this._fogMode = value;
  25982. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25983. },
  25984. enumerable: true,
  25985. configurable: true
  25986. });
  25987. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  25988. get: function () {
  25989. return this._shadowsEnabled;
  25990. },
  25991. /**
  25992. * Gets or sets a boolean indicating if shadows are enabled on this scene
  25993. */
  25994. set: function (value) {
  25995. if (this._shadowsEnabled === value) {
  25996. return;
  25997. }
  25998. this._shadowsEnabled = value;
  25999. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  26000. },
  26001. enumerable: true,
  26002. configurable: true
  26003. });
  26004. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  26005. get: function () {
  26006. return this._lightsEnabled;
  26007. },
  26008. /**
  26009. * Gets or sets a boolean indicating if lights are enabled on this scene
  26010. */
  26011. set: function (value) {
  26012. if (this._lightsEnabled === value) {
  26013. return;
  26014. }
  26015. this._lightsEnabled = value;
  26016. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  26017. },
  26018. enumerable: true,
  26019. configurable: true
  26020. });
  26021. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  26022. /** The default material used on meshes when no material is affected */
  26023. get: function () {
  26024. if (!this._defaultMaterial) {
  26025. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  26026. }
  26027. return this._defaultMaterial;
  26028. },
  26029. /** The default material used on meshes when no material is affected */
  26030. set: function (value) {
  26031. this._defaultMaterial = value;
  26032. },
  26033. enumerable: true,
  26034. configurable: true
  26035. });
  26036. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  26037. get: function () {
  26038. return this._texturesEnabled;
  26039. },
  26040. /**
  26041. * Gets or sets a boolean indicating if textures are enabled on this scene
  26042. */
  26043. set: function (value) {
  26044. if (this._texturesEnabled === value) {
  26045. return;
  26046. }
  26047. this._texturesEnabled = value;
  26048. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26049. },
  26050. enumerable: true,
  26051. configurable: true
  26052. });
  26053. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  26054. get: function () {
  26055. return this._skeletonsEnabled;
  26056. },
  26057. /**
  26058. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  26059. */
  26060. set: function (value) {
  26061. if (this._skeletonsEnabled === value) {
  26062. return;
  26063. }
  26064. this._skeletonsEnabled = value;
  26065. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  26066. },
  26067. enumerable: true,
  26068. configurable: true
  26069. });
  26070. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  26071. /** @hidden */
  26072. get: function () {
  26073. return this._alternateRendering;
  26074. },
  26075. enumerable: true,
  26076. configurable: true
  26077. });
  26078. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  26079. /**
  26080. * Gets the list of frustum planes (built from the active camera)
  26081. */
  26082. get: function () {
  26083. return this._frustumPlanes;
  26084. },
  26085. enumerable: true,
  26086. configurable: true
  26087. });
  26088. /**
  26089. * Registers the transient components if needed.
  26090. */
  26091. Scene.prototype._registerTransientComponents = function () {
  26092. // Register components that have been associated lately to the scene.
  26093. if (this._transientComponents.length > 0) {
  26094. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  26095. var component = _a[_i];
  26096. component.register();
  26097. }
  26098. this._transientComponents = [];
  26099. }
  26100. };
  26101. /**
  26102. * @hidden
  26103. * Add a component to the scene.
  26104. * Note that the ccomponent could be registered on th next frame if this is called after
  26105. * the register component stage.
  26106. * @param component Defines the component to add to the scene
  26107. */
  26108. Scene.prototype._addComponent = function (component) {
  26109. this._components.push(component);
  26110. this._transientComponents.push(component);
  26111. var serializableComponent = component;
  26112. if (serializableComponent.addFromContainer) {
  26113. this._serializableComponents.push(serializableComponent);
  26114. }
  26115. };
  26116. /**
  26117. * @hidden
  26118. * Gets a component from the scene.
  26119. * @param name defines the name of the component to retrieve
  26120. * @returns the component or null if not present
  26121. */
  26122. Scene.prototype._getComponent = function (name) {
  26123. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  26124. var component = _a[_i];
  26125. if (component.name === name) {
  26126. return component;
  26127. }
  26128. }
  26129. return null;
  26130. };
  26131. /**
  26132. * @hidden
  26133. */
  26134. Scene.prototype._getDefaultMeshCandidates = function () {
  26135. this._defaultMeshCandidates.data = this.meshes;
  26136. this._defaultMeshCandidates.length = this.meshes.length;
  26137. return this._defaultMeshCandidates;
  26138. };
  26139. /**
  26140. * @hidden
  26141. */
  26142. Scene.prototype._getDefaultSubMeshCandidates = function (mesh) {
  26143. this._defaultSubMeshCandidates.data = mesh.subMeshes;
  26144. this._defaultSubMeshCandidates.length = mesh.subMeshes.length;
  26145. return this._defaultSubMeshCandidates;
  26146. };
  26147. /**
  26148. * Sets the default candidate providers for the scene.
  26149. * This sets the getActiveMeshCandidates, getActiveSubMeshCandidates, getIntersectingSubMeshCandidates
  26150. * and getCollidingSubMeshCandidates to their default function
  26151. */
  26152. Scene.prototype.setDefaultCandidateProviders = function () {
  26153. this.getActiveMeshCandidates = this._getDefaultMeshCandidates.bind(this);
  26154. this.getActiveSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  26155. this.getIntersectingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  26156. this.getCollidingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  26157. };
  26158. Object.defineProperty(Scene.prototype, "workerCollisions", {
  26159. /**
  26160. * Gets a boolean indicating if collisions are processed on a web worker
  26161. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  26162. */
  26163. get: function () {
  26164. return this._workerCollisions;
  26165. },
  26166. set: function (enabled) {
  26167. if (!BABYLON.CollisionCoordinatorLegacy) {
  26168. return;
  26169. }
  26170. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  26171. this._workerCollisions = enabled;
  26172. if (this.collisionCoordinator) {
  26173. this.collisionCoordinator.destroy();
  26174. }
  26175. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  26176. this.collisionCoordinator.init(this);
  26177. },
  26178. enumerable: true,
  26179. configurable: true
  26180. });
  26181. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  26182. /**
  26183. * Gets the mesh that is currently under the pointer
  26184. */
  26185. get: function () {
  26186. return this._pointerOverMesh;
  26187. },
  26188. enumerable: true,
  26189. configurable: true
  26190. });
  26191. Object.defineProperty(Scene.prototype, "pointerX", {
  26192. /**
  26193. * Gets the current on-screen X position of the pointer
  26194. */
  26195. get: function () {
  26196. return this._pointerX;
  26197. },
  26198. enumerable: true,
  26199. configurable: true
  26200. });
  26201. Object.defineProperty(Scene.prototype, "pointerY", {
  26202. /**
  26203. * Gets the current on-screen Y position of the pointer
  26204. */
  26205. get: function () {
  26206. return this._pointerY;
  26207. },
  26208. enumerable: true,
  26209. configurable: true
  26210. });
  26211. /**
  26212. * Gets the cached material (ie. the latest rendered one)
  26213. * @returns the cached material
  26214. */
  26215. Scene.prototype.getCachedMaterial = function () {
  26216. return this._cachedMaterial;
  26217. };
  26218. /**
  26219. * Gets the cached effect (ie. the latest rendered one)
  26220. * @returns the cached effect
  26221. */
  26222. Scene.prototype.getCachedEffect = function () {
  26223. return this._cachedEffect;
  26224. };
  26225. /**
  26226. * Gets the cached visibility state (ie. the latest rendered one)
  26227. * @returns the cached visibility state
  26228. */
  26229. Scene.prototype.getCachedVisibility = function () {
  26230. return this._cachedVisibility;
  26231. };
  26232. /**
  26233. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  26234. * @param material defines the current material
  26235. * @param effect defines the current effect
  26236. * @param visibility defines the current visibility state
  26237. * @returns true if one parameter is not cached
  26238. */
  26239. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  26240. if (visibility === void 0) { visibility = 1; }
  26241. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  26242. };
  26243. /**
  26244. * Gets the engine associated with the scene
  26245. * @returns an Engine
  26246. */
  26247. Scene.prototype.getEngine = function () {
  26248. return this._engine;
  26249. };
  26250. /**
  26251. * Gets the total number of vertices rendered per frame
  26252. * @returns the total number of vertices rendered per frame
  26253. */
  26254. Scene.prototype.getTotalVertices = function () {
  26255. return this._totalVertices.current;
  26256. };
  26257. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  26258. /**
  26259. * Gets the performance counter for total vertices
  26260. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26261. */
  26262. get: function () {
  26263. return this._totalVertices;
  26264. },
  26265. enumerable: true,
  26266. configurable: true
  26267. });
  26268. /**
  26269. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  26270. * @returns the total number of active indices rendered per frame
  26271. */
  26272. Scene.prototype.getActiveIndices = function () {
  26273. return this._activeIndices.current;
  26274. };
  26275. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  26276. /**
  26277. * Gets the performance counter for active indices
  26278. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26279. */
  26280. get: function () {
  26281. return this._activeIndices;
  26282. },
  26283. enumerable: true,
  26284. configurable: true
  26285. });
  26286. /**
  26287. * Gets the total number of active particles rendered per frame
  26288. * @returns the total number of active particles rendered per frame
  26289. */
  26290. Scene.prototype.getActiveParticles = function () {
  26291. return this._activeParticles.current;
  26292. };
  26293. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  26294. /**
  26295. * Gets the performance counter for active particles
  26296. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26297. */
  26298. get: function () {
  26299. return this._activeParticles;
  26300. },
  26301. enumerable: true,
  26302. configurable: true
  26303. });
  26304. /**
  26305. * Gets the total number of active bones rendered per frame
  26306. * @returns the total number of active bones rendered per frame
  26307. */
  26308. Scene.prototype.getActiveBones = function () {
  26309. return this._activeBones.current;
  26310. };
  26311. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  26312. /**
  26313. * Gets the performance counter for active bones
  26314. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26315. */
  26316. get: function () {
  26317. return this._activeBones;
  26318. },
  26319. enumerable: true,
  26320. configurable: true
  26321. });
  26322. /** @hidden */
  26323. Scene.prototype.getInterFramePerfCounter = function () {
  26324. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  26325. return 0;
  26326. };
  26327. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  26328. /** @hidden */
  26329. get: function () {
  26330. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  26331. return null;
  26332. },
  26333. enumerable: true,
  26334. configurable: true
  26335. });
  26336. /** @hidden */
  26337. Scene.prototype.getLastFrameDuration = function () {
  26338. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  26339. return 0;
  26340. };
  26341. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  26342. /** @hidden */
  26343. get: function () {
  26344. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  26345. return null;
  26346. },
  26347. enumerable: true,
  26348. configurable: true
  26349. });
  26350. /** @hidden */
  26351. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  26352. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  26353. return 0;
  26354. };
  26355. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  26356. /** @hidden */
  26357. get: function () {
  26358. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  26359. return null;
  26360. },
  26361. enumerable: true,
  26362. configurable: true
  26363. });
  26364. /**
  26365. * Gets the array of active meshes
  26366. * @returns an array of AbstractMesh
  26367. */
  26368. Scene.prototype.getActiveMeshes = function () {
  26369. return this._activeMeshes;
  26370. };
  26371. /** @hidden */
  26372. Scene.prototype.getRenderTargetsDuration = function () {
  26373. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  26374. return 0;
  26375. };
  26376. /** @hidden */
  26377. Scene.prototype.getRenderDuration = function () {
  26378. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  26379. return 0;
  26380. };
  26381. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  26382. /** @hidden */
  26383. get: function () {
  26384. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  26385. return null;
  26386. },
  26387. enumerable: true,
  26388. configurable: true
  26389. });
  26390. /** @hidden */
  26391. Scene.prototype.getParticlesDuration = function () {
  26392. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  26393. return 0;
  26394. };
  26395. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  26396. /** @hidden */
  26397. get: function () {
  26398. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  26399. return null;
  26400. },
  26401. enumerable: true,
  26402. configurable: true
  26403. });
  26404. /** @hidden */
  26405. Scene.prototype.getSpritesDuration = function () {
  26406. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  26407. return 0;
  26408. };
  26409. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  26410. /** @hidden */
  26411. get: function () {
  26412. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  26413. return null;
  26414. },
  26415. enumerable: true,
  26416. configurable: true
  26417. });
  26418. /**
  26419. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  26420. * @returns a number
  26421. */
  26422. Scene.prototype.getAnimationRatio = function () {
  26423. return this._animationRatio !== undefined ? this._animationRatio : 1;
  26424. };
  26425. /**
  26426. * Gets an unique Id for the current render phase
  26427. * @returns a number
  26428. */
  26429. Scene.prototype.getRenderId = function () {
  26430. return this._renderId;
  26431. };
  26432. /**
  26433. * Gets an unique Id for the current frame
  26434. * @returns a number
  26435. */
  26436. Scene.prototype.getFrameId = function () {
  26437. return this._frameId;
  26438. };
  26439. /** Call this function if you want to manually increment the render Id*/
  26440. Scene.prototype.incrementRenderId = function () {
  26441. this._renderId++;
  26442. };
  26443. Scene.prototype._updatePointerPosition = function (evt) {
  26444. var canvasRect = this._engine.getRenderingCanvasClientRect();
  26445. if (!canvasRect) {
  26446. return;
  26447. }
  26448. this._pointerX = evt.clientX - canvasRect.left;
  26449. this._pointerY = evt.clientY - canvasRect.top;
  26450. this._unTranslatedPointerX = this._pointerX;
  26451. this._unTranslatedPointerY = this._pointerY;
  26452. };
  26453. Scene.prototype._createUbo = function () {
  26454. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  26455. this._sceneUbo.addUniform("viewProjection", 16);
  26456. this._sceneUbo.addUniform("view", 16);
  26457. };
  26458. Scene.prototype._createAlternateUbo = function () {
  26459. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  26460. this._alternateSceneUbo.addUniform("viewProjection", 16);
  26461. this._alternateSceneUbo.addUniform("view", 16);
  26462. };
  26463. // Pointers handling
  26464. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  26465. if (pointerInfo.pickInfo) {
  26466. if (!pointerInfo.pickInfo.ray) {
  26467. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  26468. }
  26469. }
  26470. };
  26471. /**
  26472. * Use this method to simulate a pointer move on a mesh
  26473. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26474. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26475. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26476. * @returns the current scene
  26477. */
  26478. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  26479. var evt = new PointerEvent("pointermove", pointerEventInit);
  26480. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  26481. return this;
  26482. }
  26483. return this._processPointerMove(pickResult, evt);
  26484. };
  26485. Scene.prototype._processPointerMove = function (pickResult, evt) {
  26486. var canvas = this._engine.getRenderingCanvas();
  26487. if (!canvas) {
  26488. return this;
  26489. }
  26490. // Restore pointer
  26491. canvas.style.cursor = this.defaultCursor;
  26492. var isMeshPicked = (pickResult && pickResult.hit && pickResult.pickedMesh) ? true : false;
  26493. if (isMeshPicked) {
  26494. this.setPointerOverMesh(pickResult.pickedMesh);
  26495. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  26496. if (this._pointerOverMesh.actionManager.hoverCursor) {
  26497. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  26498. }
  26499. else {
  26500. canvas.style.cursor = this.hoverCursor;
  26501. }
  26502. }
  26503. }
  26504. else {
  26505. this.setPointerOverMesh(null);
  26506. }
  26507. for (var _i = 0, _a = this._pointerMoveStage; _i < _a.length; _i++) {
  26508. var step = _a[_i];
  26509. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas);
  26510. }
  26511. if (pickResult) {
  26512. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  26513. if (this.onPointerMove) {
  26514. this.onPointerMove(evt, pickResult, type);
  26515. }
  26516. if (this.onPointerObservable.hasObservers()) {
  26517. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26518. this._setRayOnPointerInfo(pi);
  26519. this.onPointerObservable.notifyObservers(pi, type);
  26520. }
  26521. }
  26522. return this;
  26523. };
  26524. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  26525. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  26526. if (pickResult) {
  26527. pi.ray = pickResult.ray;
  26528. }
  26529. this.onPrePointerObservable.notifyObservers(pi, type);
  26530. if (pi.skipOnPointerObservable) {
  26531. return true;
  26532. }
  26533. else {
  26534. return false;
  26535. }
  26536. };
  26537. /**
  26538. * Use this method to simulate a pointer down on a mesh
  26539. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26540. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26541. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26542. * @returns the current scene
  26543. */
  26544. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  26545. var evt = new PointerEvent("pointerdown", pointerEventInit);
  26546. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  26547. return this;
  26548. }
  26549. return this._processPointerDown(pickResult, evt);
  26550. };
  26551. Scene.prototype._processPointerDown = function (pickResult, evt) {
  26552. var _this = this;
  26553. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  26554. this._pickedDownMesh = pickResult.pickedMesh;
  26555. var actionManager = pickResult.pickedMesh.actionManager;
  26556. if (actionManager) {
  26557. if (actionManager.hasPickTriggers) {
  26558. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26559. switch (evt.button) {
  26560. case 0:
  26561. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26562. break;
  26563. case 1:
  26564. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26565. break;
  26566. case 2:
  26567. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26568. break;
  26569. }
  26570. }
  26571. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  26572. window.setTimeout(function () {
  26573. 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);
  26574. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  26575. if (_this._totalPointersPressed !== 0 &&
  26576. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  26577. !_this._isPointerSwiping()) {
  26578. _this._startingPointerTime = 0;
  26579. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26580. }
  26581. }
  26582. }, Scene.LongPressDelay);
  26583. }
  26584. }
  26585. }
  26586. else {
  26587. for (var _i = 0, _a = this._pointerDownStage; _i < _a.length; _i++) {
  26588. var step = _a[_i];
  26589. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  26590. }
  26591. }
  26592. if (pickResult) {
  26593. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  26594. if (this.onPointerDown) {
  26595. this.onPointerDown(evt, pickResult, type);
  26596. }
  26597. if (this.onPointerObservable.hasObservers()) {
  26598. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26599. this._setRayOnPointerInfo(pi);
  26600. this.onPointerObservable.notifyObservers(pi, type);
  26601. }
  26602. }
  26603. return this;
  26604. };
  26605. /**
  26606. * Use this method to simulate a pointer up on a mesh
  26607. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26608. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26609. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26610. * @returns the current scene
  26611. */
  26612. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  26613. var evt = new PointerEvent("pointerup", pointerEventInit);
  26614. var clickInfo = new ClickInfo();
  26615. clickInfo.singleClick = true;
  26616. clickInfo.ignore = true;
  26617. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  26618. return this;
  26619. }
  26620. return this._processPointerUp(pickResult, evt, clickInfo);
  26621. };
  26622. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  26623. if (pickResult && pickResult && pickResult.pickedMesh) {
  26624. this._pickedUpMesh = pickResult.pickedMesh;
  26625. if (this._pickedDownMesh === this._pickedUpMesh) {
  26626. if (this.onPointerPick) {
  26627. this.onPointerPick(evt, pickResult);
  26628. }
  26629. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  26630. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  26631. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  26632. this._setRayOnPointerInfo(pi);
  26633. this.onPointerObservable.notifyObservers(pi, type_1);
  26634. }
  26635. }
  26636. if (pickResult.pickedMesh.actionManager) {
  26637. if (clickInfo.ignore) {
  26638. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26639. }
  26640. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  26641. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26642. }
  26643. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26644. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26645. }
  26646. }
  26647. }
  26648. else {
  26649. if (!clickInfo.ignore) {
  26650. for (var _i = 0, _a = this._pointerUpStage; _i < _a.length; _i++) {
  26651. var step = _a[_i];
  26652. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  26653. }
  26654. }
  26655. }
  26656. if (this._pickedDownMesh &&
  26657. this._pickedDownMesh.actionManager &&
  26658. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  26659. this._pickedDownMesh !== this._pickedUpMesh) {
  26660. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  26661. }
  26662. var type = BABYLON.PointerEventTypes.POINTERUP;
  26663. if (this.onPointerObservable.hasObservers()) {
  26664. if (!clickInfo.ignore) {
  26665. if (!clickInfo.hasSwiped) {
  26666. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  26667. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  26668. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  26669. this._setRayOnPointerInfo(pi);
  26670. this.onPointerObservable.notifyObservers(pi, type_2);
  26671. }
  26672. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26673. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  26674. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  26675. this._setRayOnPointerInfo(pi);
  26676. this.onPointerObservable.notifyObservers(pi, type_3);
  26677. }
  26678. }
  26679. }
  26680. else {
  26681. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26682. this._setRayOnPointerInfo(pi);
  26683. this.onPointerObservable.notifyObservers(pi, type);
  26684. }
  26685. }
  26686. if (this.onPointerUp) {
  26687. this.onPointerUp(evt, pickResult, type);
  26688. }
  26689. return this;
  26690. };
  26691. /**
  26692. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  26693. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  26694. * @returns true if the pointer was captured
  26695. */
  26696. Scene.prototype.isPointerCaptured = function (pointerId) {
  26697. if (pointerId === void 0) { pointerId = 0; }
  26698. return this._pointerCaptures[pointerId];
  26699. };
  26700. /** @hidden */
  26701. Scene.prototype._isPointerSwiping = function () {
  26702. return Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  26703. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  26704. };
  26705. /**
  26706. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  26707. * @param attachUp defines if you want to attach events to pointerup
  26708. * @param attachDown defines if you want to attach events to pointerdown
  26709. * @param attachMove defines if you want to attach events to pointermove
  26710. */
  26711. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  26712. var _this = this;
  26713. if (attachUp === void 0) { attachUp = true; }
  26714. if (attachDown === void 0) { attachDown = true; }
  26715. if (attachMove === void 0) { attachMove = true; }
  26716. this._initActionManager = function (act, clickInfo) {
  26717. if (!_this._meshPickProceed) {
  26718. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  26719. _this._currentPickResult = pickResult;
  26720. if (pickResult) {
  26721. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  26722. }
  26723. _this._meshPickProceed = true;
  26724. }
  26725. return act;
  26726. };
  26727. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  26728. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  26729. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  26730. btn !== _this._previousButtonPressed) {
  26731. _this._doubleClickOccured = false;
  26732. clickInfo.singleClick = true;
  26733. clickInfo.ignore = false;
  26734. cb(clickInfo, _this._currentPickResult);
  26735. }
  26736. };
  26737. this._initClickEvent = function (obs1, obs2, evt, cb) {
  26738. var clickInfo = new ClickInfo();
  26739. _this._currentPickResult = null;
  26740. var act = null;
  26741. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  26742. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  26743. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26744. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  26745. act = _this._initActionManager(act, clickInfo);
  26746. if (act) {
  26747. checkPicking = act.hasPickTriggers;
  26748. }
  26749. }
  26750. if (checkPicking) {
  26751. var btn = evt.button;
  26752. clickInfo.hasSwiped = _this._isPointerSwiping();
  26753. if (!clickInfo.hasSwiped) {
  26754. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  26755. if (!checkSingleClickImmediately) {
  26756. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  26757. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26758. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26759. act = _this._initActionManager(act, clickInfo);
  26760. if (act) {
  26761. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  26762. }
  26763. }
  26764. }
  26765. if (checkSingleClickImmediately) {
  26766. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  26767. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  26768. btn !== _this._previousButtonPressed) {
  26769. clickInfo.singleClick = true;
  26770. cb(clickInfo, _this._currentPickResult);
  26771. }
  26772. }
  26773. // at least one double click is required to be check and exclusive double click is enabled
  26774. else {
  26775. // wait that no double click has been raised during the double click delay
  26776. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26777. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  26778. }
  26779. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  26780. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26781. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26782. act = _this._initActionManager(act, clickInfo);
  26783. if (act) {
  26784. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  26785. }
  26786. }
  26787. if (checkDoubleClick) {
  26788. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  26789. if (btn === _this._previousButtonPressed &&
  26790. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  26791. !_this._doubleClickOccured) {
  26792. // pointer has not moved for 2 clicks, it's a double click
  26793. if (!clickInfo.hasSwiped &&
  26794. !_this._isPointerSwiping()) {
  26795. _this._previousStartingPointerTime = 0;
  26796. _this._doubleClickOccured = true;
  26797. clickInfo.doubleClick = true;
  26798. clickInfo.ignore = false;
  26799. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  26800. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  26801. }
  26802. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26803. cb(clickInfo, _this._currentPickResult);
  26804. }
  26805. // if the two successive clicks are too far, it's just two simple clicks
  26806. else {
  26807. _this._doubleClickOccured = false;
  26808. _this._previousStartingPointerTime = _this._startingPointerTime;
  26809. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  26810. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  26811. _this._previousButtonPressed = btn;
  26812. if (Scene.ExclusiveDoubleClickMode) {
  26813. if (_this._previousDelayedSimpleClickTimeout) {
  26814. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  26815. }
  26816. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26817. cb(clickInfo, _this._previousPickResult);
  26818. }
  26819. else {
  26820. cb(clickInfo, _this._currentPickResult);
  26821. }
  26822. }
  26823. }
  26824. // just the first click of the double has been raised
  26825. else {
  26826. _this._doubleClickOccured = false;
  26827. _this._previousStartingPointerTime = _this._startingPointerTime;
  26828. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  26829. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  26830. _this._previousButtonPressed = btn;
  26831. }
  26832. }
  26833. }
  26834. }
  26835. clickInfo.ignore = true;
  26836. cb(clickInfo, _this._currentPickResult);
  26837. };
  26838. this._onPointerMove = function (evt) {
  26839. _this._updatePointerPosition(evt);
  26840. // PreObservable support
  26841. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  26842. return;
  26843. }
  26844. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26845. return;
  26846. }
  26847. if (!_this.pointerMovePredicate) {
  26848. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  26849. }
  26850. // Meshes
  26851. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  26852. _this._processPointerMove(pickResult, evt);
  26853. };
  26854. this._onPointerDown = function (evt) {
  26855. _this._totalPointersPressed++;
  26856. _this._pickedDownMesh = null;
  26857. _this._meshPickProceed = false;
  26858. _this._updatePointerPosition(evt);
  26859. if (_this.preventDefaultOnPointerDown && canvas) {
  26860. evt.preventDefault();
  26861. canvas.focus();
  26862. }
  26863. // PreObservable support
  26864. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  26865. return;
  26866. }
  26867. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26868. return;
  26869. }
  26870. _this._pointerCaptures[evt.pointerId] = true;
  26871. _this._startingPointerPosition.x = _this._pointerX;
  26872. _this._startingPointerPosition.y = _this._pointerY;
  26873. _this._startingPointerTime = Date.now();
  26874. if (!_this.pointerDownPredicate) {
  26875. _this.pointerDownPredicate = function (mesh) {
  26876. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  26877. };
  26878. }
  26879. // Meshes
  26880. _this._pickedDownMesh = null;
  26881. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  26882. _this._processPointerDown(pickResult, evt);
  26883. };
  26884. this._onPointerUp = function (evt) {
  26885. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  26886. return; // So we need to test it the pointer down was pressed before.
  26887. }
  26888. _this._totalPointersPressed--;
  26889. _this._pickedUpMesh = null;
  26890. _this._meshPickProceed = false;
  26891. _this._updatePointerPosition(evt);
  26892. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  26893. // PreObservable support
  26894. if (_this.onPrePointerObservable.hasObservers()) {
  26895. if (!clickInfo.ignore) {
  26896. if (!clickInfo.hasSwiped) {
  26897. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  26898. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  26899. return;
  26900. }
  26901. }
  26902. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26903. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26904. return;
  26905. }
  26906. }
  26907. }
  26908. }
  26909. else {
  26910. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  26911. return;
  26912. }
  26913. }
  26914. }
  26915. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26916. return;
  26917. }
  26918. _this._pointerCaptures[evt.pointerId] = false;
  26919. if (!_this.pointerUpPredicate) {
  26920. _this.pointerUpPredicate = function (mesh) {
  26921. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  26922. };
  26923. }
  26924. // Meshes
  26925. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  26926. _this._initActionManager(null, clickInfo);
  26927. }
  26928. if (!pickResult) {
  26929. pickResult = _this._currentPickResult;
  26930. }
  26931. _this._processPointerUp(pickResult, evt, clickInfo);
  26932. _this._previousPickResult = _this._currentPickResult;
  26933. });
  26934. };
  26935. this._onKeyDown = function (evt) {
  26936. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  26937. if (_this.onPreKeyboardObservable.hasObservers()) {
  26938. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  26939. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  26940. if (pi.skipOnPointerObservable) {
  26941. return;
  26942. }
  26943. }
  26944. if (_this.onKeyboardObservable.hasObservers()) {
  26945. var pi = new BABYLON.KeyboardInfo(type, evt);
  26946. _this.onKeyboardObservable.notifyObservers(pi, type);
  26947. }
  26948. if (_this.actionManager) {
  26949. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  26950. }
  26951. };
  26952. this._onKeyUp = function (evt) {
  26953. var type = BABYLON.KeyboardEventTypes.KEYUP;
  26954. if (_this.onPreKeyboardObservable.hasObservers()) {
  26955. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  26956. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  26957. if (pi.skipOnPointerObservable) {
  26958. return;
  26959. }
  26960. }
  26961. if (_this.onKeyboardObservable.hasObservers()) {
  26962. var pi = new BABYLON.KeyboardInfo(type, evt);
  26963. _this.onKeyboardObservable.notifyObservers(pi, type);
  26964. }
  26965. if (_this.actionManager) {
  26966. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  26967. }
  26968. };
  26969. var engine = this.getEngine();
  26970. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  26971. if (!canvas) {
  26972. return;
  26973. }
  26974. canvas.addEventListener("keydown", _this._onKeyDown, false);
  26975. canvas.addEventListener("keyup", _this._onKeyUp, false);
  26976. });
  26977. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  26978. if (!canvas) {
  26979. return;
  26980. }
  26981. canvas.removeEventListener("keydown", _this._onKeyDown);
  26982. canvas.removeEventListener("keyup", _this._onKeyUp);
  26983. });
  26984. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  26985. var canvas = this._engine.getRenderingCanvas();
  26986. if (!canvas) {
  26987. return;
  26988. }
  26989. if (attachMove) {
  26990. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  26991. // Wheel
  26992. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  26993. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  26994. }
  26995. if (attachDown) {
  26996. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  26997. }
  26998. if (attachUp) {
  26999. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  27000. }
  27001. canvas.tabIndex = 1;
  27002. };
  27003. /** Detaches all event handlers*/
  27004. Scene.prototype.detachControl = function () {
  27005. var engine = this.getEngine();
  27006. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  27007. var canvas = engine.getRenderingCanvas();
  27008. if (!canvas) {
  27009. return;
  27010. }
  27011. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  27012. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  27013. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  27014. if (this._onCanvasBlurObserver) {
  27015. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  27016. }
  27017. if (this._onCanvasFocusObserver) {
  27018. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  27019. }
  27020. // Wheel
  27021. canvas.removeEventListener('mousewheel', this._onPointerMove);
  27022. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  27023. // Keyboard
  27024. canvas.removeEventListener("keydown", this._onKeyDown);
  27025. canvas.removeEventListener("keyup", this._onKeyUp);
  27026. // Observables
  27027. this.onKeyboardObservable.clear();
  27028. this.onPreKeyboardObservable.clear();
  27029. this.onPointerObservable.clear();
  27030. this.onPrePointerObservable.clear();
  27031. };
  27032. /**
  27033. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  27034. * Delay loaded resources are not taking in account
  27035. * @return true if all required resources are ready
  27036. */
  27037. Scene.prototype.isReady = function () {
  27038. if (this._isDisposed) {
  27039. return false;
  27040. }
  27041. if (this._pendingData.length > 0) {
  27042. return false;
  27043. }
  27044. var index;
  27045. var engine = this.getEngine();
  27046. // Geometries
  27047. for (index = 0; index < this.geometries.length; index++) {
  27048. var geometry = this.geometries[index];
  27049. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27050. return false;
  27051. }
  27052. }
  27053. // Meshes
  27054. for (index = 0; index < this.meshes.length; index++) {
  27055. var mesh = this.meshes[index];
  27056. if (!mesh.isEnabled()) {
  27057. continue;
  27058. }
  27059. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  27060. continue;
  27061. }
  27062. if (!mesh.isReady(true)) {
  27063. return false;
  27064. }
  27065. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  27066. // Is Ready For Mesh
  27067. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  27068. var step = _a[_i];
  27069. if (!step.action(mesh, hardwareInstancedRendering)) {
  27070. return false;
  27071. }
  27072. }
  27073. }
  27074. // Post-processes
  27075. if (this.activeCameras && this.activeCameras.length > 0) {
  27076. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  27077. var camera = _c[_b];
  27078. if (!camera.isReady(true)) {
  27079. return false;
  27080. }
  27081. }
  27082. }
  27083. else if (this.activeCamera) {
  27084. if (!this.activeCamera.isReady(true)) {
  27085. return false;
  27086. }
  27087. }
  27088. // Particles
  27089. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  27090. var particleSystem = _e[_d];
  27091. if (!particleSystem.isReady()) {
  27092. return false;
  27093. }
  27094. }
  27095. return true;
  27096. };
  27097. /** Resets all cached information relative to material (including effect and visibility) */
  27098. Scene.prototype.resetCachedMaterial = function () {
  27099. this._cachedMaterial = null;
  27100. this._cachedEffect = null;
  27101. this._cachedVisibility = null;
  27102. };
  27103. /**
  27104. * Registers a function to be called before every frame render
  27105. * @param func defines the function to register
  27106. */
  27107. Scene.prototype.registerBeforeRender = function (func) {
  27108. this.onBeforeRenderObservable.add(func);
  27109. };
  27110. /**
  27111. * Unregisters a function called before every frame render
  27112. * @param func defines the function to unregister
  27113. */
  27114. Scene.prototype.unregisterBeforeRender = function (func) {
  27115. this.onBeforeRenderObservable.removeCallback(func);
  27116. };
  27117. /**
  27118. * Registers a function to be called after every frame render
  27119. * @param func defines the function to register
  27120. */
  27121. Scene.prototype.registerAfterRender = function (func) {
  27122. this.onAfterRenderObservable.add(func);
  27123. };
  27124. /**
  27125. * Unregisters a function called after every frame render
  27126. * @param func defines the function to unregister
  27127. */
  27128. Scene.prototype.unregisterAfterRender = function (func) {
  27129. this.onAfterRenderObservable.removeCallback(func);
  27130. };
  27131. Scene.prototype._executeOnceBeforeRender = function (func) {
  27132. var _this = this;
  27133. var execFunc = function () {
  27134. func();
  27135. setTimeout(function () {
  27136. _this.unregisterBeforeRender(execFunc);
  27137. });
  27138. };
  27139. this.registerBeforeRender(execFunc);
  27140. };
  27141. /**
  27142. * The provided function will run before render once and will be disposed afterwards.
  27143. * A timeout delay can be provided so that the function will be executed in N ms.
  27144. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  27145. * @param func The function to be executed.
  27146. * @param timeout optional delay in ms
  27147. */
  27148. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  27149. var _this = this;
  27150. if (timeout !== undefined) {
  27151. setTimeout(function () {
  27152. _this._executeOnceBeforeRender(func);
  27153. }, timeout);
  27154. }
  27155. else {
  27156. this._executeOnceBeforeRender(func);
  27157. }
  27158. };
  27159. /** @hidden */
  27160. Scene.prototype._addPendingData = function (data) {
  27161. this._pendingData.push(data);
  27162. };
  27163. /** @hidden */
  27164. Scene.prototype._removePendingData = function (data) {
  27165. var wasLoading = this.isLoading;
  27166. var index = this._pendingData.indexOf(data);
  27167. if (index !== -1) {
  27168. this._pendingData.splice(index, 1);
  27169. }
  27170. if (wasLoading && !this.isLoading) {
  27171. this.onDataLoadedObservable.notifyObservers(this);
  27172. }
  27173. };
  27174. /**
  27175. * Returns the number of items waiting to be loaded
  27176. * @returns the number of items waiting to be loaded
  27177. */
  27178. Scene.prototype.getWaitingItemsCount = function () {
  27179. return this._pendingData.length;
  27180. };
  27181. Object.defineProperty(Scene.prototype, "isLoading", {
  27182. /**
  27183. * Returns a boolean indicating if the scene is still loading data
  27184. */
  27185. get: function () {
  27186. return this._pendingData.length > 0;
  27187. },
  27188. enumerable: true,
  27189. configurable: true
  27190. });
  27191. /**
  27192. * Registers a function to be executed when the scene is ready
  27193. * @param {Function} func - the function to be executed
  27194. */
  27195. Scene.prototype.executeWhenReady = function (func) {
  27196. var _this = this;
  27197. this.onReadyObservable.add(func);
  27198. if (this._executeWhenReadyTimeoutId !== -1) {
  27199. return;
  27200. }
  27201. this._executeWhenReadyTimeoutId = setTimeout(function () {
  27202. _this._checkIsReady();
  27203. }, 150);
  27204. };
  27205. /**
  27206. * Returns a promise that resolves when the scene is ready
  27207. * @returns A promise that resolves when the scene is ready
  27208. */
  27209. Scene.prototype.whenReadyAsync = function () {
  27210. var _this = this;
  27211. return new Promise(function (resolve) {
  27212. _this.executeWhenReady(function () {
  27213. resolve();
  27214. });
  27215. });
  27216. };
  27217. /** @hidden */
  27218. Scene.prototype._checkIsReady = function () {
  27219. var _this = this;
  27220. this._registerTransientComponents();
  27221. if (this.isReady()) {
  27222. this.onReadyObservable.notifyObservers(this);
  27223. this.onReadyObservable.clear();
  27224. this._executeWhenReadyTimeoutId = -1;
  27225. return;
  27226. }
  27227. this._executeWhenReadyTimeoutId = setTimeout(function () {
  27228. _this._checkIsReady();
  27229. }, 150);
  27230. };
  27231. // Animations
  27232. /**
  27233. * Will start the animation sequence of a given target
  27234. * @param target defines the target
  27235. * @param from defines from which frame should animation start
  27236. * @param to defines until which frame should animation run.
  27237. * @param weight defines the weight to apply to the animation (1.0 by default)
  27238. * @param loop defines if the animation loops
  27239. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  27240. * @param onAnimationEnd defines the function to be executed when the animation ends
  27241. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  27242. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  27243. * @returns the animatable object created for this animation
  27244. */
  27245. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  27246. if (weight === void 0) { weight = 1.0; }
  27247. if (speedRatio === void 0) { speedRatio = 1.0; }
  27248. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  27249. returnedAnimatable.weight = weight;
  27250. return returnedAnimatable;
  27251. };
  27252. /**
  27253. * Will start the animation sequence of a given target
  27254. * @param target defines the target
  27255. * @param from defines from which frame should animation start
  27256. * @param to defines until which frame should animation run.
  27257. * @param loop defines if the animation loops
  27258. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  27259. * @param onAnimationEnd defines the function to be executed when the animation ends
  27260. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  27261. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  27262. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  27263. * @returns the animatable object created for this animation
  27264. */
  27265. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  27266. if (speedRatio === void 0) { speedRatio = 1.0; }
  27267. if (stopCurrent === void 0) { stopCurrent = true; }
  27268. if (from > to && speedRatio > 0) {
  27269. speedRatio *= -1;
  27270. }
  27271. if (stopCurrent) {
  27272. this.stopAnimation(target, undefined, targetMask);
  27273. }
  27274. if (!animatable) {
  27275. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  27276. }
  27277. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  27278. // Local animations
  27279. if (target.animations && shouldRunTargetAnimations) {
  27280. animatable.appendAnimations(target, target.animations);
  27281. }
  27282. // Children animations
  27283. if (target.getAnimatables) {
  27284. var animatables = target.getAnimatables();
  27285. for (var index = 0; index < animatables.length; index++) {
  27286. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  27287. }
  27288. }
  27289. animatable.reset();
  27290. return animatable;
  27291. };
  27292. /**
  27293. * Begin a new animation on a given node
  27294. * @param target defines the target where the animation will take place
  27295. * @param animations defines the list of animations to start
  27296. * @param from defines the initial value
  27297. * @param to defines the final value
  27298. * @param loop defines if you want animation to loop (off by default)
  27299. * @param speedRatio defines the speed ratio to apply to all animations
  27300. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  27301. * @returns the list of created animatables
  27302. */
  27303. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  27304. if (speedRatio === undefined) {
  27305. speedRatio = 1.0;
  27306. }
  27307. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  27308. return animatable;
  27309. };
  27310. /**
  27311. * Begin a new animation on a given node and its hierarchy
  27312. * @param target defines the root node where the animation will take place
  27313. * @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.
  27314. * @param animations defines the list of animations to start
  27315. * @param from defines the initial value
  27316. * @param to defines the final value
  27317. * @param loop defines if you want animation to loop (off by default)
  27318. * @param speedRatio defines the speed ratio to apply to all animations
  27319. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  27320. * @returns the list of animatables created for all nodes
  27321. */
  27322. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  27323. var children = target.getDescendants(directDescendantsOnly);
  27324. var result = [];
  27325. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  27326. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  27327. var child = children_1[_i];
  27328. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  27329. }
  27330. return result;
  27331. };
  27332. /**
  27333. * Gets the animatable associated with a specific target
  27334. * @param target defines the target of the animatable
  27335. * @returns the required animatable if found
  27336. */
  27337. Scene.prototype.getAnimatableByTarget = function (target) {
  27338. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27339. if (this._activeAnimatables[index].target === target) {
  27340. return this._activeAnimatables[index];
  27341. }
  27342. }
  27343. return null;
  27344. };
  27345. /**
  27346. * Gets all animatables associated with a given target
  27347. * @param target defines the target to look animatables for
  27348. * @returns an array of Animatables
  27349. */
  27350. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  27351. var result = [];
  27352. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27353. if (this._activeAnimatables[index].target === target) {
  27354. result.push(this._activeAnimatables[index]);
  27355. }
  27356. }
  27357. return result;
  27358. };
  27359. Object.defineProperty(Scene.prototype, "animatables", {
  27360. /**
  27361. * Gets all animatable attached to the scene
  27362. */
  27363. get: function () {
  27364. return this._activeAnimatables;
  27365. },
  27366. enumerable: true,
  27367. configurable: true
  27368. });
  27369. /**
  27370. * Will stop the animation of the given target
  27371. * @param target - the target
  27372. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  27373. * @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)
  27374. */
  27375. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  27376. var animatables = this.getAllAnimatablesByTarget(target);
  27377. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  27378. var animatable = animatables_1[_i];
  27379. animatable.stop(animationName, targetMask);
  27380. }
  27381. };
  27382. /**
  27383. * Stops and removes all animations that have been applied to the scene
  27384. */
  27385. Scene.prototype.stopAllAnimations = function () {
  27386. if (this._activeAnimatables) {
  27387. for (var i = 0; i < this._activeAnimatables.length; i++) {
  27388. this._activeAnimatables[i].stop();
  27389. }
  27390. this._activeAnimatables = [];
  27391. }
  27392. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  27393. var group = _a[_i];
  27394. group.stop();
  27395. }
  27396. };
  27397. Scene.prototype._animate = function () {
  27398. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  27399. return;
  27400. }
  27401. // Getting time
  27402. var now = BABYLON.Tools.Now;
  27403. if (!this._animationTimeLast) {
  27404. if (this._pendingData.length > 0) {
  27405. return;
  27406. }
  27407. this._animationTimeLast = now;
  27408. }
  27409. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  27410. this._animationTime += deltaTime;
  27411. this._animationTimeLast = now;
  27412. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27413. this._activeAnimatables[index]._animate(this._animationTime);
  27414. }
  27415. // Late animation bindings
  27416. this._processLateAnimationBindings();
  27417. };
  27418. /** @hidden */
  27419. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  27420. var target = runtimeAnimation.target;
  27421. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  27422. if (!target._lateAnimationHolders) {
  27423. target._lateAnimationHolders = {};
  27424. }
  27425. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  27426. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  27427. totalWeight: 0,
  27428. animations: [],
  27429. originalValue: originalValue
  27430. };
  27431. }
  27432. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  27433. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  27434. };
  27435. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  27436. var normalizer = 1.0;
  27437. var finalPosition = BABYLON.Tmp.Vector3[0];
  27438. var finalScaling = BABYLON.Tmp.Vector3[1];
  27439. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  27440. var startIndex = 0;
  27441. var originalAnimation = holder.animations[0];
  27442. var originalValue = holder.originalValue;
  27443. var scale = 1;
  27444. if (holder.totalWeight < 1.0) {
  27445. // We need to mix the original value in
  27446. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  27447. scale = 1.0 - holder.totalWeight;
  27448. }
  27449. else {
  27450. startIndex = 1;
  27451. // We need to normalize the weights
  27452. normalizer = holder.totalWeight;
  27453. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  27454. scale = originalAnimation.weight / normalizer;
  27455. if (scale == 1) {
  27456. return originalAnimation.currentValue;
  27457. }
  27458. }
  27459. finalScaling.scaleInPlace(scale);
  27460. finalPosition.scaleInPlace(scale);
  27461. finalQuaternion.scaleInPlace(scale);
  27462. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  27463. var runtimeAnimation = holder.animations[animIndex];
  27464. var scale = runtimeAnimation.weight / normalizer;
  27465. var currentPosition = BABYLON.Tmp.Vector3[2];
  27466. var currentScaling = BABYLON.Tmp.Vector3[3];
  27467. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  27468. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  27469. currentScaling.scaleAndAddToRef(scale, finalScaling);
  27470. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  27471. currentPosition.scaleAndAddToRef(scale, finalPosition);
  27472. }
  27473. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  27474. return originalAnimation._workValue;
  27475. };
  27476. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) {
  27477. var originalAnimation = holder.animations[0];
  27478. var originalValue = holder.originalValue;
  27479. if (holder.animations.length === 1) {
  27480. BABYLON.Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), refQuaternion);
  27481. return refQuaternion;
  27482. }
  27483. var normalizer = 1.0;
  27484. var quaternions;
  27485. var weights;
  27486. if (holder.totalWeight < 1.0) {
  27487. var scale = 1.0 - holder.totalWeight;
  27488. quaternions = [];
  27489. weights = [];
  27490. quaternions.push(originalValue);
  27491. weights.push(scale);
  27492. }
  27493. else {
  27494. if (holder.animations.length === 2) { // Slerp as soon as we can
  27495. BABYLON.Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);
  27496. return refQuaternion;
  27497. }
  27498. quaternions = [];
  27499. weights = [];
  27500. normalizer = holder.totalWeight;
  27501. }
  27502. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  27503. var runtimeAnimation = holder.animations[animIndex];
  27504. quaternions.push(runtimeAnimation.currentValue);
  27505. weights.push(runtimeAnimation.weight / normalizer);
  27506. }
  27507. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  27508. var cumulativeAmount = 0;
  27509. var cumulativeQuaternion = null;
  27510. for (var index = 0; index < quaternions.length;) {
  27511. if (!cumulativeQuaternion) {
  27512. BABYLON.Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);
  27513. cumulativeQuaternion = refQuaternion;
  27514. cumulativeAmount = weights[index] + weights[index + 1];
  27515. index += 2;
  27516. continue;
  27517. }
  27518. cumulativeAmount += weights[index];
  27519. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  27520. index++;
  27521. }
  27522. return cumulativeQuaternion;
  27523. };
  27524. Scene.prototype._processLateAnimationBindings = function () {
  27525. if (!this._registeredForLateAnimationBindings.length) {
  27526. return;
  27527. }
  27528. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  27529. var target = this._registeredForLateAnimationBindings.data[index];
  27530. for (var path in target._lateAnimationHolders) {
  27531. var holder = target._lateAnimationHolders[path];
  27532. var originalAnimation = holder.animations[0];
  27533. var originalValue = holder.originalValue;
  27534. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  27535. var finalValue = target[path];
  27536. if (matrixDecomposeMode) {
  27537. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  27538. }
  27539. else {
  27540. var quaternionMode = originalValue.w !== undefined;
  27541. if (quaternionMode) {
  27542. finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || BABYLON.Quaternion.Identity());
  27543. }
  27544. else {
  27545. var startIndex = 0;
  27546. var normalizer = 1.0;
  27547. if (holder.totalWeight < 1.0) {
  27548. // We need to mix the original value in
  27549. if (originalValue.scale) {
  27550. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  27551. }
  27552. else {
  27553. finalValue = originalValue * (1.0 - holder.totalWeight);
  27554. }
  27555. }
  27556. else {
  27557. // We need to normalize the weights
  27558. normalizer = holder.totalWeight;
  27559. var scale_1 = originalAnimation.weight / normalizer;
  27560. if (scale_1 !== 1) {
  27561. if (originalAnimation.currentValue.scale) {
  27562. finalValue = originalAnimation.currentValue.scale(scale_1);
  27563. }
  27564. else {
  27565. finalValue = originalAnimation.currentValue * scale_1;
  27566. }
  27567. }
  27568. else {
  27569. finalValue = originalAnimation.currentValue;
  27570. }
  27571. startIndex = 1;
  27572. }
  27573. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  27574. var runtimeAnimation = holder.animations[animIndex];
  27575. var scale = runtimeAnimation.weight / normalizer;
  27576. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  27577. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  27578. }
  27579. else {
  27580. finalValue += runtimeAnimation.currentValue * scale;
  27581. }
  27582. }
  27583. }
  27584. }
  27585. target[path] = finalValue;
  27586. }
  27587. target._lateAnimationHolders = {};
  27588. }
  27589. this._registeredForLateAnimationBindings.reset();
  27590. };
  27591. // Matrix
  27592. /** @hidden */
  27593. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  27594. this._useAlternateCameraConfiguration = active;
  27595. };
  27596. /**
  27597. * Gets the current view matrix
  27598. * @returns a Matrix
  27599. */
  27600. Scene.prototype.getViewMatrix = function () {
  27601. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  27602. };
  27603. /**
  27604. * Gets the current projection matrix
  27605. * @returns a Matrix
  27606. */
  27607. Scene.prototype.getProjectionMatrix = function () {
  27608. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  27609. };
  27610. /**
  27611. * Gets the current transform matrix
  27612. * @returns a Matrix made of View * Projection
  27613. */
  27614. Scene.prototype.getTransformMatrix = function () {
  27615. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  27616. };
  27617. /**
  27618. * Sets the current transform matrix
  27619. * @param view defines the View matrix to use
  27620. * @param projection defines the Projection matrix to use
  27621. */
  27622. Scene.prototype.setTransformMatrix = function (view, projection) {
  27623. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  27624. return;
  27625. }
  27626. this._viewUpdateFlag = view.updateFlag;
  27627. this._projectionUpdateFlag = projection.updateFlag;
  27628. this._viewMatrix = view;
  27629. this._projectionMatrix = projection;
  27630. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  27631. // Update frustum
  27632. if (!this._frustumPlanes) {
  27633. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  27634. }
  27635. else {
  27636. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  27637. }
  27638. if (this.activeCamera && this.activeCamera._alternateCamera) {
  27639. var otherCamera = this.activeCamera._alternateCamera;
  27640. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  27641. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  27642. }
  27643. if (this._sceneUbo.useUbo) {
  27644. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  27645. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  27646. this._sceneUbo.update();
  27647. }
  27648. };
  27649. /** @hidden */
  27650. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  27651. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  27652. return;
  27653. }
  27654. this._alternateViewUpdateFlag = view.updateFlag;
  27655. this._alternateProjectionUpdateFlag = projection.updateFlag;
  27656. this._alternateViewMatrix = view;
  27657. this._alternateProjectionMatrix = projection;
  27658. if (!this._alternateTransformMatrix) {
  27659. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  27660. }
  27661. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  27662. if (!this._alternateSceneUbo) {
  27663. this._createAlternateUbo();
  27664. }
  27665. if (this._alternateSceneUbo.useUbo) {
  27666. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  27667. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  27668. this._alternateSceneUbo.update();
  27669. }
  27670. };
  27671. /**
  27672. * Gets the uniform buffer used to store scene data
  27673. * @returns a UniformBuffer
  27674. */
  27675. Scene.prototype.getSceneUniformBuffer = function () {
  27676. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  27677. };
  27678. /**
  27679. * Gets an unique (relatively to the current scene) Id
  27680. * @returns an unique number for the scene
  27681. */
  27682. Scene.prototype.getUniqueId = function () {
  27683. var result = Scene._uniqueIdCounter;
  27684. Scene._uniqueIdCounter++;
  27685. return result;
  27686. };
  27687. /**
  27688. * Add a mesh to the list of scene's meshes
  27689. * @param newMesh defines the mesh to add
  27690. * @param recursive if all child meshes should also be added to the scene
  27691. */
  27692. Scene.prototype.addMesh = function (newMesh, recursive) {
  27693. var _this = this;
  27694. if (recursive === void 0) { recursive = false; }
  27695. this.meshes.push(newMesh);
  27696. //notify the collision coordinator
  27697. if (this.collisionCoordinator) {
  27698. this.collisionCoordinator.onMeshAdded(newMesh);
  27699. }
  27700. newMesh._resyncLightSources();
  27701. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  27702. if (recursive) {
  27703. newMesh.getChildMeshes().forEach(function (m) {
  27704. _this.addMesh(m);
  27705. });
  27706. }
  27707. };
  27708. /**
  27709. * Remove a mesh for the list of scene's meshes
  27710. * @param toRemove defines the mesh to remove
  27711. * @param recursive if all child meshes should also be removed from the scene
  27712. * @returns the index where the mesh was in the mesh list
  27713. */
  27714. Scene.prototype.removeMesh = function (toRemove, recursive) {
  27715. var _this = this;
  27716. if (recursive === void 0) { recursive = false; }
  27717. var index = this.meshes.indexOf(toRemove);
  27718. if (index !== -1) {
  27719. // Remove from the scene if mesh found
  27720. this.meshes.splice(index, 1);
  27721. }
  27722. this.onMeshRemovedObservable.notifyObservers(toRemove);
  27723. if (recursive) {
  27724. toRemove.getChildMeshes().forEach(function (m) {
  27725. _this.removeMesh(m);
  27726. });
  27727. }
  27728. return index;
  27729. };
  27730. /**
  27731. * Add a transform node to the list of scene's transform nodes
  27732. * @param newTransformNode defines the transform node to add
  27733. */
  27734. Scene.prototype.addTransformNode = function (newTransformNode) {
  27735. this.transformNodes.push(newTransformNode);
  27736. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  27737. };
  27738. /**
  27739. * Remove a transform node for the list of scene's transform nodes
  27740. * @param toRemove defines the transform node to remove
  27741. * @returns the index where the transform node was in the transform node list
  27742. */
  27743. Scene.prototype.removeTransformNode = function (toRemove) {
  27744. var index = this.transformNodes.indexOf(toRemove);
  27745. if (index !== -1) {
  27746. // Remove from the scene if found
  27747. this.transformNodes.splice(index, 1);
  27748. }
  27749. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  27750. return index;
  27751. };
  27752. /**
  27753. * Remove a skeleton for the list of scene's skeletons
  27754. * @param toRemove defines the skeleton to remove
  27755. * @returns the index where the skeleton was in the skeleton list
  27756. */
  27757. Scene.prototype.removeSkeleton = function (toRemove) {
  27758. var index = this.skeletons.indexOf(toRemove);
  27759. if (index !== -1) {
  27760. // Remove from the scene if found
  27761. this.skeletons.splice(index, 1);
  27762. }
  27763. return index;
  27764. };
  27765. /**
  27766. * Remove a morph target for the list of scene's morph targets
  27767. * @param toRemove defines the morph target to remove
  27768. * @returns the index where the morph target was in the morph target list
  27769. */
  27770. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  27771. var index = this.morphTargetManagers.indexOf(toRemove);
  27772. if (index !== -1) {
  27773. // Remove from the scene if found
  27774. this.morphTargetManagers.splice(index, 1);
  27775. }
  27776. return index;
  27777. };
  27778. /**
  27779. * Remove a light for the list of scene's lights
  27780. * @param toRemove defines the light to remove
  27781. * @returns the index where the light was in the light list
  27782. */
  27783. Scene.prototype.removeLight = function (toRemove) {
  27784. var index = this.lights.indexOf(toRemove);
  27785. if (index !== -1) {
  27786. // Remove from meshes
  27787. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  27788. var mesh = _a[_i];
  27789. mesh._removeLightSource(toRemove);
  27790. }
  27791. // Remove from the scene if mesh found
  27792. this.lights.splice(index, 1);
  27793. this.sortLightsByPriority();
  27794. }
  27795. this.onLightRemovedObservable.notifyObservers(toRemove);
  27796. return index;
  27797. };
  27798. /**
  27799. * Remove a camera for the list of scene's cameras
  27800. * @param toRemove defines the camera to remove
  27801. * @returns the index where the camera was in the camera list
  27802. */
  27803. Scene.prototype.removeCamera = function (toRemove) {
  27804. var index = this.cameras.indexOf(toRemove);
  27805. if (index !== -1) {
  27806. // Remove from the scene if mesh found
  27807. this.cameras.splice(index, 1);
  27808. }
  27809. // Remove from activeCameras
  27810. var index2 = this.activeCameras.indexOf(toRemove);
  27811. if (index2 !== -1) {
  27812. // Remove from the scene if mesh found
  27813. this.activeCameras.splice(index2, 1);
  27814. }
  27815. // Reset the activeCamera
  27816. if (this.activeCamera === toRemove) {
  27817. if (this.cameras.length > 0) {
  27818. this.activeCamera = this.cameras[0];
  27819. }
  27820. else {
  27821. this.activeCamera = null;
  27822. }
  27823. }
  27824. this.onCameraRemovedObservable.notifyObservers(toRemove);
  27825. return index;
  27826. };
  27827. /**
  27828. * Remove a particle system for the list of scene's particle systems
  27829. * @param toRemove defines the particle system to remove
  27830. * @returns the index where the particle system was in the particle system list
  27831. */
  27832. Scene.prototype.removeParticleSystem = function (toRemove) {
  27833. var index = this.particleSystems.indexOf(toRemove);
  27834. if (index !== -1) {
  27835. this.particleSystems.splice(index, 1);
  27836. }
  27837. return index;
  27838. };
  27839. /**
  27840. * Remove a animation for the list of scene's animations
  27841. * @param toRemove defines the animation to remove
  27842. * @returns the index where the animation was in the animation list
  27843. */
  27844. Scene.prototype.removeAnimation = function (toRemove) {
  27845. var index = this.animations.indexOf(toRemove);
  27846. if (index !== -1) {
  27847. this.animations.splice(index, 1);
  27848. }
  27849. return index;
  27850. };
  27851. /**
  27852. * Removes the given animation group from this scene.
  27853. * @param toRemove The animation group to remove
  27854. * @returns The index of the removed animation group
  27855. */
  27856. Scene.prototype.removeAnimationGroup = function (toRemove) {
  27857. var index = this.animationGroups.indexOf(toRemove);
  27858. if (index !== -1) {
  27859. this.animationGroups.splice(index, 1);
  27860. }
  27861. return index;
  27862. };
  27863. /**
  27864. * Removes the given multi-material from this scene.
  27865. * @param toRemove The multi-material to remove
  27866. * @returns The index of the removed multi-material
  27867. */
  27868. Scene.prototype.removeMultiMaterial = function (toRemove) {
  27869. var index = this.multiMaterials.indexOf(toRemove);
  27870. if (index !== -1) {
  27871. this.multiMaterials.splice(index, 1);
  27872. }
  27873. return index;
  27874. };
  27875. /**
  27876. * Removes the given material from this scene.
  27877. * @param toRemove The material to remove
  27878. * @returns The index of the removed material
  27879. */
  27880. Scene.prototype.removeMaterial = function (toRemove) {
  27881. var index = this.materials.indexOf(toRemove);
  27882. if (index !== -1) {
  27883. this.materials.splice(index, 1);
  27884. }
  27885. this.onMaterialRemovedObservable.notifyObservers(toRemove);
  27886. return index;
  27887. };
  27888. /**
  27889. * Removes the given action manager from this scene.
  27890. * @param toRemove The action manager to remove
  27891. * @returns The index of the removed action manager
  27892. */
  27893. Scene.prototype.removeActionManager = function (toRemove) {
  27894. var index = this.actionManagers.indexOf(toRemove);
  27895. if (index !== -1) {
  27896. this.actionManagers.splice(index, 1);
  27897. }
  27898. return index;
  27899. };
  27900. /**
  27901. * Removes the given texture from this scene.
  27902. * @param toRemove The texture to remove
  27903. * @returns The index of the removed texture
  27904. */
  27905. Scene.prototype.removeTexture = function (toRemove) {
  27906. var index = this.textures.indexOf(toRemove);
  27907. if (index !== -1) {
  27908. this.textures.splice(index, 1);
  27909. }
  27910. this.onTextureRemovedObservable.notifyObservers(toRemove);
  27911. return index;
  27912. };
  27913. /**
  27914. * Adds the given light to this scene
  27915. * @param newLight The light to add
  27916. */
  27917. Scene.prototype.addLight = function (newLight) {
  27918. this.lights.push(newLight);
  27919. this.sortLightsByPriority();
  27920. // Add light to all meshes (To support if the light is removed and then readded)
  27921. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  27922. var mesh = _a[_i];
  27923. if (mesh._lightSources.indexOf(newLight) === -1) {
  27924. mesh._lightSources.push(newLight);
  27925. mesh._resyncLightSources();
  27926. }
  27927. }
  27928. this.onNewLightAddedObservable.notifyObservers(newLight);
  27929. };
  27930. /**
  27931. * Sorts the list list based on light priorities
  27932. */
  27933. Scene.prototype.sortLightsByPriority = function () {
  27934. if (this.requireLightSorting) {
  27935. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  27936. }
  27937. };
  27938. /**
  27939. * Adds the given camera to this scene
  27940. * @param newCamera The camera to add
  27941. */
  27942. Scene.prototype.addCamera = function (newCamera) {
  27943. this.cameras.push(newCamera);
  27944. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  27945. };
  27946. /**
  27947. * Adds the given skeleton to this scene
  27948. * @param newSkeleton The skeleton to add
  27949. */
  27950. Scene.prototype.addSkeleton = function (newSkeleton) {
  27951. this.skeletons.push(newSkeleton);
  27952. };
  27953. /**
  27954. * Adds the given particle system to this scene
  27955. * @param newParticleSystem The particle system to add
  27956. */
  27957. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  27958. this.particleSystems.push(newParticleSystem);
  27959. };
  27960. /**
  27961. * Adds the given animation to this scene
  27962. * @param newAnimation The animation to add
  27963. */
  27964. Scene.prototype.addAnimation = function (newAnimation) {
  27965. this.animations.push(newAnimation);
  27966. };
  27967. /**
  27968. * Adds the given animation group to this scene.
  27969. * @param newAnimationGroup The animation group to add
  27970. */
  27971. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  27972. this.animationGroups.push(newAnimationGroup);
  27973. };
  27974. /**
  27975. * Adds the given multi-material to this scene
  27976. * @param newMultiMaterial The multi-material to add
  27977. */
  27978. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  27979. this.multiMaterials.push(newMultiMaterial);
  27980. };
  27981. /**
  27982. * Adds the given material to this scene
  27983. * @param newMaterial The material to add
  27984. */
  27985. Scene.prototype.addMaterial = function (newMaterial) {
  27986. this.materials.push(newMaterial);
  27987. this.onNewMaterialAddedObservable.notifyObservers(newMaterial);
  27988. };
  27989. /**
  27990. * Adds the given morph target to this scene
  27991. * @param newMorphTargetManager The morph target to add
  27992. */
  27993. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  27994. this.morphTargetManagers.push(newMorphTargetManager);
  27995. };
  27996. /**
  27997. * Adds the given geometry to this scene
  27998. * @param newGeometry The geometry to add
  27999. */
  28000. Scene.prototype.addGeometry = function (newGeometry) {
  28001. this.geometries.push(newGeometry);
  28002. };
  28003. /**
  28004. * Adds the given action manager to this scene
  28005. * @param newActionManager The action manager to add
  28006. */
  28007. Scene.prototype.addActionManager = function (newActionManager) {
  28008. this.actionManagers.push(newActionManager);
  28009. };
  28010. /**
  28011. * Adds the given texture to this scene.
  28012. * @param newTexture The texture to add
  28013. */
  28014. Scene.prototype.addTexture = function (newTexture) {
  28015. this.textures.push(newTexture);
  28016. this.onNewTextureAddedObservable.notifyObservers(newTexture);
  28017. };
  28018. /**
  28019. * Switch active camera
  28020. * @param newCamera defines the new active camera
  28021. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  28022. */
  28023. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  28024. if (attachControl === void 0) { attachControl = true; }
  28025. var canvas = this._engine.getRenderingCanvas();
  28026. if (!canvas) {
  28027. return;
  28028. }
  28029. if (this.activeCamera) {
  28030. this.activeCamera.detachControl(canvas);
  28031. }
  28032. this.activeCamera = newCamera;
  28033. if (attachControl) {
  28034. newCamera.attachControl(canvas);
  28035. }
  28036. };
  28037. /**
  28038. * sets the active camera of the scene using its ID
  28039. * @param id defines the camera's ID
  28040. * @return the new active camera or null if none found.
  28041. */
  28042. Scene.prototype.setActiveCameraByID = function (id) {
  28043. var camera = this.getCameraByID(id);
  28044. if (camera) {
  28045. this.activeCamera = camera;
  28046. return camera;
  28047. }
  28048. return null;
  28049. };
  28050. /**
  28051. * sets the active camera of the scene using its name
  28052. * @param name defines the camera's name
  28053. * @returns the new active camera or null if none found.
  28054. */
  28055. Scene.prototype.setActiveCameraByName = function (name) {
  28056. var camera = this.getCameraByName(name);
  28057. if (camera) {
  28058. this.activeCamera = camera;
  28059. return camera;
  28060. }
  28061. return null;
  28062. };
  28063. /**
  28064. * get an animation group using its name
  28065. * @param name defines the material's name
  28066. * @return the animation group or null if none found.
  28067. */
  28068. Scene.prototype.getAnimationGroupByName = function (name) {
  28069. for (var index = 0; index < this.animationGroups.length; index++) {
  28070. if (this.animationGroups[index].name === name) {
  28071. return this.animationGroups[index];
  28072. }
  28073. }
  28074. return null;
  28075. };
  28076. /**
  28077. * get a material using its id
  28078. * @param id defines the material's ID
  28079. * @return the material or null if none found.
  28080. */
  28081. Scene.prototype.getMaterialByID = function (id) {
  28082. for (var index = 0; index < this.materials.length; index++) {
  28083. if (this.materials[index].id === id) {
  28084. return this.materials[index];
  28085. }
  28086. }
  28087. return null;
  28088. };
  28089. /**
  28090. * Gets a material using its name
  28091. * @param name defines the material's name
  28092. * @return the material or null if none found.
  28093. */
  28094. Scene.prototype.getMaterialByName = function (name) {
  28095. for (var index = 0; index < this.materials.length; index++) {
  28096. if (this.materials[index].name === name) {
  28097. return this.materials[index];
  28098. }
  28099. }
  28100. return null;
  28101. };
  28102. /**
  28103. * Gets a camera using its id
  28104. * @param id defines the id to look for
  28105. * @returns the camera or null if not found
  28106. */
  28107. Scene.prototype.getCameraByID = function (id) {
  28108. for (var index = 0; index < this.cameras.length; index++) {
  28109. if (this.cameras[index].id === id) {
  28110. return this.cameras[index];
  28111. }
  28112. }
  28113. return null;
  28114. };
  28115. /**
  28116. * Gets a camera using its unique id
  28117. * @param uniqueId defines the unique id to look for
  28118. * @returns the camera or null if not found
  28119. */
  28120. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  28121. for (var index = 0; index < this.cameras.length; index++) {
  28122. if (this.cameras[index].uniqueId === uniqueId) {
  28123. return this.cameras[index];
  28124. }
  28125. }
  28126. return null;
  28127. };
  28128. /**
  28129. * Gets a camera using its name
  28130. * @param name defines the camera's name
  28131. * @return the camera or null if none found.
  28132. */
  28133. Scene.prototype.getCameraByName = function (name) {
  28134. for (var index = 0; index < this.cameras.length; index++) {
  28135. if (this.cameras[index].name === name) {
  28136. return this.cameras[index];
  28137. }
  28138. }
  28139. return null;
  28140. };
  28141. /**
  28142. * Gets a bone using its id
  28143. * @param id defines the bone's id
  28144. * @return the bone or null if not found
  28145. */
  28146. Scene.prototype.getBoneByID = function (id) {
  28147. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  28148. var skeleton = this.skeletons[skeletonIndex];
  28149. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  28150. if (skeleton.bones[boneIndex].id === id) {
  28151. return skeleton.bones[boneIndex];
  28152. }
  28153. }
  28154. }
  28155. return null;
  28156. };
  28157. /**
  28158. * Gets a bone using its id
  28159. * @param name defines the bone's name
  28160. * @return the bone or null if not found
  28161. */
  28162. Scene.prototype.getBoneByName = function (name) {
  28163. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  28164. var skeleton = this.skeletons[skeletonIndex];
  28165. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  28166. if (skeleton.bones[boneIndex].name === name) {
  28167. return skeleton.bones[boneIndex];
  28168. }
  28169. }
  28170. }
  28171. return null;
  28172. };
  28173. /**
  28174. * Gets a light node using its name
  28175. * @param name defines the the light's name
  28176. * @return the light or null if none found.
  28177. */
  28178. Scene.prototype.getLightByName = function (name) {
  28179. for (var index = 0; index < this.lights.length; index++) {
  28180. if (this.lights[index].name === name) {
  28181. return this.lights[index];
  28182. }
  28183. }
  28184. return null;
  28185. };
  28186. /**
  28187. * Gets a light node using its id
  28188. * @param id defines the light's id
  28189. * @return the light or null if none found.
  28190. */
  28191. Scene.prototype.getLightByID = function (id) {
  28192. for (var index = 0; index < this.lights.length; index++) {
  28193. if (this.lights[index].id === id) {
  28194. return this.lights[index];
  28195. }
  28196. }
  28197. return null;
  28198. };
  28199. /**
  28200. * Gets a light node using its scene-generated unique ID
  28201. * @param uniqueId defines the light's unique id
  28202. * @return the light or null if none found.
  28203. */
  28204. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  28205. for (var index = 0; index < this.lights.length; index++) {
  28206. if (this.lights[index].uniqueId === uniqueId) {
  28207. return this.lights[index];
  28208. }
  28209. }
  28210. return null;
  28211. };
  28212. /**
  28213. * Gets a particle system by id
  28214. * @param id defines the particle system id
  28215. * @return the corresponding system or null if none found
  28216. */
  28217. Scene.prototype.getParticleSystemByID = function (id) {
  28218. for (var index = 0; index < this.particleSystems.length; index++) {
  28219. if (this.particleSystems[index].id === id) {
  28220. return this.particleSystems[index];
  28221. }
  28222. }
  28223. return null;
  28224. };
  28225. /**
  28226. * Gets a geometry using its ID
  28227. * @param id defines the geometry's id
  28228. * @return the geometry or null if none found.
  28229. */
  28230. Scene.prototype.getGeometryByID = function (id) {
  28231. for (var index = 0; index < this.geometries.length; index++) {
  28232. if (this.geometries[index].id === id) {
  28233. return this.geometries[index];
  28234. }
  28235. }
  28236. return null;
  28237. };
  28238. /**
  28239. * Add a new geometry to this scene
  28240. * @param geometry defines the geometry to be added to the scene.
  28241. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  28242. * @return a boolean defining if the geometry was added or not
  28243. */
  28244. Scene.prototype.pushGeometry = function (geometry, force) {
  28245. if (!force && this.getGeometryByID(geometry.id)) {
  28246. return false;
  28247. }
  28248. this.geometries.push(geometry);
  28249. //notify the collision coordinator
  28250. if (this.collisionCoordinator) {
  28251. this.collisionCoordinator.onGeometryAdded(geometry);
  28252. }
  28253. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  28254. return true;
  28255. };
  28256. /**
  28257. * Removes an existing geometry
  28258. * @param geometry defines the geometry to be removed from the scene
  28259. * @return a boolean defining if the geometry was removed or not
  28260. */
  28261. Scene.prototype.removeGeometry = function (geometry) {
  28262. var index = this.geometries.indexOf(geometry);
  28263. if (index > -1) {
  28264. this.geometries.splice(index, 1);
  28265. //notify the collision coordinator
  28266. if (this.collisionCoordinator) {
  28267. this.collisionCoordinator.onGeometryDeleted(geometry);
  28268. }
  28269. this.onGeometryRemovedObservable.notifyObservers(geometry);
  28270. return true;
  28271. }
  28272. return false;
  28273. };
  28274. /**
  28275. * Gets the list of geometries attached to the scene
  28276. * @returns an array of Geometry
  28277. */
  28278. Scene.prototype.getGeometries = function () {
  28279. return this.geometries;
  28280. };
  28281. /**
  28282. * Gets the first added mesh found of a given ID
  28283. * @param id defines the id to search for
  28284. * @return the mesh found or null if not found at all
  28285. */
  28286. Scene.prototype.getMeshByID = function (id) {
  28287. for (var index = 0; index < this.meshes.length; index++) {
  28288. if (this.meshes[index].id === id) {
  28289. return this.meshes[index];
  28290. }
  28291. }
  28292. return null;
  28293. };
  28294. /**
  28295. * Gets a list of meshes using their id
  28296. * @param id defines the id to search for
  28297. * @returns a list of meshes
  28298. */
  28299. Scene.prototype.getMeshesByID = function (id) {
  28300. return this.meshes.filter(function (m) {
  28301. return m.id === id;
  28302. });
  28303. };
  28304. /**
  28305. * Gets the first added transform node found of a given ID
  28306. * @param id defines the id to search for
  28307. * @return the found transform node or null if not found at all.
  28308. */
  28309. Scene.prototype.getTransformNodeByID = function (id) {
  28310. for (var index = 0; index < this.transformNodes.length; index++) {
  28311. if (this.transformNodes[index].id === id) {
  28312. return this.transformNodes[index];
  28313. }
  28314. }
  28315. return null;
  28316. };
  28317. /**
  28318. * Gets a list of transform nodes using their id
  28319. * @param id defines the id to search for
  28320. * @returns a list of transform nodes
  28321. */
  28322. Scene.prototype.getTransformNodesByID = function (id) {
  28323. return this.transformNodes.filter(function (m) {
  28324. return m.id === id;
  28325. });
  28326. };
  28327. /**
  28328. * Gets a mesh with its auto-generated unique id
  28329. * @param uniqueId defines the unique id to search for
  28330. * @return the found mesh or null if not found at all.
  28331. */
  28332. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  28333. for (var index = 0; index < this.meshes.length; index++) {
  28334. if (this.meshes[index].uniqueId === uniqueId) {
  28335. return this.meshes[index];
  28336. }
  28337. }
  28338. return null;
  28339. };
  28340. /**
  28341. * Gets a the last added mesh using a given id
  28342. * @param id defines the id to search for
  28343. * @return the found mesh or null if not found at all.
  28344. */
  28345. Scene.prototype.getLastMeshByID = function (id) {
  28346. for (var index = this.meshes.length - 1; index >= 0; index--) {
  28347. if (this.meshes[index].id === id) {
  28348. return this.meshes[index];
  28349. }
  28350. }
  28351. return null;
  28352. };
  28353. /**
  28354. * Gets a the last added node (Mesh, Camera, Light) using a given id
  28355. * @param id defines the id to search for
  28356. * @return the found node or null if not found at all
  28357. */
  28358. Scene.prototype.getLastEntryByID = function (id) {
  28359. var index;
  28360. for (index = this.meshes.length - 1; index >= 0; index--) {
  28361. if (this.meshes[index].id === id) {
  28362. return this.meshes[index];
  28363. }
  28364. }
  28365. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  28366. if (this.transformNodes[index].id === id) {
  28367. return this.transformNodes[index];
  28368. }
  28369. }
  28370. for (index = this.cameras.length - 1; index >= 0; index--) {
  28371. if (this.cameras[index].id === id) {
  28372. return this.cameras[index];
  28373. }
  28374. }
  28375. for (index = this.lights.length - 1; index >= 0; index--) {
  28376. if (this.lights[index].id === id) {
  28377. return this.lights[index];
  28378. }
  28379. }
  28380. return null;
  28381. };
  28382. /**
  28383. * Gets a node (Mesh, Camera, Light) using a given id
  28384. * @param id defines the id to search for
  28385. * @return the found node or null if not found at all
  28386. */
  28387. Scene.prototype.getNodeByID = function (id) {
  28388. var mesh = this.getMeshByID(id);
  28389. if (mesh) {
  28390. return mesh;
  28391. }
  28392. var light = this.getLightByID(id);
  28393. if (light) {
  28394. return light;
  28395. }
  28396. var camera = this.getCameraByID(id);
  28397. if (camera) {
  28398. return camera;
  28399. }
  28400. var bone = this.getBoneByID(id);
  28401. return bone;
  28402. };
  28403. /**
  28404. * Gets a node (Mesh, Camera, Light) using a given name
  28405. * @param name defines the name to search for
  28406. * @return the found node or null if not found at all.
  28407. */
  28408. Scene.prototype.getNodeByName = function (name) {
  28409. var mesh = this.getMeshByName(name);
  28410. if (mesh) {
  28411. return mesh;
  28412. }
  28413. var light = this.getLightByName(name);
  28414. if (light) {
  28415. return light;
  28416. }
  28417. var camera = this.getCameraByName(name);
  28418. if (camera) {
  28419. return camera;
  28420. }
  28421. var bone = this.getBoneByName(name);
  28422. return bone;
  28423. };
  28424. /**
  28425. * Gets a mesh using a given name
  28426. * @param name defines the name to search for
  28427. * @return the found mesh or null if not found at all.
  28428. */
  28429. Scene.prototype.getMeshByName = function (name) {
  28430. for (var index = 0; index < this.meshes.length; index++) {
  28431. if (this.meshes[index].name === name) {
  28432. return this.meshes[index];
  28433. }
  28434. }
  28435. return null;
  28436. };
  28437. /**
  28438. * Gets a transform node using a given name
  28439. * @param name defines the name to search for
  28440. * @return the found transform node or null if not found at all.
  28441. */
  28442. Scene.prototype.getTransformNodeByName = function (name) {
  28443. for (var index = 0; index < this.transformNodes.length; index++) {
  28444. if (this.transformNodes[index].name === name) {
  28445. return this.transformNodes[index];
  28446. }
  28447. }
  28448. return null;
  28449. };
  28450. /**
  28451. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  28452. * @param id defines the id to search for
  28453. * @return the found skeleton or null if not found at all.
  28454. */
  28455. Scene.prototype.getLastSkeletonByID = function (id) {
  28456. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  28457. if (this.skeletons[index].id === id) {
  28458. return this.skeletons[index];
  28459. }
  28460. }
  28461. return null;
  28462. };
  28463. /**
  28464. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  28465. * @param id defines the id to search for
  28466. * @return the found skeleton or null if not found at all.
  28467. */
  28468. Scene.prototype.getSkeletonById = function (id) {
  28469. for (var index = 0; index < this.skeletons.length; index++) {
  28470. if (this.skeletons[index].id === id) {
  28471. return this.skeletons[index];
  28472. }
  28473. }
  28474. return null;
  28475. };
  28476. /**
  28477. * Gets a skeleton using a given name
  28478. * @param name defines the name to search for
  28479. * @return the found skeleton or null if not found at all.
  28480. */
  28481. Scene.prototype.getSkeletonByName = function (name) {
  28482. for (var index = 0; index < this.skeletons.length; index++) {
  28483. if (this.skeletons[index].name === name) {
  28484. return this.skeletons[index];
  28485. }
  28486. }
  28487. return null;
  28488. };
  28489. /**
  28490. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  28491. * @param id defines the id to search for
  28492. * @return the found morph target manager or null if not found at all.
  28493. */
  28494. Scene.prototype.getMorphTargetManagerById = function (id) {
  28495. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  28496. if (this.morphTargetManagers[index].uniqueId === id) {
  28497. return this.morphTargetManagers[index];
  28498. }
  28499. }
  28500. return null;
  28501. };
  28502. /**
  28503. * Gets a boolean indicating if the given mesh is active
  28504. * @param mesh defines the mesh to look for
  28505. * @returns true if the mesh is in the active list
  28506. */
  28507. Scene.prototype.isActiveMesh = function (mesh) {
  28508. return (this._activeMeshes.indexOf(mesh) !== -1);
  28509. };
  28510. Object.defineProperty(Scene.prototype, "uid", {
  28511. /**
  28512. * Return a unique id as a string which can serve as an identifier for the scene
  28513. */
  28514. get: function () {
  28515. if (!this._uid) {
  28516. this._uid = BABYLON.Tools.RandomId();
  28517. }
  28518. return this._uid;
  28519. },
  28520. enumerable: true,
  28521. configurable: true
  28522. });
  28523. /**
  28524. * Add an externaly attached data from its key.
  28525. * This method call will fail and return false, if such key already exists.
  28526. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  28527. * @param key the unique key that identifies the data
  28528. * @param data the data object to associate to the key for this Engine instance
  28529. * @return true if no such key were already present and the data was added successfully, false otherwise
  28530. */
  28531. Scene.prototype.addExternalData = function (key, data) {
  28532. if (!this._externalData) {
  28533. this._externalData = new BABYLON.StringDictionary();
  28534. }
  28535. return this._externalData.add(key, data);
  28536. };
  28537. /**
  28538. * Get an externaly attached data from its key
  28539. * @param key the unique key that identifies the data
  28540. * @return the associated data, if present (can be null), or undefined if not present
  28541. */
  28542. Scene.prototype.getExternalData = function (key) {
  28543. if (!this._externalData) {
  28544. return null;
  28545. }
  28546. return this._externalData.get(key);
  28547. };
  28548. /**
  28549. * Get an externaly attached data from its key, create it using a factory if it's not already present
  28550. * @param key the unique key that identifies the data
  28551. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  28552. * @return the associated data, can be null if the factory returned null.
  28553. */
  28554. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  28555. if (!this._externalData) {
  28556. this._externalData = new BABYLON.StringDictionary();
  28557. }
  28558. return this._externalData.getOrAddWithFactory(key, factory);
  28559. };
  28560. /**
  28561. * Remove an externaly attached data from the Engine instance
  28562. * @param key the unique key that identifies the data
  28563. * @return true if the data was successfully removed, false if it doesn't exist
  28564. */
  28565. Scene.prototype.removeExternalData = function (key) {
  28566. return this._externalData.remove(key);
  28567. };
  28568. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  28569. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  28570. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  28571. var step = _a[_i];
  28572. step.action(mesh, subMesh);
  28573. }
  28574. var material = subMesh.getMaterial();
  28575. if (material !== null && material !== undefined) {
  28576. // Render targets
  28577. if (material.hasRenderTargetTextures && material.getRenderTargetTextures !== undefined) {
  28578. if (this._processedMaterials.indexOf(material) === -1) {
  28579. this._processedMaterials.push(material);
  28580. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  28581. }
  28582. }
  28583. // Dispatch
  28584. this._activeIndices.addCount(subMesh.indexCount, false);
  28585. this._renderingManager.dispatch(subMesh, mesh, material);
  28586. }
  28587. }
  28588. };
  28589. /**
  28590. * Clear the processed materials smart array preventing retention point in material dispose.
  28591. */
  28592. Scene.prototype.freeProcessedMaterials = function () {
  28593. this._processedMaterials.dispose();
  28594. };
  28595. /**
  28596. * Clear the active meshes smart array preventing retention point in mesh dispose.
  28597. */
  28598. Scene.prototype.freeActiveMeshes = function () {
  28599. this._activeMeshes.dispose();
  28600. if (this.activeCamera && this.activeCamera._activeMeshes) {
  28601. this.activeCamera._activeMeshes.dispose();
  28602. }
  28603. if (this.activeCameras) {
  28604. for (var i = 0; i < this.activeCameras.length; i++) {
  28605. var activeCamera = this.activeCameras[i];
  28606. if (activeCamera && activeCamera._activeMeshes) {
  28607. activeCamera._activeMeshes.dispose();
  28608. }
  28609. }
  28610. }
  28611. };
  28612. /**
  28613. * Clear the info related to rendering groups preventing retention points during dispose.
  28614. */
  28615. Scene.prototype.freeRenderingGroups = function () {
  28616. if (this._renderingManager) {
  28617. this._renderingManager.freeRenderingGroups();
  28618. }
  28619. if (this.textures) {
  28620. for (var i = 0; i < this.textures.length; i++) {
  28621. var texture = this.textures[i];
  28622. if (texture && texture.renderList) {
  28623. texture.freeRenderingGroups();
  28624. }
  28625. }
  28626. }
  28627. };
  28628. /** @hidden */
  28629. Scene.prototype._isInIntermediateRendering = function () {
  28630. return this._intermediateRendering;
  28631. };
  28632. /**
  28633. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  28634. * @returns the current scene
  28635. */
  28636. Scene.prototype.freezeActiveMeshes = function () {
  28637. if (!this.activeCamera) {
  28638. return this;
  28639. }
  28640. if (!this._frustumPlanes) {
  28641. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  28642. }
  28643. this._evaluateActiveMeshes();
  28644. this._activeMeshesFrozen = true;
  28645. return this;
  28646. };
  28647. /**
  28648. * Use this function to restart evaluating active meshes on every frame
  28649. * @returns the current scene
  28650. */
  28651. Scene.prototype.unfreezeActiveMeshes = function () {
  28652. this._activeMeshesFrozen = false;
  28653. return this;
  28654. };
  28655. Scene.prototype._evaluateActiveMeshes = function () {
  28656. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  28657. return;
  28658. }
  28659. if (!this.activeCamera) {
  28660. return;
  28661. }
  28662. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  28663. this.activeCamera._activeMeshes.reset();
  28664. this._activeMeshes.reset();
  28665. this._renderingManager.reset();
  28666. this._processedMaterials.reset();
  28667. this._activeParticleSystems.reset();
  28668. this._activeSkeletons.reset();
  28669. this._softwareSkinnedMeshes.reset();
  28670. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  28671. var step = _a[_i];
  28672. step.action();
  28673. }
  28674. // Determine mesh candidates
  28675. var meshes = this.getActiveMeshCandidates();
  28676. // Check each mesh
  28677. var len = meshes.length;
  28678. for (var i = 0; i < len; i++) {
  28679. var mesh = meshes.data[i];
  28680. if (mesh.isBlocked) {
  28681. continue;
  28682. }
  28683. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  28684. if (!mesh.isReady() || !mesh.isEnabled()) {
  28685. continue;
  28686. }
  28687. mesh.computeWorldMatrix();
  28688. // Intersections
  28689. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger)) {
  28690. this._meshesForIntersections.pushNoDuplicate(mesh);
  28691. }
  28692. // Switch to current LOD
  28693. var meshLOD = mesh.getLOD(this.activeCamera);
  28694. if (meshLOD === undefined || meshLOD === null) {
  28695. continue;
  28696. }
  28697. mesh._preActivate();
  28698. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  28699. this._activeMeshes.push(mesh);
  28700. this.activeCamera._activeMeshes.push(mesh);
  28701. mesh._activate(this._renderId);
  28702. if (meshLOD !== mesh) {
  28703. meshLOD._activate(this._renderId);
  28704. }
  28705. this._activeMesh(mesh, meshLOD);
  28706. }
  28707. }
  28708. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  28709. // Particle systems
  28710. if (this.particlesEnabled) {
  28711. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  28712. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  28713. var particleSystem = this.particleSystems[particleIndex];
  28714. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  28715. continue;
  28716. }
  28717. var emitter = particleSystem.emitter;
  28718. if (!emitter.position || emitter.isEnabled()) {
  28719. this._activeParticleSystems.push(particleSystem);
  28720. particleSystem.animate();
  28721. this._renderingManager.dispatchParticles(particleSystem);
  28722. }
  28723. }
  28724. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  28725. }
  28726. };
  28727. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  28728. if (this._skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  28729. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  28730. mesh.skeleton.prepare();
  28731. }
  28732. if (!mesh.computeBonesUsingShaders) {
  28733. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  28734. }
  28735. }
  28736. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  28737. var step = _a[_i];
  28738. step.action(sourceMesh, mesh);
  28739. }
  28740. if (mesh !== undefined && mesh !== null
  28741. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  28742. var subMeshes = this.getActiveSubMeshCandidates(mesh);
  28743. var len = subMeshes.length;
  28744. for (var i = 0; i < len; i++) {
  28745. var subMesh = subMeshes.data[i];
  28746. this._evaluateSubMesh(subMesh, mesh);
  28747. }
  28748. }
  28749. };
  28750. /**
  28751. * Update the transform matrix to update from the current active camera
  28752. * @param force defines a boolean used to force the update even if cache is up to date
  28753. */
  28754. Scene.prototype.updateTransformMatrix = function (force) {
  28755. if (!this.activeCamera) {
  28756. return;
  28757. }
  28758. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  28759. };
  28760. /**
  28761. * 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)
  28762. * @param alternateCamera defines the camera to use
  28763. */
  28764. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  28765. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  28766. };
  28767. Scene.prototype._renderForCamera = function (camera, rigParent) {
  28768. if (camera && camera._skipRendering) {
  28769. return;
  28770. }
  28771. var engine = this._engine;
  28772. this.activeCamera = camera;
  28773. if (!this.activeCamera) {
  28774. throw new Error("Active camera not set");
  28775. }
  28776. // Viewport
  28777. engine.setViewport(this.activeCamera.viewport);
  28778. // Camera
  28779. this.resetCachedMaterial();
  28780. this._renderId++;
  28781. this.updateTransformMatrix();
  28782. if (camera._alternateCamera) {
  28783. this.updateAlternateTransformMatrix(camera._alternateCamera);
  28784. this._alternateRendering = true;
  28785. }
  28786. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  28787. // Meshes
  28788. this._evaluateActiveMeshes();
  28789. // Software skinning
  28790. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  28791. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  28792. mesh.applySkeleton(mesh.skeleton);
  28793. }
  28794. // Render targets
  28795. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  28796. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  28797. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  28798. }
  28799. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  28800. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  28801. }
  28802. // Collects render targets from external components.
  28803. for (var _i = 0, _a = this._gatherActiveCameraRenderTargetsStage; _i < _a.length; _i++) {
  28804. var step = _a[_i];
  28805. step.action(this._renderTargets);
  28806. }
  28807. if (this.renderTargetsEnabled) {
  28808. this._intermediateRendering = true;
  28809. if (this._renderTargets.length > 0) {
  28810. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  28811. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  28812. var renderTarget = this._renderTargets.data[renderIndex];
  28813. if (renderTarget._shouldRender()) {
  28814. this._renderId++;
  28815. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  28816. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  28817. }
  28818. }
  28819. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  28820. this._renderId++;
  28821. }
  28822. for (var _b = 0, _c = this._cameraDrawRenderTargetStage; _b < _c.length; _b++) {
  28823. var step = _c[_b];
  28824. step.action(this.activeCamera);
  28825. }
  28826. this._intermediateRendering = false;
  28827. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  28828. }
  28829. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  28830. // Prepare Frame
  28831. if (this.postProcessManager) {
  28832. this.postProcessManager._prepareFrame();
  28833. }
  28834. // Before Camera Draw
  28835. for (var _d = 0, _e = this._beforeCameraDrawStage; _d < _e.length; _d++) {
  28836. var step = _e[_d];
  28837. step.action(this.activeCamera);
  28838. }
  28839. // Render
  28840. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  28841. this._renderingManager.render(null, null, true, true);
  28842. this.onAfterDrawPhaseObservable.notifyObservers(this);
  28843. // After Camera Draw
  28844. for (var _f = 0, _g = this._afterCameraDrawStage; _f < _g.length; _f++) {
  28845. var step = _g[_f];
  28846. step.action(this.activeCamera);
  28847. }
  28848. // Finalize frame
  28849. if (this.postProcessManager) {
  28850. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  28851. }
  28852. // Reset some special arrays
  28853. this._renderTargets.reset();
  28854. this._alternateRendering = false;
  28855. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  28856. };
  28857. Scene.prototype._processSubCameras = function (camera) {
  28858. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  28859. this._renderForCamera(camera);
  28860. return;
  28861. }
  28862. // rig cameras
  28863. for (var index = 0; index < camera._rigCameras.length; index++) {
  28864. this._renderForCamera(camera._rigCameras[index], camera);
  28865. }
  28866. this.activeCamera = camera;
  28867. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  28868. };
  28869. Scene.prototype._checkIntersections = function () {
  28870. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  28871. var sourceMesh = this._meshesForIntersections.data[index];
  28872. if (!sourceMesh.actionManager) {
  28873. continue;
  28874. }
  28875. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  28876. var action = sourceMesh.actionManager.actions[actionIndex];
  28877. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28878. var parameters = action.getTriggerParameter();
  28879. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  28880. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  28881. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  28882. if (areIntersecting && currentIntersectionInProgress === -1) {
  28883. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  28884. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  28885. sourceMesh._intersectionsInProgress.push(otherMesh);
  28886. }
  28887. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28888. sourceMesh._intersectionsInProgress.push(otherMesh);
  28889. }
  28890. }
  28891. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  28892. //They intersected, and now they don't.
  28893. //is this trigger an exit trigger? execute an event.
  28894. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28895. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  28896. }
  28897. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  28898. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  28899. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  28900. return otherMesh === parameterMesh;
  28901. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28902. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  28903. }
  28904. }
  28905. }
  28906. }
  28907. }
  28908. };
  28909. /** @hidden */
  28910. Scene.prototype._advancePhysicsEngineStep = function (step) {
  28911. // Do nothing. Code will be replaced if physics engine component is referenced
  28912. };
  28913. /**
  28914. * Render the scene
  28915. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  28916. */
  28917. Scene.prototype.render = function (updateCameras) {
  28918. if (updateCameras === void 0) { updateCameras = true; }
  28919. if (this.isDisposed) {
  28920. return;
  28921. }
  28922. this._frameId++;
  28923. // Register components that have been associated lately to the scene.
  28924. this._registerTransientComponents();
  28925. this._activeParticles.fetchNewFrame();
  28926. this._totalVertices.fetchNewFrame();
  28927. this._activeIndices.fetchNewFrame();
  28928. this._activeBones.fetchNewFrame();
  28929. this._meshesForIntersections.reset();
  28930. this.resetCachedMaterial();
  28931. this.onBeforeAnimationsObservable.notifyObservers(this);
  28932. // Actions
  28933. if (this.actionManager) {
  28934. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  28935. }
  28936. if (this._engine.isDeterministicLockStep()) {
  28937. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  28938. var defaultFPS = (60.0 / 1000.0);
  28939. var defaultFrameTime = this.getDeterministicFrameTime();
  28940. var stepsTaken = 0;
  28941. var maxSubSteps = this._engine.getLockstepMaxSteps();
  28942. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  28943. internalSteps = Math.min(internalSteps, maxSubSteps);
  28944. do {
  28945. this.onBeforeStepObservable.notifyObservers(this);
  28946. // Animations
  28947. this._animationRatio = defaultFrameTime * defaultFPS;
  28948. this._animate();
  28949. this.onAfterAnimationsObservable.notifyObservers(this);
  28950. // Physics
  28951. this._advancePhysicsEngineStep(defaultFrameTime);
  28952. this.onAfterStepObservable.notifyObservers(this);
  28953. this._currentStepId++;
  28954. stepsTaken++;
  28955. deltaTime -= defaultFrameTime;
  28956. } while (deltaTime > 0 && stepsTaken < internalSteps);
  28957. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  28958. }
  28959. else {
  28960. // Animations
  28961. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  28962. this._animationRatio = deltaTime * (60.0 / 1000.0);
  28963. this._animate();
  28964. this.onAfterAnimationsObservable.notifyObservers(this);
  28965. // Physics
  28966. this._advancePhysicsEngineStep(deltaTime);
  28967. }
  28968. // Before camera update steps
  28969. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  28970. var step = _a[_i];
  28971. step.action();
  28972. }
  28973. // Update Cameras
  28974. if (updateCameras) {
  28975. if (this.activeCameras.length > 0) {
  28976. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28977. var camera = this.activeCameras[cameraIndex];
  28978. camera.update();
  28979. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28980. // rig cameras
  28981. for (var index = 0; index < camera._rigCameras.length; index++) {
  28982. camera._rigCameras[index].update();
  28983. }
  28984. }
  28985. }
  28986. }
  28987. else if (this.activeCamera) {
  28988. this.activeCamera.update();
  28989. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28990. // rig cameras
  28991. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  28992. this.activeCamera._rigCameras[index].update();
  28993. }
  28994. }
  28995. }
  28996. }
  28997. // Before render
  28998. this.onBeforeRenderObservable.notifyObservers(this);
  28999. // Customs render targets
  29000. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  29001. var engine = this.getEngine();
  29002. var currentActiveCamera = this.activeCamera;
  29003. if (this.renderTargetsEnabled) {
  29004. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  29005. this._intermediateRendering = true;
  29006. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  29007. var renderTarget = this.customRenderTargets[customIndex];
  29008. if (renderTarget._shouldRender()) {
  29009. this._renderId++;
  29010. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  29011. if (!this.activeCamera) {
  29012. throw new Error("Active camera not set");
  29013. }
  29014. // Viewport
  29015. engine.setViewport(this.activeCamera.viewport);
  29016. // Camera
  29017. this.updateTransformMatrix();
  29018. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  29019. }
  29020. }
  29021. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  29022. this._intermediateRendering = false;
  29023. this._renderId++;
  29024. }
  29025. // Restore back buffer
  29026. if (this.customRenderTargets.length > 0) {
  29027. engine.restoreDefaultFramebuffer();
  29028. }
  29029. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  29030. this.activeCamera = currentActiveCamera;
  29031. for (var _b = 0, _c = this._beforeClearStage; _b < _c.length; _b++) {
  29032. var step = _c[_b];
  29033. step.action();
  29034. }
  29035. // Clear
  29036. if (this.autoClearDepthAndStencil || this.autoClear) {
  29037. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  29038. }
  29039. // Collects render targets from external components.
  29040. for (var _d = 0, _e = this._gatherRenderTargetsStage; _d < _e.length; _d++) {
  29041. var step = _e[_d];
  29042. step.action(this._renderTargets);
  29043. }
  29044. // Multi-cameras?
  29045. if (this.activeCameras.length > 0) {
  29046. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  29047. if (cameraIndex > 0) {
  29048. this._engine.clear(null, false, true, true);
  29049. }
  29050. this._processSubCameras(this.activeCameras[cameraIndex]);
  29051. }
  29052. }
  29053. else {
  29054. if (!this.activeCamera) {
  29055. throw new Error("No camera defined");
  29056. }
  29057. this._processSubCameras(this.activeCamera);
  29058. }
  29059. // Intersection checks
  29060. this._checkIntersections();
  29061. // Executes the after render stage actions.
  29062. for (var _f = 0, _g = this._afterRenderStage; _f < _g.length; _f++) {
  29063. var step = _g[_f];
  29064. step.action();
  29065. }
  29066. // After render
  29067. if (this.afterRender) {
  29068. this.afterRender();
  29069. }
  29070. this.onAfterRenderObservable.notifyObservers(this);
  29071. // Cleaning
  29072. if (this._toBeDisposed.length) {
  29073. for (var index = 0; index < this._toBeDisposed.length; index++) {
  29074. var data = this._toBeDisposed[index];
  29075. if (data) {
  29076. data.dispose();
  29077. }
  29078. }
  29079. this._toBeDisposed = [];
  29080. }
  29081. if (this.dumpNextRenderTargets) {
  29082. this.dumpNextRenderTargets = false;
  29083. }
  29084. this._activeBones.addCount(0, true);
  29085. this._activeIndices.addCount(0, true);
  29086. this._activeParticles.addCount(0, true);
  29087. };
  29088. /**
  29089. * Freeze all materials
  29090. * A frozen material will not be updatable but should be faster to render
  29091. */
  29092. Scene.prototype.freezeMaterials = function () {
  29093. for (var i = 0; i < this.materials.length; i++) {
  29094. this.materials[i].freeze();
  29095. }
  29096. };
  29097. /**
  29098. * Unfreeze all materials
  29099. * A frozen material will not be updatable but should be faster to render
  29100. */
  29101. Scene.prototype.unfreezeMaterials = function () {
  29102. for (var i = 0; i < this.materials.length; i++) {
  29103. this.materials[i].unfreeze();
  29104. }
  29105. };
  29106. /**
  29107. * Releases all held ressources
  29108. */
  29109. Scene.prototype.dispose = function () {
  29110. this.beforeRender = null;
  29111. this.afterRender = null;
  29112. this.skeletons = [];
  29113. this.morphTargetManagers = [];
  29114. this._transientComponents = [];
  29115. this._isReadyForMeshStage.clear();
  29116. this._beforeEvaluateActiveMeshStage.clear();
  29117. this._evaluateSubMeshStage.clear();
  29118. this._activeMeshStage.clear();
  29119. this._cameraDrawRenderTargetStage.clear();
  29120. this._beforeCameraDrawStage.clear();
  29121. this._beforeRenderingGroupDrawStage.clear();
  29122. this._beforeRenderingMeshStage.clear();
  29123. this._afterRenderingMeshStage.clear();
  29124. this._afterRenderingGroupDrawStage.clear();
  29125. this._afterCameraDrawStage.clear();
  29126. this._afterRenderStage.clear();
  29127. this._beforeCameraUpdateStage.clear();
  29128. this._beforeClearStage.clear();
  29129. this._gatherRenderTargetsStage.clear();
  29130. this._gatherActiveCameraRenderTargetsStage.clear();
  29131. this._pointerMoveStage.clear();
  29132. this._pointerDownStage.clear();
  29133. this._pointerUpStage.clear();
  29134. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  29135. var component = _a[_i];
  29136. component.dispose();
  29137. }
  29138. this.importedMeshesFiles = new Array();
  29139. this.stopAllAnimations();
  29140. this.resetCachedMaterial();
  29141. // Smart arrays
  29142. if (this.activeCamera) {
  29143. this.activeCamera._activeMeshes.dispose();
  29144. this.activeCamera = null;
  29145. }
  29146. this._activeMeshes.dispose();
  29147. this._renderingManager.dispose();
  29148. this._processedMaterials.dispose();
  29149. this._activeParticleSystems.dispose();
  29150. this._activeSkeletons.dispose();
  29151. this._softwareSkinnedMeshes.dispose();
  29152. this._renderTargets.dispose();
  29153. this._registeredForLateAnimationBindings.dispose();
  29154. this._meshesForIntersections.dispose();
  29155. this._toBeDisposed = [];
  29156. // Abort active requests
  29157. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  29158. var request = _c[_b];
  29159. request.abort();
  29160. }
  29161. // Events
  29162. this.onDisposeObservable.notifyObservers(this);
  29163. this.onDisposeObservable.clear();
  29164. this.onBeforeRenderObservable.clear();
  29165. this.onAfterRenderObservable.clear();
  29166. this.onBeforeRenderTargetsRenderObservable.clear();
  29167. this.onAfterRenderTargetsRenderObservable.clear();
  29168. this.onAfterStepObservable.clear();
  29169. this.onBeforeStepObservable.clear();
  29170. this.onBeforeActiveMeshesEvaluationObservable.clear();
  29171. this.onAfterActiveMeshesEvaluationObservable.clear();
  29172. this.onBeforeParticlesRenderingObservable.clear();
  29173. this.onAfterParticlesRenderingObservable.clear();
  29174. this.onBeforeDrawPhaseObservable.clear();
  29175. this.onAfterDrawPhaseObservable.clear();
  29176. this.onBeforeAnimationsObservable.clear();
  29177. this.onAfterAnimationsObservable.clear();
  29178. this.onDataLoadedObservable.clear();
  29179. this.onBeforeRenderingGroupObservable.clear();
  29180. this.onAfterRenderingGroupObservable.clear();
  29181. this.onMeshImportedObservable.clear();
  29182. this.onBeforeCameraRenderObservable.clear();
  29183. this.onAfterCameraRenderObservable.clear();
  29184. this.onReadyObservable.clear();
  29185. this.onNewCameraAddedObservable.clear();
  29186. this.onCameraRemovedObservable.clear();
  29187. this.onNewLightAddedObservable.clear();
  29188. this.onLightRemovedObservable.clear();
  29189. this.onNewGeometryAddedObservable.clear();
  29190. this.onGeometryRemovedObservable.clear();
  29191. this.onNewTransformNodeAddedObservable.clear();
  29192. this.onTransformNodeRemovedObservable.clear();
  29193. this.onNewMeshAddedObservable.clear();
  29194. this.onMeshRemovedObservable.clear();
  29195. this.onNewMaterialAddedObservable.clear();
  29196. this.onMaterialRemovedObservable.clear();
  29197. this.onNewTextureAddedObservable.clear();
  29198. this.onTextureRemovedObservable.clear();
  29199. this.onPrePointerObservable.clear();
  29200. this.onPointerObservable.clear();
  29201. this.onPreKeyboardObservable.clear();
  29202. this.onKeyboardObservable.clear();
  29203. this.detachControl();
  29204. // Detach cameras
  29205. var canvas = this._engine.getRenderingCanvas();
  29206. if (canvas) {
  29207. var index;
  29208. for (index = 0; index < this.cameras.length; index++) {
  29209. this.cameras[index].detachControl(canvas);
  29210. }
  29211. }
  29212. // Release animation groups
  29213. while (this.animationGroups.length) {
  29214. this.animationGroups[0].dispose();
  29215. }
  29216. // Release lights
  29217. while (this.lights.length) {
  29218. this.lights[0].dispose();
  29219. }
  29220. // Release meshes
  29221. while (this.meshes.length) {
  29222. this.meshes[0].dispose(true);
  29223. }
  29224. while (this.transformNodes.length) {
  29225. this.removeTransformNode(this.transformNodes[0]);
  29226. }
  29227. // Release cameras
  29228. while (this.cameras.length) {
  29229. this.cameras[0].dispose();
  29230. }
  29231. // Release materials
  29232. if (this.defaultMaterial) {
  29233. this.defaultMaterial.dispose();
  29234. }
  29235. while (this.multiMaterials.length) {
  29236. this.multiMaterials[0].dispose();
  29237. }
  29238. while (this.materials.length) {
  29239. this.materials[0].dispose();
  29240. }
  29241. // Release particles
  29242. while (this.particleSystems.length) {
  29243. this.particleSystems[0].dispose();
  29244. }
  29245. // Release postProcesses
  29246. while (this.postProcesses.length) {
  29247. this.postProcesses[0].dispose();
  29248. }
  29249. // Release textures
  29250. while (this.textures.length) {
  29251. this.textures[0].dispose();
  29252. }
  29253. // Release UBO
  29254. this._sceneUbo.dispose();
  29255. if (this._alternateSceneUbo) {
  29256. this._alternateSceneUbo.dispose();
  29257. }
  29258. // Post-processes
  29259. this.postProcessManager.dispose();
  29260. // Remove from engine
  29261. index = this._engine.scenes.indexOf(this);
  29262. if (index > -1) {
  29263. this._engine.scenes.splice(index, 1);
  29264. }
  29265. this._engine.wipeCaches(true);
  29266. this._isDisposed = true;
  29267. };
  29268. Object.defineProperty(Scene.prototype, "isDisposed", {
  29269. /**
  29270. * Gets if the scene is already disposed
  29271. */
  29272. get: function () {
  29273. return this._isDisposed;
  29274. },
  29275. enumerable: true,
  29276. configurable: true
  29277. });
  29278. /**
  29279. * Call this function to reduce memory footprint of the scene.
  29280. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  29281. */
  29282. Scene.prototype.clearCachedVertexData = function () {
  29283. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  29284. var mesh = this.meshes[meshIndex];
  29285. var geometry = mesh.geometry;
  29286. if (geometry) {
  29287. geometry._indices = [];
  29288. for (var vbName in geometry._vertexBuffers) {
  29289. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  29290. continue;
  29291. }
  29292. geometry._vertexBuffers[vbName]._buffer._data = null;
  29293. }
  29294. }
  29295. }
  29296. };
  29297. /**
  29298. * This function will remove the local cached buffer data from texture.
  29299. * It will save memory but will prevent the texture from being rebuilt
  29300. */
  29301. Scene.prototype.cleanCachedTextureBuffer = function () {
  29302. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  29303. var baseTexture = _a[_i];
  29304. var buffer = baseTexture._buffer;
  29305. if (buffer) {
  29306. baseTexture._buffer = null;
  29307. }
  29308. }
  29309. };
  29310. /**
  29311. * Get the world extend vectors with an optional filter
  29312. *
  29313. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  29314. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  29315. */
  29316. Scene.prototype.getWorldExtends = function (filterPredicate) {
  29317. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  29318. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  29319. filterPredicate = filterPredicate || (function () { return true; });
  29320. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  29321. mesh.computeWorldMatrix(true);
  29322. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  29323. return;
  29324. }
  29325. var boundingInfo = mesh.getBoundingInfo();
  29326. var minBox = boundingInfo.boundingBox.minimumWorld;
  29327. var maxBox = boundingInfo.boundingBox.maximumWorld;
  29328. BABYLON.Tools.CheckExtends(minBox, min, max);
  29329. BABYLON.Tools.CheckExtends(maxBox, min, max);
  29330. });
  29331. return {
  29332. min: min,
  29333. max: max
  29334. };
  29335. };
  29336. // Picking
  29337. /**
  29338. * Creates a ray that can be used to pick in the scene
  29339. * @param x defines the x coordinate of the origin (on-screen)
  29340. * @param y defines the y coordinate of the origin (on-screen)
  29341. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  29342. * @param camera defines the camera to use for the picking
  29343. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  29344. * @returns a Ray
  29345. */
  29346. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  29347. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  29348. var result = BABYLON.Ray.Zero();
  29349. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  29350. return result;
  29351. };
  29352. /**
  29353. * Creates a ray that can be used to pick in the scene
  29354. * @param x defines the x coordinate of the origin (on-screen)
  29355. * @param y defines the y coordinate of the origin (on-screen)
  29356. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  29357. * @param result defines the ray where to store the picking ray
  29358. * @param camera defines the camera to use for the picking
  29359. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  29360. * @returns the current scene
  29361. */
  29362. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  29363. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  29364. var engine = this._engine;
  29365. if (!camera) {
  29366. if (!this.activeCamera) {
  29367. throw new Error("Active camera not set");
  29368. }
  29369. camera = this.activeCamera;
  29370. }
  29371. var cameraViewport = camera.viewport;
  29372. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  29373. // Moving coordinates to local viewport world
  29374. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  29375. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  29376. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  29377. return this;
  29378. };
  29379. /**
  29380. * Creates a ray that can be used to pick in the scene
  29381. * @param x defines the x coordinate of the origin (on-screen)
  29382. * @param y defines the y coordinate of the origin (on-screen)
  29383. * @param camera defines the camera to use for the picking
  29384. * @returns a Ray
  29385. */
  29386. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  29387. var result = BABYLON.Ray.Zero();
  29388. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  29389. return result;
  29390. };
  29391. /**
  29392. * Creates a ray that can be used to pick in the scene
  29393. * @param x defines the x coordinate of the origin (on-screen)
  29394. * @param y defines the y coordinate of the origin (on-screen)
  29395. * @param result defines the ray where to store the picking ray
  29396. * @param camera defines the camera to use for the picking
  29397. * @returns the current scene
  29398. */
  29399. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  29400. if (!BABYLON.PickingInfo) {
  29401. return this;
  29402. }
  29403. var engine = this._engine;
  29404. if (!camera) {
  29405. if (!this.activeCamera) {
  29406. throw new Error("Active camera not set");
  29407. }
  29408. camera = this.activeCamera;
  29409. }
  29410. var cameraViewport = camera.viewport;
  29411. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  29412. var identity = BABYLON.Matrix.Identity();
  29413. // Moving coordinates to local viewport world
  29414. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  29415. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  29416. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  29417. return this;
  29418. };
  29419. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  29420. if (!BABYLON.PickingInfo) {
  29421. return null;
  29422. }
  29423. var pickingInfo = null;
  29424. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  29425. var mesh = this.meshes[meshIndex];
  29426. if (predicate) {
  29427. if (!predicate(mesh)) {
  29428. continue;
  29429. }
  29430. }
  29431. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  29432. continue;
  29433. }
  29434. var world = mesh.getWorldMatrix();
  29435. var ray = rayFunction(world);
  29436. var result = mesh.intersects(ray, fastCheck);
  29437. if (!result || !result.hit) {
  29438. continue;
  29439. }
  29440. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance) {
  29441. continue;
  29442. }
  29443. pickingInfo = result;
  29444. if (fastCheck) {
  29445. break;
  29446. }
  29447. }
  29448. return pickingInfo || new BABYLON.PickingInfo();
  29449. };
  29450. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  29451. if (!BABYLON.PickingInfo) {
  29452. return null;
  29453. }
  29454. var pickingInfos = new Array();
  29455. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  29456. var mesh = this.meshes[meshIndex];
  29457. if (predicate) {
  29458. if (!predicate(mesh)) {
  29459. continue;
  29460. }
  29461. }
  29462. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  29463. continue;
  29464. }
  29465. var world = mesh.getWorldMatrix();
  29466. var ray = rayFunction(world);
  29467. var result = mesh.intersects(ray, false);
  29468. if (!result || !result.hit) {
  29469. continue;
  29470. }
  29471. pickingInfos.push(result);
  29472. }
  29473. return pickingInfos;
  29474. };
  29475. /** Launch a ray to try to pick a mesh in the scene
  29476. * @param x position on screen
  29477. * @param y position on screen
  29478. * @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
  29479. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  29480. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  29481. * @returns a PickingInfo
  29482. */
  29483. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  29484. var _this = this;
  29485. if (!BABYLON.PickingInfo) {
  29486. return null;
  29487. }
  29488. var result = this._internalPick(function (world) {
  29489. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  29490. return _this._tempPickingRay;
  29491. }, predicate, fastCheck);
  29492. if (result) {
  29493. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  29494. }
  29495. return result;
  29496. };
  29497. /** Use the given ray to pick a mesh in the scene
  29498. * @param ray The ray to use to pick meshes
  29499. * @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
  29500. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  29501. * @returns a PickingInfo
  29502. */
  29503. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  29504. var _this = this;
  29505. var result = this._internalPick(function (world) {
  29506. if (!_this._pickWithRayInverseMatrix) {
  29507. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  29508. }
  29509. world.invertToRef(_this._pickWithRayInverseMatrix);
  29510. if (!_this._cachedRayForTransform) {
  29511. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  29512. }
  29513. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  29514. return _this._cachedRayForTransform;
  29515. }, predicate, fastCheck);
  29516. if (result) {
  29517. result.ray = ray;
  29518. }
  29519. return result;
  29520. };
  29521. /**
  29522. * Launch a ray to try to pick a mesh in the scene
  29523. * @param x X position on screen
  29524. * @param y Y position on screen
  29525. * @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
  29526. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  29527. * @returns an array of PickingInfo
  29528. */
  29529. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  29530. var _this = this;
  29531. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  29532. };
  29533. /**
  29534. * Launch a ray to try to pick a mesh in the scene
  29535. * @param ray Ray to use
  29536. * @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
  29537. * @returns an array of PickingInfo
  29538. */
  29539. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  29540. var _this = this;
  29541. return this._internalMultiPick(function (world) {
  29542. if (!_this._pickWithRayInverseMatrix) {
  29543. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  29544. }
  29545. world.invertToRef(_this._pickWithRayInverseMatrix);
  29546. if (!_this._cachedRayForTransform) {
  29547. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  29548. }
  29549. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  29550. return _this._cachedRayForTransform;
  29551. }, predicate);
  29552. };
  29553. /**
  29554. * Force the value of meshUnderPointer
  29555. * @param mesh defines the mesh to use
  29556. */
  29557. Scene.prototype.setPointerOverMesh = function (mesh) {
  29558. if (this._pointerOverMesh === mesh) {
  29559. return;
  29560. }
  29561. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  29562. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  29563. }
  29564. this._pointerOverMesh = mesh;
  29565. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  29566. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  29567. }
  29568. };
  29569. /**
  29570. * Gets the mesh under the pointer
  29571. * @returns a Mesh or null if no mesh is under the pointer
  29572. */
  29573. Scene.prototype.getPointerOverMesh = function () {
  29574. return this._pointerOverMesh;
  29575. };
  29576. // Misc.
  29577. /** @hidden */
  29578. Scene.prototype._rebuildGeometries = function () {
  29579. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  29580. var geometry = _a[_i];
  29581. geometry._rebuild();
  29582. }
  29583. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  29584. var mesh = _c[_b];
  29585. mesh._rebuild();
  29586. }
  29587. if (this.postProcessManager) {
  29588. this.postProcessManager._rebuild();
  29589. }
  29590. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  29591. var component = _e[_d];
  29592. component.rebuild();
  29593. }
  29594. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  29595. var system = _g[_f];
  29596. system.rebuild();
  29597. }
  29598. };
  29599. /** @hidden */
  29600. Scene.prototype._rebuildTextures = function () {
  29601. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  29602. var texture = _a[_i];
  29603. texture._rebuild();
  29604. }
  29605. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29606. };
  29607. // Tags
  29608. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  29609. if (tagsQuery === undefined) {
  29610. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  29611. return list;
  29612. }
  29613. var listByTags = [];
  29614. forEach = forEach || (function (item) { return; });
  29615. for (var i in list) {
  29616. var item = list[i];
  29617. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  29618. listByTags.push(item);
  29619. forEach(item);
  29620. }
  29621. }
  29622. return listByTags;
  29623. };
  29624. /**
  29625. * Get a list of meshes by tags
  29626. * @param tagsQuery defines the tags query to use
  29627. * @param forEach defines a predicate used to filter results
  29628. * @returns an array of Mesh
  29629. */
  29630. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  29631. return this._getByTags(this.meshes, tagsQuery, forEach);
  29632. };
  29633. /**
  29634. * Get a list of cameras by tags
  29635. * @param tagsQuery defines the tags query to use
  29636. * @param forEach defines a predicate used to filter results
  29637. * @returns an array of Camera
  29638. */
  29639. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  29640. return this._getByTags(this.cameras, tagsQuery, forEach);
  29641. };
  29642. /**
  29643. * Get a list of lights by tags
  29644. * @param tagsQuery defines the tags query to use
  29645. * @param forEach defines a predicate used to filter results
  29646. * @returns an array of Light
  29647. */
  29648. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  29649. return this._getByTags(this.lights, tagsQuery, forEach);
  29650. };
  29651. /**
  29652. * Get a list of materials by tags
  29653. * @param tagsQuery defines the tags query to use
  29654. * @param forEach defines a predicate used to filter results
  29655. * @returns an array of Material
  29656. */
  29657. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  29658. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  29659. };
  29660. /**
  29661. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  29662. * This allowed control for front to back rendering or reversly depending of the special needs.
  29663. *
  29664. * @param renderingGroupId The rendering group id corresponding to its index
  29665. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  29666. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  29667. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  29668. */
  29669. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  29670. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  29671. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  29672. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  29673. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  29674. };
  29675. /**
  29676. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  29677. *
  29678. * @param renderingGroupId The rendering group id corresponding to its index
  29679. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  29680. * @param depth Automatically clears depth between groups if true and autoClear is true.
  29681. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  29682. */
  29683. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  29684. if (depth === void 0) { depth = true; }
  29685. if (stencil === void 0) { stencil = true; }
  29686. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  29687. };
  29688. /**
  29689. * Gets the current auto clear configuration for one rendering group of the rendering
  29690. * manager.
  29691. * @param index the rendering group index to get the information for
  29692. * @returns The auto clear setup for the requested rendering group
  29693. */
  29694. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  29695. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  29696. };
  29697. Object.defineProperty(Scene.prototype, "blockMaterialDirtyMechanism", {
  29698. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  29699. get: function () {
  29700. return this._blockMaterialDirtyMechanism;
  29701. },
  29702. set: function (value) {
  29703. if (this._blockMaterialDirtyMechanism === value) {
  29704. return;
  29705. }
  29706. this._blockMaterialDirtyMechanism = value;
  29707. if (!value) { // Do a complete update
  29708. this.markAllMaterialsAsDirty(BABYLON.Material.AllDirtyFlag);
  29709. }
  29710. },
  29711. enumerable: true,
  29712. configurable: true
  29713. });
  29714. /**
  29715. * Will flag all materials as dirty to trigger new shader compilation
  29716. * @param flag defines the flag used to specify which material part must be marked as dirty
  29717. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  29718. */
  29719. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29720. if (this._blockMaterialDirtyMechanism) {
  29721. return;
  29722. }
  29723. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29724. var material = _a[_i];
  29725. if (predicate && !predicate(material)) {
  29726. continue;
  29727. }
  29728. material.markAsDirty(flag);
  29729. }
  29730. };
  29731. /** @hidden */
  29732. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  29733. var _this = this;
  29734. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  29735. this._activeRequests.push(request);
  29736. request.onCompleteObservable.add(function (request) {
  29737. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29738. });
  29739. return request;
  29740. };
  29741. /** @hidden */
  29742. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  29743. var _this = this;
  29744. return new Promise(function (resolve, reject) {
  29745. _this._loadFile(url, function (data) {
  29746. resolve(data);
  29747. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  29748. reject(exception);
  29749. });
  29750. });
  29751. };
  29752. // Statics
  29753. Scene._uniqueIdCounter = 0;
  29754. /** The fog is deactivated */
  29755. Scene.FOGMODE_NONE = 0;
  29756. /** The fog density is following an exponential function */
  29757. Scene.FOGMODE_EXP = 1;
  29758. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  29759. Scene.FOGMODE_EXP2 = 2;
  29760. /** The fog density is following a linear function. */
  29761. Scene.FOGMODE_LINEAR = 3;
  29762. /**
  29763. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29764. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29765. */
  29766. Scene.MinDeltaTime = 1.0;
  29767. /**
  29768. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29769. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29770. */
  29771. Scene.MaxDeltaTime = 1000.0;
  29772. /** The distance in pixel that you have to move to prevent some events */
  29773. Scene.DragMovementThreshold = 10; // in pixels
  29774. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29775. Scene.LongPressDelay = 500; // in milliseconds
  29776. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29777. Scene.DoubleClickDelay = 300; // in milliseconds
  29778. /** If you need to check double click without raising a single click at first click, enable this flag */
  29779. Scene.ExclusiveDoubleClickMode = false;
  29780. return Scene;
  29781. }(BABYLON.AbstractScene));
  29782. BABYLON.Scene = Scene;
  29783. })(BABYLON || (BABYLON = {}));
  29784. //# sourceMappingURL=babylon.scene.js.map
  29785. var BABYLON;
  29786. (function (BABYLON) {
  29787. /**
  29788. * Set of assets to keep when moving a scene into an asset container.
  29789. */
  29790. var KeepAssets = /** @class */ (function (_super) {
  29791. __extends(KeepAssets, _super);
  29792. function KeepAssets() {
  29793. return _super !== null && _super.apply(this, arguments) || this;
  29794. }
  29795. return KeepAssets;
  29796. }(BABYLON.AbstractScene));
  29797. BABYLON.KeepAssets = KeepAssets;
  29798. /**
  29799. * Container with a set of assets that can be added or removed from a scene.
  29800. */
  29801. var AssetContainer = /** @class */ (function (_super) {
  29802. __extends(AssetContainer, _super);
  29803. /**
  29804. * Instantiates an AssetContainer.
  29805. * @param scene The scene the AssetContainer belongs to.
  29806. */
  29807. function AssetContainer(scene) {
  29808. var _this = _super.call(this) || this;
  29809. _this.scene = scene;
  29810. return _this;
  29811. }
  29812. /**
  29813. * Adds all the assets from the container to the scene.
  29814. */
  29815. AssetContainer.prototype.addAllToScene = function () {
  29816. var _this = this;
  29817. this.cameras.forEach(function (o) {
  29818. _this.scene.addCamera(o);
  29819. });
  29820. this.lights.forEach(function (o) {
  29821. _this.scene.addLight(o);
  29822. });
  29823. this.meshes.forEach(function (o) {
  29824. _this.scene.addMesh(o);
  29825. });
  29826. this.skeletons.forEach(function (o) {
  29827. _this.scene.addSkeleton(o);
  29828. });
  29829. this.animations.forEach(function (o) {
  29830. _this.scene.addAnimation(o);
  29831. });
  29832. this.animationGroups.forEach(function (o) {
  29833. _this.scene.addAnimationGroup(o);
  29834. });
  29835. this.multiMaterials.forEach(function (o) {
  29836. _this.scene.addMultiMaterial(o);
  29837. });
  29838. this.materials.forEach(function (o) {
  29839. _this.scene.addMaterial(o);
  29840. });
  29841. this.morphTargetManagers.forEach(function (o) {
  29842. _this.scene.addMorphTargetManager(o);
  29843. });
  29844. this.geometries.forEach(function (o) {
  29845. _this.scene.addGeometry(o);
  29846. });
  29847. this.transformNodes.forEach(function (o) {
  29848. _this.scene.addTransformNode(o);
  29849. });
  29850. this.actionManagers.forEach(function (o) {
  29851. _this.scene.addActionManager(o);
  29852. });
  29853. this.textures.forEach(function (o) {
  29854. _this.scene.addTexture(o);
  29855. });
  29856. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29857. var component = _a[_i];
  29858. component.addFromContainer(this.scene);
  29859. }
  29860. };
  29861. /**
  29862. * Removes all the assets in the container from the scene
  29863. */
  29864. AssetContainer.prototype.removeAllFromScene = function () {
  29865. var _this = this;
  29866. this.cameras.forEach(function (o) {
  29867. _this.scene.removeCamera(o);
  29868. });
  29869. this.lights.forEach(function (o) {
  29870. _this.scene.removeLight(o);
  29871. });
  29872. this.meshes.forEach(function (o) {
  29873. _this.scene.removeMesh(o);
  29874. });
  29875. this.skeletons.forEach(function (o) {
  29876. _this.scene.removeSkeleton(o);
  29877. });
  29878. this.animations.forEach(function (o) {
  29879. _this.scene.removeAnimation(o);
  29880. });
  29881. this.animationGroups.forEach(function (o) {
  29882. _this.scene.removeAnimationGroup(o);
  29883. });
  29884. this.multiMaterials.forEach(function (o) {
  29885. _this.scene.removeMultiMaterial(o);
  29886. });
  29887. this.materials.forEach(function (o) {
  29888. _this.scene.removeMaterial(o);
  29889. });
  29890. this.morphTargetManagers.forEach(function (o) {
  29891. _this.scene.removeMorphTargetManager(o);
  29892. });
  29893. this.geometries.forEach(function (o) {
  29894. _this.scene.removeGeometry(o);
  29895. });
  29896. this.transformNodes.forEach(function (o) {
  29897. _this.scene.removeTransformNode(o);
  29898. });
  29899. this.actionManagers.forEach(function (o) {
  29900. _this.scene.removeActionManager(o);
  29901. });
  29902. this.textures.forEach(function (o) {
  29903. _this.scene.removeTexture(o);
  29904. });
  29905. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29906. var component = _a[_i];
  29907. component.removeFromContainer(this.scene);
  29908. }
  29909. };
  29910. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29911. if (!sourceAssets) {
  29912. return;
  29913. }
  29914. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29915. var asset = sourceAssets_1[_i];
  29916. var move = true;
  29917. if (keepAssets) {
  29918. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29919. var keepAsset = keepAssets_1[_a];
  29920. if (asset === keepAsset) {
  29921. move = false;
  29922. break;
  29923. }
  29924. }
  29925. }
  29926. if (move) {
  29927. targetAssets.push(asset);
  29928. }
  29929. }
  29930. };
  29931. /**
  29932. * Removes all the assets contained in the scene and adds them to the container.
  29933. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29934. */
  29935. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29936. if (keepAssets === undefined) {
  29937. keepAssets = new KeepAssets();
  29938. }
  29939. for (var key in this) {
  29940. if (this.hasOwnProperty(key)) {
  29941. this[key] = this[key] || [];
  29942. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  29943. }
  29944. }
  29945. this.removeAllFromScene();
  29946. };
  29947. /**
  29948. * 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.
  29949. * @returns the root mesh
  29950. */
  29951. AssetContainer.prototype.createRootMesh = function () {
  29952. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29953. this.meshes.forEach(function (m) {
  29954. if (!m.parent) {
  29955. rootMesh.addChild(m);
  29956. }
  29957. });
  29958. this.meshes.unshift(rootMesh);
  29959. return rootMesh;
  29960. };
  29961. return AssetContainer;
  29962. }(BABYLON.AbstractScene));
  29963. BABYLON.AssetContainer = AssetContainer;
  29964. })(BABYLON || (BABYLON = {}));
  29965. //# sourceMappingURL=babylon.assetContainer.js.map
  29966. var BABYLON;
  29967. (function (BABYLON) {
  29968. /**
  29969. * Class used to store data that will be store in GPU memory
  29970. */
  29971. var Buffer = /** @class */ (function () {
  29972. /**
  29973. * Constructor
  29974. * @param engine the engine
  29975. * @param data the data to use for this buffer
  29976. * @param updatable whether the data is updatable
  29977. * @param stride the stride (optional)
  29978. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29979. * @param instanced whether the buffer is instanced (optional)
  29980. * @param useBytes set to true if the stride in in bytes (optional)
  29981. */
  29982. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29983. if (stride === void 0) { stride = 0; }
  29984. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29985. if (instanced === void 0) { instanced = false; }
  29986. if (useBytes === void 0) { useBytes = false; }
  29987. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29988. this._engine = engine.getScene().getEngine();
  29989. }
  29990. else {
  29991. this._engine = engine;
  29992. }
  29993. this._updatable = updatable;
  29994. this._instanced = instanced;
  29995. this._data = data;
  29996. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29997. if (!postponeInternalCreation) { // by default
  29998. this.create();
  29999. }
  30000. }
  30001. /**
  30002. * Create a new VertexBuffer based on the current buffer
  30003. * @param kind defines the vertex buffer kind (position, normal, etc.)
  30004. * @param offset defines offset in the buffer (0 by default)
  30005. * @param size defines the size in floats of attributes (position is 3 for instance)
  30006. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  30007. * @param instanced defines if the vertex buffer contains indexed data
  30008. * @param useBytes defines if the offset and stride are in bytes
  30009. * @returns the new vertex buffer
  30010. */
  30011. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  30012. if (useBytes === void 0) { useBytes = false; }
  30013. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  30014. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  30015. // a lot of these parameters are ignored as they are overriden by the buffer
  30016. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  30017. };
  30018. // Properties
  30019. /**
  30020. * Gets a boolean indicating if the Buffer is updatable?
  30021. * @returns true if the buffer is updatable
  30022. */
  30023. Buffer.prototype.isUpdatable = function () {
  30024. return this._updatable;
  30025. };
  30026. /**
  30027. * Gets current buffer's data
  30028. * @returns a DataArray or null
  30029. */
  30030. Buffer.prototype.getData = function () {
  30031. return this._data;
  30032. };
  30033. /**
  30034. * Gets underlying native buffer
  30035. * @returns underlying native buffer
  30036. */
  30037. Buffer.prototype.getBuffer = function () {
  30038. return this._buffer;
  30039. };
  30040. /**
  30041. * Gets the stride in float32 units (i.e. byte stride / 4).
  30042. * May not be an integer if the byte stride is not divisible by 4.
  30043. * DEPRECATED. Use byteStride instead.
  30044. * @returns the stride in float32 units
  30045. */
  30046. Buffer.prototype.getStrideSize = function () {
  30047. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  30048. };
  30049. // Methods
  30050. /**
  30051. * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property
  30052. * @param data defines the data to store
  30053. */
  30054. Buffer.prototype.create = function (data) {
  30055. if (data === void 0) { data = null; }
  30056. if (!data && this._buffer) {
  30057. return; // nothing to do
  30058. }
  30059. data = data || this._data;
  30060. if (!data) {
  30061. return;
  30062. }
  30063. if (!this._buffer) { // create buffer
  30064. if (this._updatable) {
  30065. this._buffer = this._engine.createDynamicVertexBuffer(data);
  30066. this._data = data;
  30067. }
  30068. else {
  30069. this._buffer = this._engine.createVertexBuffer(data);
  30070. }
  30071. }
  30072. else if (this._updatable) { // update buffer
  30073. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  30074. this._data = data;
  30075. }
  30076. };
  30077. /** @hidden */
  30078. Buffer.prototype._rebuild = function () {
  30079. this._buffer = null;
  30080. this.create(this._data);
  30081. };
  30082. /**
  30083. * Update current buffer data
  30084. * @param data defines the data to store
  30085. */
  30086. Buffer.prototype.update = function (data) {
  30087. this.create(data);
  30088. };
  30089. /**
  30090. * Updates the data directly.
  30091. * @param data the new data
  30092. * @param offset the new offset
  30093. * @param vertexCount the vertex count (optional)
  30094. * @param useBytes set to true if the offset is in bytes
  30095. */
  30096. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  30097. if (useBytes === void 0) { useBytes = false; }
  30098. if (!this._buffer) {
  30099. return;
  30100. }
  30101. if (this._updatable) { // update buffer
  30102. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  30103. this._data = null;
  30104. }
  30105. };
  30106. /**
  30107. * Release all resources
  30108. */
  30109. Buffer.prototype.dispose = function () {
  30110. if (!this._buffer) {
  30111. return;
  30112. }
  30113. if (this._engine._releaseBuffer(this._buffer)) {
  30114. this._buffer = null;
  30115. }
  30116. };
  30117. return Buffer;
  30118. }());
  30119. BABYLON.Buffer = Buffer;
  30120. })(BABYLON || (BABYLON = {}));
  30121. //# sourceMappingURL=babylon.buffer.js.map
  30122. var BABYLON;
  30123. (function (BABYLON) {
  30124. /**
  30125. * Specialized buffer used to store vertex data
  30126. */
  30127. var VertexBuffer = /** @class */ (function () {
  30128. /**
  30129. * Constructor
  30130. * @param engine the engine
  30131. * @param data the data to use for this vertex buffer
  30132. * @param kind the vertex buffer kind
  30133. * @param updatable whether the data is updatable
  30134. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  30135. * @param stride the stride (optional)
  30136. * @param instanced whether the buffer is instanced (optional)
  30137. * @param offset the offset of the data (optional)
  30138. * @param size the number of components (optional)
  30139. * @param type the type of the component (optional)
  30140. * @param normalized whether the data contains normalized data (optional)
  30141. * @param useBytes set to true if stride and offset are in bytes (optional)
  30142. */
  30143. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  30144. if (normalized === void 0) { normalized = false; }
  30145. if (useBytes === void 0) { useBytes = false; }
  30146. if (data instanceof BABYLON.Buffer) {
  30147. this._buffer = data;
  30148. this._ownsBuffer = false;
  30149. }
  30150. else {
  30151. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  30152. this._ownsBuffer = true;
  30153. }
  30154. this._kind = kind;
  30155. if (type == undefined) {
  30156. var data_1 = this.getData();
  30157. this.type = VertexBuffer.FLOAT;
  30158. if (data_1 instanceof Int8Array) {
  30159. this.type = VertexBuffer.BYTE;
  30160. }
  30161. else if (data_1 instanceof Uint8Array) {
  30162. this.type = VertexBuffer.UNSIGNED_BYTE;
  30163. }
  30164. else if (data_1 instanceof Int16Array) {
  30165. this.type = VertexBuffer.SHORT;
  30166. }
  30167. else if (data_1 instanceof Uint16Array) {
  30168. this.type = VertexBuffer.UNSIGNED_SHORT;
  30169. }
  30170. else if (data_1 instanceof Int32Array) {
  30171. this.type = VertexBuffer.INT;
  30172. }
  30173. else if (data_1 instanceof Uint32Array) {
  30174. this.type = VertexBuffer.UNSIGNED_INT;
  30175. }
  30176. }
  30177. else {
  30178. this.type = type;
  30179. }
  30180. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  30181. if (useBytes) {
  30182. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  30183. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  30184. this.byteOffset = offset || 0;
  30185. }
  30186. else {
  30187. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  30188. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  30189. this.byteOffset = (offset || 0) * typeByteLength;
  30190. }
  30191. this.normalized = normalized;
  30192. this._instanced = instanced !== undefined ? instanced : false;
  30193. this._instanceDivisor = instanced ? 1 : 0;
  30194. }
  30195. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  30196. /**
  30197. * Gets or sets the instance divisor when in instanced mode
  30198. */
  30199. get: function () {
  30200. return this._instanceDivisor;
  30201. },
  30202. set: function (value) {
  30203. this._instanceDivisor = value;
  30204. if (value == 0) {
  30205. this._instanced = false;
  30206. }
  30207. else {
  30208. this._instanced = true;
  30209. }
  30210. },
  30211. enumerable: true,
  30212. configurable: true
  30213. });
  30214. /** @hidden */
  30215. VertexBuffer.prototype._rebuild = function () {
  30216. if (!this._buffer) {
  30217. return;
  30218. }
  30219. this._buffer._rebuild();
  30220. };
  30221. /**
  30222. * Returns the kind of the VertexBuffer (string)
  30223. * @returns a string
  30224. */
  30225. VertexBuffer.prototype.getKind = function () {
  30226. return this._kind;
  30227. };
  30228. // Properties
  30229. /**
  30230. * Gets a boolean indicating if the VertexBuffer is updatable?
  30231. * @returns true if the buffer is updatable
  30232. */
  30233. VertexBuffer.prototype.isUpdatable = function () {
  30234. return this._buffer.isUpdatable();
  30235. };
  30236. /**
  30237. * Gets current buffer's data
  30238. * @returns a DataArray or null
  30239. */
  30240. VertexBuffer.prototype.getData = function () {
  30241. return this._buffer.getData();
  30242. };
  30243. /**
  30244. * Gets underlying native buffer
  30245. * @returns underlying native buffer
  30246. */
  30247. VertexBuffer.prototype.getBuffer = function () {
  30248. return this._buffer.getBuffer();
  30249. };
  30250. /**
  30251. * Gets the stride in float32 units (i.e. byte stride / 4).
  30252. * May not be an integer if the byte stride is not divisible by 4.
  30253. * DEPRECATED. Use byteStride instead.
  30254. * @returns the stride in float32 units
  30255. */
  30256. VertexBuffer.prototype.getStrideSize = function () {
  30257. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  30258. };
  30259. /**
  30260. * Returns the offset as a multiple of the type byte length.
  30261. * DEPRECATED. Use byteOffset instead.
  30262. * @returns the offset in bytes
  30263. */
  30264. VertexBuffer.prototype.getOffset = function () {
  30265. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  30266. };
  30267. /**
  30268. * Returns the number of components per vertex attribute (integer)
  30269. * @returns the size in float
  30270. */
  30271. VertexBuffer.prototype.getSize = function () {
  30272. return this._size;
  30273. };
  30274. /**
  30275. * Gets a boolean indicating is the internal buffer of the VertexBuffer is instanced
  30276. * @returns true if this buffer is instanced
  30277. */
  30278. VertexBuffer.prototype.getIsInstanced = function () {
  30279. return this._instanced;
  30280. };
  30281. /**
  30282. * Returns the instancing divisor, zero for non-instanced (integer).
  30283. * @returns a number
  30284. */
  30285. VertexBuffer.prototype.getInstanceDivisor = function () {
  30286. return this._instanceDivisor;
  30287. };
  30288. // Methods
  30289. /**
  30290. * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property
  30291. * @param data defines the data to store
  30292. */
  30293. VertexBuffer.prototype.create = function (data) {
  30294. this._buffer.create(data);
  30295. };
  30296. /**
  30297. * Updates the underlying buffer according to the passed numeric array or Float32Array.
  30298. * This function will create a new buffer if the current one is not updatable
  30299. * @param data defines the data to store
  30300. */
  30301. VertexBuffer.prototype.update = function (data) {
  30302. this._buffer.update(data);
  30303. };
  30304. /**
  30305. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  30306. * Returns the directly updated WebGLBuffer.
  30307. * @param data the new data
  30308. * @param offset the new offset
  30309. * @param useBytes set to true if the offset is in bytes
  30310. */
  30311. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  30312. if (useBytes === void 0) { useBytes = false; }
  30313. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  30314. };
  30315. /**
  30316. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  30317. */
  30318. VertexBuffer.prototype.dispose = function () {
  30319. if (this._ownsBuffer) {
  30320. this._buffer.dispose();
  30321. }
  30322. };
  30323. /**
  30324. * Enumerates each value of this vertex buffer as numbers.
  30325. * @param count the number of values to enumerate
  30326. * @param callback the callback function called for each value
  30327. */
  30328. VertexBuffer.prototype.forEach = function (count, callback) {
  30329. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  30330. };
  30331. /**
  30332. * Deduces the stride given a kind.
  30333. * @param kind The kind string to deduce
  30334. * @returns The deduced stride
  30335. */
  30336. VertexBuffer.DeduceStride = function (kind) {
  30337. switch (kind) {
  30338. case VertexBuffer.UVKind:
  30339. case VertexBuffer.UV2Kind:
  30340. case VertexBuffer.UV3Kind:
  30341. case VertexBuffer.UV4Kind:
  30342. case VertexBuffer.UV5Kind:
  30343. case VertexBuffer.UV6Kind:
  30344. return 2;
  30345. case VertexBuffer.NormalKind:
  30346. case VertexBuffer.PositionKind:
  30347. return 3;
  30348. case VertexBuffer.ColorKind:
  30349. case VertexBuffer.MatricesIndicesKind:
  30350. case VertexBuffer.MatricesIndicesExtraKind:
  30351. case VertexBuffer.MatricesWeightsKind:
  30352. case VertexBuffer.MatricesWeightsExtraKind:
  30353. case VertexBuffer.TangentKind:
  30354. return 4;
  30355. default:
  30356. throw new Error("Invalid kind '" + kind + "'");
  30357. }
  30358. };
  30359. /**
  30360. * Gets the byte length of the given type.
  30361. * @param type the type
  30362. * @returns the number of bytes
  30363. */
  30364. VertexBuffer.GetTypeByteLength = function (type) {
  30365. switch (type) {
  30366. case VertexBuffer.BYTE:
  30367. case VertexBuffer.UNSIGNED_BYTE:
  30368. return 1;
  30369. case VertexBuffer.SHORT:
  30370. case VertexBuffer.UNSIGNED_SHORT:
  30371. return 2;
  30372. case VertexBuffer.INT:
  30373. case VertexBuffer.FLOAT:
  30374. return 4;
  30375. default:
  30376. throw new Error("Invalid type '" + type + "'");
  30377. }
  30378. };
  30379. /**
  30380. * Enumerates each value of the given parameters as numbers.
  30381. * @param data the data to enumerate
  30382. * @param byteOffset the byte offset of the data
  30383. * @param byteStride the byte stride of the data
  30384. * @param componentCount the number of components per element
  30385. * @param componentType the type of the component
  30386. * @param count the total number of components
  30387. * @param normalized whether the data is normalized
  30388. * @param callback the callback function called for each value
  30389. */
  30390. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  30391. if (data instanceof Array) {
  30392. var offset = byteOffset / 4;
  30393. var stride = byteStride / 4;
  30394. for (var index = 0; index < count; index += componentCount) {
  30395. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30396. callback(data[offset + componentIndex], index + componentIndex);
  30397. }
  30398. offset += stride;
  30399. }
  30400. }
  30401. else {
  30402. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  30403. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  30404. for (var index = 0; index < count; index += componentCount) {
  30405. var componentByteOffset = byteOffset;
  30406. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30407. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  30408. callback(value, index + componentIndex);
  30409. componentByteOffset += componentByteLength;
  30410. }
  30411. byteOffset += byteStride;
  30412. }
  30413. }
  30414. };
  30415. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  30416. switch (type) {
  30417. case VertexBuffer.BYTE: {
  30418. var value = dataView.getInt8(byteOffset);
  30419. if (normalized) {
  30420. value = Math.max(value / 127, -1);
  30421. }
  30422. return value;
  30423. }
  30424. case VertexBuffer.UNSIGNED_BYTE: {
  30425. var value = dataView.getUint8(byteOffset);
  30426. if (normalized) {
  30427. value = value / 255;
  30428. }
  30429. return value;
  30430. }
  30431. case VertexBuffer.SHORT: {
  30432. var value = dataView.getInt16(byteOffset, true);
  30433. if (normalized) {
  30434. value = Math.max(value / 16383, -1);
  30435. }
  30436. return value;
  30437. }
  30438. case VertexBuffer.UNSIGNED_SHORT: {
  30439. var value = dataView.getUint16(byteOffset, true);
  30440. if (normalized) {
  30441. value = value / 65535;
  30442. }
  30443. return value;
  30444. }
  30445. case VertexBuffer.FLOAT: {
  30446. return dataView.getFloat32(byteOffset, true);
  30447. }
  30448. default: {
  30449. throw new Error("Invalid component type " + type);
  30450. }
  30451. }
  30452. };
  30453. /**
  30454. * The byte type.
  30455. */
  30456. VertexBuffer.BYTE = 5120;
  30457. /**
  30458. * The unsigned byte type.
  30459. */
  30460. VertexBuffer.UNSIGNED_BYTE = 5121;
  30461. /**
  30462. * The short type.
  30463. */
  30464. VertexBuffer.SHORT = 5122;
  30465. /**
  30466. * The unsigned short type.
  30467. */
  30468. VertexBuffer.UNSIGNED_SHORT = 5123;
  30469. /**
  30470. * The integer type.
  30471. */
  30472. VertexBuffer.INT = 5124;
  30473. /**
  30474. * The unsigned integer type.
  30475. */
  30476. VertexBuffer.UNSIGNED_INT = 5125;
  30477. /**
  30478. * The float type.
  30479. */
  30480. VertexBuffer.FLOAT = 5126;
  30481. // Enums
  30482. /**
  30483. * Positions
  30484. */
  30485. VertexBuffer.PositionKind = "position";
  30486. /**
  30487. * Normals
  30488. */
  30489. VertexBuffer.NormalKind = "normal";
  30490. /**
  30491. * Tangents
  30492. */
  30493. VertexBuffer.TangentKind = "tangent";
  30494. /**
  30495. * Texture coordinates
  30496. */
  30497. VertexBuffer.UVKind = "uv";
  30498. /**
  30499. * Texture coordinates 2
  30500. */
  30501. VertexBuffer.UV2Kind = "uv2";
  30502. /**
  30503. * Texture coordinates 3
  30504. */
  30505. VertexBuffer.UV3Kind = "uv3";
  30506. /**
  30507. * Texture coordinates 4
  30508. */
  30509. VertexBuffer.UV4Kind = "uv4";
  30510. /**
  30511. * Texture coordinates 5
  30512. */
  30513. VertexBuffer.UV5Kind = "uv5";
  30514. /**
  30515. * Texture coordinates 6
  30516. */
  30517. VertexBuffer.UV6Kind = "uv6";
  30518. /**
  30519. * Colors
  30520. */
  30521. VertexBuffer.ColorKind = "color";
  30522. /**
  30523. * Matrix indices (for bones)
  30524. */
  30525. VertexBuffer.MatricesIndicesKind = "matricesIndices";
  30526. /**
  30527. * Matrix weights (for bones)
  30528. */
  30529. VertexBuffer.MatricesWeightsKind = "matricesWeights";
  30530. /**
  30531. * Additional matrix indices (for bones)
  30532. */
  30533. VertexBuffer.MatricesIndicesExtraKind = "matricesIndicesExtra";
  30534. /**
  30535. * Additional matrix weights (for bones)
  30536. */
  30537. VertexBuffer.MatricesWeightsExtraKind = "matricesWeightsExtra";
  30538. return VertexBuffer;
  30539. }());
  30540. BABYLON.VertexBuffer = VertexBuffer;
  30541. })(BABYLON || (BABYLON = {}));
  30542. //# sourceMappingURL=babylon.vertexBuffer.js.map
  30543. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  30544. var BABYLON;
  30545. (function (BABYLON) {
  30546. /**
  30547. * Internal class used by the engine to get list of InternalTexture already bound to the GL context
  30548. */
  30549. var DummyInternalTextureTracker = /** @class */ (function () {
  30550. function DummyInternalTextureTracker() {
  30551. /**
  30552. * Gets or set the previous tracker in the list
  30553. */
  30554. this.previous = null;
  30555. /**
  30556. * Gets or set the next tracker in the list
  30557. */
  30558. this.next = null;
  30559. }
  30560. return DummyInternalTextureTracker;
  30561. }());
  30562. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  30563. })(BABYLON || (BABYLON = {}));
  30564. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  30565. var BABYLON;
  30566. (function (BABYLON) {
  30567. /**
  30568. * Class used to store data associated with WebGL texture data for the engine
  30569. * This class should not be used directly
  30570. */
  30571. var InternalTexture = /** @class */ (function () {
  30572. /**
  30573. * Creates a new InternalTexture
  30574. * @param engine defines the engine to use
  30575. * @param dataSource defines the type of data that will be used
  30576. */
  30577. function InternalTexture(engine, dataSource) {
  30578. /**
  30579. * Observable called when the texture is loaded
  30580. */
  30581. this.onLoadedObservable = new BABYLON.Observable();
  30582. /**
  30583. * Gets or set the previous tracker in the list
  30584. */
  30585. this.previous = null;
  30586. /**
  30587. * Gets or set the next tracker in the list
  30588. */
  30589. this.next = null;
  30590. // Private
  30591. /** @hidden */
  30592. this._initialSlot = -1;
  30593. /** @hidden */
  30594. this._designatedSlot = -1;
  30595. /** @hidden */
  30596. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  30597. /** @hidden */
  30598. this._comparisonFunction = 0;
  30599. /** @hidden */
  30600. this._sphericalPolynomial = null;
  30601. /** @hidden */
  30602. this._lodGenerationScale = 0;
  30603. /** @hidden */
  30604. this._lodGenerationOffset = 0;
  30605. /** @hidden */
  30606. this._isRGBD = false;
  30607. /** @hidden */
  30608. this._references = 1;
  30609. this._engine = engine;
  30610. this._dataSource = dataSource;
  30611. this._webGLTexture = engine._createTexture();
  30612. }
  30613. /**
  30614. * Gets the Engine the texture belongs to.
  30615. * @returns The babylon engine
  30616. */
  30617. InternalTexture.prototype.getEngine = function () {
  30618. return this._engine;
  30619. };
  30620. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  30621. /**
  30622. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30623. */
  30624. get: function () {
  30625. return this._dataSource;
  30626. },
  30627. enumerable: true,
  30628. configurable: true
  30629. });
  30630. /**
  30631. * Increments the number of references (ie. the number of Texture that point to it)
  30632. */
  30633. InternalTexture.prototype.incrementReferences = function () {
  30634. this._references++;
  30635. };
  30636. /**
  30637. * Change the size of the texture (not the size of the content)
  30638. * @param width defines the new width
  30639. * @param height defines the new height
  30640. * @param depth defines the new depth (1 by default)
  30641. */
  30642. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30643. if (depth === void 0) { depth = 1; }
  30644. this.width = width;
  30645. this.height = height;
  30646. this.depth = depth;
  30647. this.baseWidth = width;
  30648. this.baseHeight = height;
  30649. this.baseDepth = depth;
  30650. this._size = width * height * depth;
  30651. };
  30652. /** @hidden */
  30653. InternalTexture.prototype._rebuild = function () {
  30654. var _this = this;
  30655. var proxy;
  30656. this.isReady = false;
  30657. this._cachedCoordinatesMode = null;
  30658. this._cachedWrapU = null;
  30659. this._cachedWrapV = null;
  30660. this._cachedAnisotropicFilteringLevel = null;
  30661. switch (this._dataSource) {
  30662. case InternalTexture.DATASOURCE_TEMP:
  30663. return;
  30664. case InternalTexture.DATASOURCE_URL:
  30665. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30666. _this.isReady = true;
  30667. }, null, this._buffer, undefined, this.format);
  30668. proxy._swapAndDie(this);
  30669. return;
  30670. case InternalTexture.DATASOURCE_RAW:
  30671. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30672. proxy._swapAndDie(this);
  30673. this.isReady = true;
  30674. return;
  30675. case InternalTexture.DATASOURCE_RAW3D:
  30676. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30677. proxy._swapAndDie(this);
  30678. this.isReady = true;
  30679. return;
  30680. case InternalTexture.DATASOURCE_DYNAMIC:
  30681. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30682. proxy._swapAndDie(this);
  30683. // The engine will make sure to update content so no need to flag it as isReady = true
  30684. return;
  30685. case InternalTexture.DATASOURCE_RENDERTARGET:
  30686. var options = new BABYLON.RenderTargetCreationOptions();
  30687. options.generateDepthBuffer = this._generateDepthBuffer;
  30688. options.generateMipMaps = this.generateMipMaps;
  30689. options.generateStencilBuffer = this._generateStencilBuffer;
  30690. options.samplingMode = this.samplingMode;
  30691. options.type = this.type;
  30692. if (this.isCube) {
  30693. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30694. }
  30695. else {
  30696. var size = {
  30697. width: this.width,
  30698. height: this.height
  30699. };
  30700. proxy = this._engine.createRenderTargetTexture(size, options);
  30701. }
  30702. proxy._swapAndDie(this);
  30703. this.isReady = true;
  30704. return;
  30705. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30706. var depthTextureOptions = {
  30707. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30708. comparisonFunction: this._comparisonFunction,
  30709. generateStencil: this._generateStencilBuffer,
  30710. isCube: this.isCube
  30711. };
  30712. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30713. proxy._swapAndDie(this);
  30714. this.isReady = true;
  30715. return;
  30716. case InternalTexture.DATASOURCE_CUBE:
  30717. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30718. _this.isReady = true;
  30719. }, null, this.format, this._extension);
  30720. proxy._swapAndDie(this);
  30721. return;
  30722. case InternalTexture.DATASOURCE_CUBERAW:
  30723. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30724. proxy._swapAndDie(this);
  30725. this.isReady = true;
  30726. return;
  30727. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  30728. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30729. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  30730. _this.isReady = true;
  30731. });
  30732. proxy._swapAndDie(this);
  30733. return;
  30734. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30735. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30736. if (proxy) {
  30737. proxy._swapAndDie(_this);
  30738. }
  30739. _this.isReady = true;
  30740. }, null, this.format, this._extension);
  30741. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30742. return;
  30743. }
  30744. };
  30745. /** @hidden */
  30746. InternalTexture.prototype._swapAndDie = function (target) {
  30747. target._webGLTexture = this._webGLTexture;
  30748. if (this._framebuffer) {
  30749. target._framebuffer = this._framebuffer;
  30750. }
  30751. if (this._depthStencilBuffer) {
  30752. target._depthStencilBuffer = this._depthStencilBuffer;
  30753. }
  30754. if (this._lodTextureHigh) {
  30755. if (target._lodTextureHigh) {
  30756. target._lodTextureHigh.dispose();
  30757. }
  30758. target._lodTextureHigh = this._lodTextureHigh;
  30759. }
  30760. if (this._lodTextureMid) {
  30761. if (target._lodTextureMid) {
  30762. target._lodTextureMid.dispose();
  30763. }
  30764. target._lodTextureMid = this._lodTextureMid;
  30765. }
  30766. if (this._lodTextureLow) {
  30767. if (target._lodTextureLow) {
  30768. target._lodTextureLow.dispose();
  30769. }
  30770. target._lodTextureLow = this._lodTextureLow;
  30771. }
  30772. var cache = this._engine.getLoadedTexturesCache();
  30773. var index = cache.indexOf(this);
  30774. if (index !== -1) {
  30775. cache.splice(index, 1);
  30776. }
  30777. };
  30778. /**
  30779. * Dispose the current allocated resources
  30780. */
  30781. InternalTexture.prototype.dispose = function () {
  30782. if (!this._webGLTexture) {
  30783. return;
  30784. }
  30785. this._references--;
  30786. if (this._references === 0) {
  30787. this._engine._releaseTexture(this);
  30788. this._webGLTexture = null;
  30789. this.previous = null;
  30790. this.next = null;
  30791. }
  30792. };
  30793. /**
  30794. * The source of the texture data is unknown
  30795. */
  30796. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30797. /**
  30798. * Texture data comes from an URL
  30799. */
  30800. InternalTexture.DATASOURCE_URL = 1;
  30801. /**
  30802. * Texture data is only used for temporary storage
  30803. */
  30804. InternalTexture.DATASOURCE_TEMP = 2;
  30805. /**
  30806. * Texture data comes from raw data (ArrayBuffer)
  30807. */
  30808. InternalTexture.DATASOURCE_RAW = 3;
  30809. /**
  30810. * Texture content is dynamic (video or dynamic texture)
  30811. */
  30812. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30813. /**
  30814. * Texture content is generated by rendering to it
  30815. */
  30816. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30817. /**
  30818. * Texture content is part of a multi render target process
  30819. */
  30820. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30821. /**
  30822. * Texture data comes from a cube data file
  30823. */
  30824. InternalTexture.DATASOURCE_CUBE = 7;
  30825. /**
  30826. * Texture data comes from a raw cube data
  30827. */
  30828. InternalTexture.DATASOURCE_CUBERAW = 8;
  30829. /**
  30830. * Texture data come from a prefiltered cube data file
  30831. */
  30832. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30833. /**
  30834. * Texture content is raw 3D data
  30835. */
  30836. InternalTexture.DATASOURCE_RAW3D = 10;
  30837. /**
  30838. * Texture content is a depth texture
  30839. */
  30840. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30841. /**
  30842. * Texture data comes from a raw cube data encoded with RGBD
  30843. */
  30844. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  30845. return InternalTexture;
  30846. }());
  30847. BABYLON.InternalTexture = InternalTexture;
  30848. })(BABYLON || (BABYLON = {}));
  30849. //# sourceMappingURL=babylon.internalTexture.js.map
  30850. var BABYLON;
  30851. (function (BABYLON) {
  30852. /**
  30853. * Base class of all the textures in babylon.
  30854. * It groups all the common properties the materials, post process, lights... might need
  30855. * in order to make a correct use of the texture.
  30856. */
  30857. var BaseTexture = /** @class */ (function () {
  30858. /**
  30859. * Instantiates a new BaseTexture.
  30860. * Base class of all the textures in babylon.
  30861. * It groups all the common properties the materials, post process, lights... might need
  30862. * in order to make a correct use of the texture.
  30863. * @param scene Define the scene the texture blongs to
  30864. */
  30865. function BaseTexture(scene) {
  30866. this._hasAlpha = false;
  30867. /**
  30868. * Defines if the alpha value should be determined via the rgb values.
  30869. * If true the luminance of the pixel might be used to find the corresponding alpha value.
  30870. */
  30871. this.getAlphaFromRGB = false;
  30872. /**
  30873. * Intensity or strength of the texture.
  30874. * It is commonly used by materials to fine tune the intensity of the texture
  30875. */
  30876. this.level = 1;
  30877. /**
  30878. * Define the UV chanel to use starting from 0 and defaulting to 0.
  30879. * This is part of the texture as textures usually maps to one uv set.
  30880. */
  30881. this.coordinatesIndex = 0;
  30882. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30883. /**
  30884. * | Value | Type | Description |
  30885. * | ----- | ------------------ | ----------- |
  30886. * | 0 | CLAMP_ADDRESSMODE | |
  30887. * | 1 | WRAP_ADDRESSMODE | |
  30888. * | 2 | MIRROR_ADDRESSMODE | |
  30889. */
  30890. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30891. /**
  30892. * | Value | Type | Description |
  30893. * | ----- | ------------------ | ----------- |
  30894. * | 0 | CLAMP_ADDRESSMODE | |
  30895. * | 1 | WRAP_ADDRESSMODE | |
  30896. * | 2 | MIRROR_ADDRESSMODE | |
  30897. */
  30898. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30899. /**
  30900. * | Value | Type | Description |
  30901. * | ----- | ------------------ | ----------- |
  30902. * | 0 | CLAMP_ADDRESSMODE | |
  30903. * | 1 | WRAP_ADDRESSMODE | |
  30904. * | 2 | MIRROR_ADDRESSMODE | |
  30905. */
  30906. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30907. /**
  30908. * With compliant hardware and browser (supporting anisotropic filtering)
  30909. * this defines the level of anisotropic filtering in the texture.
  30910. * The higher the better but the slower. This defaults to 4 as it seems to be the best tradeoff.
  30911. */
  30912. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30913. /**
  30914. * Define if the texture is a cube texture or if false a 2d texture.
  30915. */
  30916. this.isCube = false;
  30917. /**
  30918. * Define if the texture is a 3d texture (webgl 2) or if false a 2d texture.
  30919. */
  30920. this.is3D = false;
  30921. /**
  30922. * Define if the texture contains data in gamma space (most of the png/jpg aside bump).
  30923. * HDR texture are usually stored in linear space.
  30924. * This only impacts the PBR and Background materials
  30925. */
  30926. this.gammaSpace = true;
  30927. /**
  30928. * Is Z inverted in the texture (useful in a cube texture).
  30929. */
  30930. this.invertZ = false;
  30931. /**
  30932. * @hidden
  30933. */
  30934. this.lodLevelInAlpha = false;
  30935. /**
  30936. * Define if the texture is a render target.
  30937. */
  30938. this.isRenderTarget = false;
  30939. /**
  30940. * Define the list of animation attached to the texture.
  30941. */
  30942. this.animations = new Array();
  30943. /**
  30944. * An event triggered when the texture is disposed.
  30945. */
  30946. this.onDisposeObservable = new BABYLON.Observable();
  30947. /**
  30948. * Define the current state of the loading sequence when in delayed load mode.
  30949. */
  30950. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30951. this._cachedSize = BABYLON.Size.Zero();
  30952. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30953. if (this._scene) {
  30954. this._scene.textures.push(this);
  30955. this._scene.onNewTextureAddedObservable.notifyObservers(this);
  30956. }
  30957. this._uid = null;
  30958. }
  30959. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30960. get: function () {
  30961. return this._hasAlpha;
  30962. },
  30963. /**
  30964. * Define if the texture is having a usable alpha value (can be use for transparency or glossiness for instance).
  30965. */
  30966. set: function (value) {
  30967. if (this._hasAlpha === value) {
  30968. return;
  30969. }
  30970. this._hasAlpha = value;
  30971. if (this._scene) {
  30972. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30973. }
  30974. },
  30975. enumerable: true,
  30976. configurable: true
  30977. });
  30978. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30979. get: function () {
  30980. return this._coordinatesMode;
  30981. },
  30982. /**
  30983. * How a texture is mapped.
  30984. *
  30985. * | Value | Type | Description |
  30986. * | ----- | ----------------------------------- | ----------- |
  30987. * | 0 | EXPLICIT_MODE | |
  30988. * | 1 | SPHERICAL_MODE | |
  30989. * | 2 | PLANAR_MODE | |
  30990. * | 3 | CUBIC_MODE | |
  30991. * | 4 | PROJECTION_MODE | |
  30992. * | 5 | SKYBOX_MODE | |
  30993. * | 6 | INVCUBIC_MODE | |
  30994. * | 7 | EQUIRECTANGULAR_MODE | |
  30995. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30996. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30997. */
  30998. set: function (value) {
  30999. if (this._coordinatesMode === value) {
  31000. return;
  31001. }
  31002. this._coordinatesMode = value;
  31003. if (this._scene) {
  31004. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31005. }
  31006. },
  31007. enumerable: true,
  31008. configurable: true
  31009. });
  31010. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  31011. /**
  31012. * Gets whether or not the texture contains RGBD data.
  31013. */
  31014. get: function () {
  31015. return this._texture != null && this._texture._isRGBD;
  31016. },
  31017. enumerable: true,
  31018. configurable: true
  31019. });
  31020. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  31021. /**
  31022. * With prefiltered texture, defined the offset used during the prefiltering steps.
  31023. */
  31024. get: function () {
  31025. if (this._texture) {
  31026. return this._texture._lodGenerationOffset;
  31027. }
  31028. return 0.0;
  31029. },
  31030. set: function (value) {
  31031. if (this._texture) {
  31032. this._texture._lodGenerationOffset = value;
  31033. }
  31034. },
  31035. enumerable: true,
  31036. configurable: true
  31037. });
  31038. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  31039. /**
  31040. * With prefiltered texture, defined the scale used during the prefiltering steps.
  31041. */
  31042. get: function () {
  31043. if (this._texture) {
  31044. return this._texture._lodGenerationScale;
  31045. }
  31046. return 0.0;
  31047. },
  31048. set: function (value) {
  31049. if (this._texture) {
  31050. this._texture._lodGenerationScale = value;
  31051. }
  31052. },
  31053. enumerable: true,
  31054. configurable: true
  31055. });
  31056. Object.defineProperty(BaseTexture.prototype, "uid", {
  31057. /**
  31058. * Define the unique id of the texture in the scene.
  31059. */
  31060. get: function () {
  31061. if (!this._uid) {
  31062. this._uid = BABYLON.Tools.RandomId();
  31063. }
  31064. return this._uid;
  31065. },
  31066. enumerable: true,
  31067. configurable: true
  31068. });
  31069. /**
  31070. * Return a string representation of the texture.
  31071. * @returns the texture as a string
  31072. */
  31073. BaseTexture.prototype.toString = function () {
  31074. return this.name;
  31075. };
  31076. /**
  31077. * Get the class name of the texture.
  31078. * @returns "BaseTexture"
  31079. */
  31080. BaseTexture.prototype.getClassName = function () {
  31081. return "BaseTexture";
  31082. };
  31083. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  31084. /**
  31085. * Callback triggered when the texture has been disposed.
  31086. * Kept for back compatibility, you can use the onDisposeObservable instead.
  31087. */
  31088. set: function (callback) {
  31089. if (this._onDisposeObserver) {
  31090. this.onDisposeObservable.remove(this._onDisposeObserver);
  31091. }
  31092. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31093. },
  31094. enumerable: true,
  31095. configurable: true
  31096. });
  31097. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  31098. /**
  31099. * Define if the texture is preventinga material to render or not.
  31100. * If not and the texture is not ready, the engine will use a default black texture instead.
  31101. */
  31102. get: function () {
  31103. return true;
  31104. },
  31105. enumerable: true,
  31106. configurable: true
  31107. });
  31108. /**
  31109. * Get the scene the texture belongs to.
  31110. * @returns the scene or null if undefined
  31111. */
  31112. BaseTexture.prototype.getScene = function () {
  31113. return this._scene;
  31114. };
  31115. /**
  31116. * Get the texture transform matrix used to offset tile the texture for istance.
  31117. * @returns the transformation matrix
  31118. */
  31119. BaseTexture.prototype.getTextureMatrix = function () {
  31120. return BABYLON.Matrix.IdentityReadOnly;
  31121. };
  31122. /**
  31123. * Get the texture reflection matrix used to rotate/transform the reflection.
  31124. * @returns the reflection matrix
  31125. */
  31126. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  31127. return BABYLON.Matrix.IdentityReadOnly;
  31128. };
  31129. /**
  31130. * Get the underlying lower level texture from Babylon.
  31131. * @returns the insternal texture
  31132. */
  31133. BaseTexture.prototype.getInternalTexture = function () {
  31134. return this._texture;
  31135. };
  31136. /**
  31137. * Get if the texture is ready to be consumed (either it is ready or it is not blocking)
  31138. * @returns true if ready or not blocking
  31139. */
  31140. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  31141. return !this.isBlocking || this.isReady();
  31142. };
  31143. /**
  31144. * Get if the texture is ready to be used (downloaded, converted, mip mapped...).
  31145. * @returns true if fully ready
  31146. */
  31147. BaseTexture.prototype.isReady = function () {
  31148. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31149. this.delayLoad();
  31150. return false;
  31151. }
  31152. if (this._texture) {
  31153. return this._texture.isReady;
  31154. }
  31155. return false;
  31156. };
  31157. /**
  31158. * Get the size of the texture.
  31159. * @returns the texture size.
  31160. */
  31161. BaseTexture.prototype.getSize = function () {
  31162. if (this._texture) {
  31163. if (this._texture.width) {
  31164. this._cachedSize.width = this._texture.width;
  31165. this._cachedSize.height = this._texture.height;
  31166. return this._cachedSize;
  31167. }
  31168. if (this._texture._size) {
  31169. this._cachedSize.width = this._texture._size;
  31170. this._cachedSize.height = this._texture._size;
  31171. return this._cachedSize;
  31172. }
  31173. }
  31174. return this._cachedSize;
  31175. };
  31176. /**
  31177. * Get the base size of the texture.
  31178. * It can be different from the size if the texture has been resized for POT for instance
  31179. * @returns the base size
  31180. */
  31181. BaseTexture.prototype.getBaseSize = function () {
  31182. if (!this.isReady() || !this._texture) {
  31183. return BABYLON.Size.Zero();
  31184. }
  31185. if (this._texture._size) {
  31186. return new BABYLON.Size(this._texture._size, this._texture._size);
  31187. }
  31188. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  31189. };
  31190. /**
  31191. * Scales the texture if is `canRescale()`
  31192. * @param ratio the resize factor we want to use to rescale
  31193. */
  31194. BaseTexture.prototype.scale = function (ratio) {
  31195. };
  31196. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  31197. /**
  31198. * Get if the texture can rescale.
  31199. */
  31200. get: function () {
  31201. return false;
  31202. },
  31203. enumerable: true,
  31204. configurable: true
  31205. });
  31206. /** @hidden */
  31207. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  31208. if (!this._scene) {
  31209. return null;
  31210. }
  31211. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  31212. for (var index = 0; index < texturesCache.length; index++) {
  31213. var texturesCacheEntry = texturesCache[index];
  31214. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  31215. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  31216. texturesCacheEntry.incrementReferences();
  31217. return texturesCacheEntry;
  31218. }
  31219. }
  31220. }
  31221. return null;
  31222. };
  31223. /** @hidden */
  31224. BaseTexture.prototype._rebuild = function () {
  31225. };
  31226. /**
  31227. * Triggers the load sequence in delayed load mode.
  31228. */
  31229. BaseTexture.prototype.delayLoad = function () {
  31230. };
  31231. /**
  31232. * Clones the texture.
  31233. * @returns the cloned texture
  31234. */
  31235. BaseTexture.prototype.clone = function () {
  31236. return null;
  31237. };
  31238. Object.defineProperty(BaseTexture.prototype, "textureType", {
  31239. /**
  31240. * Get the texture underlying type (INT, FLOAT...)
  31241. */
  31242. get: function () {
  31243. if (!this._texture) {
  31244. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  31245. }
  31246. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  31247. },
  31248. enumerable: true,
  31249. configurable: true
  31250. });
  31251. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  31252. /**
  31253. * Get the texture underlying format (RGB, RGBA...)
  31254. */
  31255. get: function () {
  31256. if (!this._texture) {
  31257. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  31258. }
  31259. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  31260. },
  31261. enumerable: true,
  31262. configurable: true
  31263. });
  31264. /**
  31265. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  31266. * This will returns an RGBA array buffer containing either in values (0-255) or
  31267. * float values (0-1) depending of the underlying buffer type.
  31268. * @param faceIndex defines the face of the texture to read (in case of cube texture)
  31269. * @param level defines the LOD level of the texture to read (in case of Mip Maps)
  31270. * @param buffer defines a user defined buffer to fill with data (can be null)
  31271. * @returns The Array buffer containing the pixels data.
  31272. */
  31273. BaseTexture.prototype.readPixels = function (faceIndex, level, buffer) {
  31274. if (faceIndex === void 0) { faceIndex = 0; }
  31275. if (level === void 0) { level = 0; }
  31276. if (buffer === void 0) { buffer = null; }
  31277. if (!this._texture) {
  31278. return null;
  31279. }
  31280. var size = this.getSize();
  31281. var width = size.width;
  31282. var height = size.height;
  31283. var scene = this.getScene();
  31284. if (!scene) {
  31285. return null;
  31286. }
  31287. var engine = scene.getEngine();
  31288. if (level != 0) {
  31289. width = width / Math.pow(2, level);
  31290. height = height / Math.pow(2, level);
  31291. width = Math.round(width);
  31292. height = Math.round(height);
  31293. }
  31294. if (this._texture.isCube) {
  31295. return engine._readTexturePixels(this._texture, width, height, faceIndex, level, buffer);
  31296. }
  31297. return engine._readTexturePixels(this._texture, width, height, -1, level, buffer);
  31298. };
  31299. /**
  31300. * Release and destroy the underlying lower level texture aka internalTexture.
  31301. */
  31302. BaseTexture.prototype.releaseInternalTexture = function () {
  31303. if (this._texture) {
  31304. this._texture.dispose();
  31305. this._texture = null;
  31306. }
  31307. };
  31308. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  31309. /**
  31310. * Get the polynomial representation of the texture data.
  31311. * This is mainly use as a fast way to recover IBL Diffuse irradiance data.
  31312. * @see https://learnopengl.com/PBR/IBL/Diffuse-irradiance
  31313. */
  31314. get: function () {
  31315. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  31316. return null;
  31317. }
  31318. if (!this._texture._sphericalPolynomial) {
  31319. this._texture._sphericalPolynomial =
  31320. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  31321. }
  31322. return this._texture._sphericalPolynomial;
  31323. },
  31324. set: function (value) {
  31325. if (this._texture) {
  31326. this._texture._sphericalPolynomial = value;
  31327. }
  31328. },
  31329. enumerable: true,
  31330. configurable: true
  31331. });
  31332. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  31333. /** @hidden */
  31334. get: function () {
  31335. if (this._texture) {
  31336. return this._texture._lodTextureHigh;
  31337. }
  31338. return null;
  31339. },
  31340. enumerable: true,
  31341. configurable: true
  31342. });
  31343. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  31344. /** @hidden */
  31345. get: function () {
  31346. if (this._texture) {
  31347. return this._texture._lodTextureMid;
  31348. }
  31349. return null;
  31350. },
  31351. enumerable: true,
  31352. configurable: true
  31353. });
  31354. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  31355. /** @hidden */
  31356. get: function () {
  31357. if (this._texture) {
  31358. return this._texture._lodTextureLow;
  31359. }
  31360. return null;
  31361. },
  31362. enumerable: true,
  31363. configurable: true
  31364. });
  31365. /**
  31366. * Dispose the texture and release its associated resources.
  31367. */
  31368. BaseTexture.prototype.dispose = function () {
  31369. if (!this._scene) {
  31370. return;
  31371. }
  31372. // Animations
  31373. this._scene.stopAnimation(this);
  31374. // Remove from scene
  31375. this._scene._removePendingData(this);
  31376. var index = this._scene.textures.indexOf(this);
  31377. if (index >= 0) {
  31378. this._scene.textures.splice(index, 1);
  31379. }
  31380. this._scene.onTextureRemovedObservable.notifyObservers(this);
  31381. if (this._texture === undefined) {
  31382. return;
  31383. }
  31384. // Release
  31385. this.releaseInternalTexture();
  31386. // Callback
  31387. this.onDisposeObservable.notifyObservers(this);
  31388. this.onDisposeObservable.clear();
  31389. };
  31390. /**
  31391. * Serialize the texture into a JSON representation that can be parsed later on.
  31392. * @returns the JSON representation of the texture
  31393. */
  31394. BaseTexture.prototype.serialize = function () {
  31395. if (!this.name) {
  31396. return null;
  31397. }
  31398. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  31399. // Animations
  31400. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  31401. return serializationObject;
  31402. };
  31403. /**
  31404. * Helper function to be called back once a list of texture contains only ready textures.
  31405. * @param textures Define the list of textures to wait for
  31406. * @param callback Define the callback triggered once the entire list will be ready
  31407. */
  31408. BaseTexture.WhenAllReady = function (textures, callback) {
  31409. var numRemaining = textures.length;
  31410. if (numRemaining === 0) {
  31411. callback();
  31412. return;
  31413. }
  31414. var _loop_1 = function () {
  31415. texture = textures[i];
  31416. if (texture.isReady()) {
  31417. if (--numRemaining === 0) {
  31418. callback();
  31419. }
  31420. }
  31421. else {
  31422. onLoadObservable = texture.onLoadObservable;
  31423. var onLoadCallback_1 = function () {
  31424. onLoadObservable.removeCallback(onLoadCallback_1);
  31425. if (--numRemaining === 0) {
  31426. callback();
  31427. }
  31428. };
  31429. onLoadObservable.add(onLoadCallback_1);
  31430. }
  31431. };
  31432. var texture, onLoadObservable;
  31433. for (var i = 0; i < textures.length; i++) {
  31434. _loop_1();
  31435. }
  31436. };
  31437. /**
  31438. * Default anisotropic filtering level for the application.
  31439. * It is set to 4 as a good tradeoff between perf and quality.
  31440. */
  31441. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  31442. __decorate([
  31443. BABYLON.serialize()
  31444. ], BaseTexture.prototype, "name", void 0);
  31445. __decorate([
  31446. BABYLON.serialize("hasAlpha")
  31447. ], BaseTexture.prototype, "_hasAlpha", void 0);
  31448. __decorate([
  31449. BABYLON.serialize()
  31450. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  31451. __decorate([
  31452. BABYLON.serialize()
  31453. ], BaseTexture.prototype, "level", void 0);
  31454. __decorate([
  31455. BABYLON.serialize()
  31456. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  31457. __decorate([
  31458. BABYLON.serialize("coordinatesMode")
  31459. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  31460. __decorate([
  31461. BABYLON.serialize()
  31462. ], BaseTexture.prototype, "wrapU", void 0);
  31463. __decorate([
  31464. BABYLON.serialize()
  31465. ], BaseTexture.prototype, "wrapV", void 0);
  31466. __decorate([
  31467. BABYLON.serialize()
  31468. ], BaseTexture.prototype, "wrapR", void 0);
  31469. __decorate([
  31470. BABYLON.serialize()
  31471. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  31472. __decorate([
  31473. BABYLON.serialize()
  31474. ], BaseTexture.prototype, "isCube", void 0);
  31475. __decorate([
  31476. BABYLON.serialize()
  31477. ], BaseTexture.prototype, "is3D", void 0);
  31478. __decorate([
  31479. BABYLON.serialize()
  31480. ], BaseTexture.prototype, "gammaSpace", void 0);
  31481. __decorate([
  31482. BABYLON.serialize()
  31483. ], BaseTexture.prototype, "invertZ", void 0);
  31484. __decorate([
  31485. BABYLON.serialize()
  31486. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  31487. __decorate([
  31488. BABYLON.serialize()
  31489. ], BaseTexture.prototype, "lodGenerationOffset", null);
  31490. __decorate([
  31491. BABYLON.serialize()
  31492. ], BaseTexture.prototype, "lodGenerationScale", null);
  31493. __decorate([
  31494. BABYLON.serialize()
  31495. ], BaseTexture.prototype, "isRenderTarget", void 0);
  31496. return BaseTexture;
  31497. }());
  31498. BABYLON.BaseTexture = BaseTexture;
  31499. })(BABYLON || (BABYLON = {}));
  31500. //# sourceMappingURL=babylon.baseTexture.js.map
  31501. var BABYLON;
  31502. (function (BABYLON) {
  31503. /**
  31504. * This represents a texture in babylon. It can be easily loaded from a network, base64 or html input.
  31505. * @see http://doc.babylonjs.com/babylon101/materials#texture
  31506. */
  31507. var Texture = /** @class */ (function (_super) {
  31508. __extends(Texture, _super);
  31509. /**
  31510. * Instantiates a new texture.
  31511. * This represents a texture in babylon. It can be easily loaded from a network, base64 or html input.
  31512. * @see http://doc.babylonjs.com/babylon101/materials#texture
  31513. * @param url define the url of the picture to load as a texture
  31514. * @param scene define the scene the texture will belong to
  31515. * @param noMipmap define if the texture will require mip maps or not
  31516. * @param invertY define if the texture needs to be inverted on the y axis during loading
  31517. * @param samplingMode define the sampling mode we want for the texture while fectching from it (Texture.NEAREST_SAMPLINGMODE...)
  31518. * @param onLoad define a callback triggered when the texture has been loaded
  31519. * @param onError define a callback triggered when an error occurred during the loading session
  31520. * @param buffer define the buffer to load the texture from in case the texture is loaded from a buffer representation
  31521. * @param deleteBuffer define if the buffer we are loading the texture from should be deleted after load
  31522. * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)
  31523. */
  31524. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  31525. if (noMipmap === void 0) { noMipmap = false; }
  31526. if (invertY === void 0) { invertY = true; }
  31527. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31528. if (onLoad === void 0) { onLoad = null; }
  31529. if (onError === void 0) { onError = null; }
  31530. if (buffer === void 0) { buffer = null; }
  31531. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31532. var _this = _super.call(this, scene) || this;
  31533. /**
  31534. * Define an offset on the texture to offset the u coordinates of the UVs
  31535. * @see http://doc.babylonjs.com/how_to/more_materials#offsetting
  31536. */
  31537. _this.uOffset = 0;
  31538. /**
  31539. * Define an offset on the texture to offset the v coordinates of the UVs
  31540. * @see http://doc.babylonjs.com/how_to/more_materials#offsetting
  31541. */
  31542. _this.vOffset = 0;
  31543. /**
  31544. * Define an offset on the texture to scale the u coordinates of the UVs
  31545. * @see http://doc.babylonjs.com/how_to/more_materials#tiling
  31546. */
  31547. _this.uScale = 1.0;
  31548. /**
  31549. * Define an offset on the texture to scale the v coordinates of the UVs
  31550. * @see http://doc.babylonjs.com/how_to/more_materials#tiling
  31551. */
  31552. _this.vScale = 1.0;
  31553. /**
  31554. * Define an offset on the texture to rotate around the u coordinates of the UVs
  31555. * @see http://doc.babylonjs.com/how_to/more_materials
  31556. */
  31557. _this.uAng = 0;
  31558. /**
  31559. * Define an offset on the texture to rotate around the v coordinates of the UVs
  31560. * @see http://doc.babylonjs.com/how_to/more_materials
  31561. */
  31562. _this.vAng = 0;
  31563. /**
  31564. * Define an offset on the texture to rotate around the w coordinates of the UVs (in case of 3d texture)
  31565. * @see http://doc.babylonjs.com/how_to/more_materials
  31566. */
  31567. _this.wAng = 0;
  31568. /**
  31569. * Defines the center of rotation (U)
  31570. */
  31571. _this.uRotationCenter = 0.5;
  31572. /**
  31573. * Defines the center of rotation (V)
  31574. */
  31575. _this.vRotationCenter = 0.5;
  31576. /**
  31577. * Defines the center of rotation (W)
  31578. */
  31579. _this.wRotationCenter = 0.5;
  31580. /**
  31581. * Observable triggered once the texture has been loaded.
  31582. */
  31583. _this.onLoadObservable = new BABYLON.Observable();
  31584. _this._isBlocking = true;
  31585. _this.name = url || "";
  31586. _this.url = url;
  31587. _this._noMipmap = noMipmap;
  31588. _this._invertY = invertY;
  31589. _this._samplingMode = samplingMode;
  31590. _this._buffer = buffer;
  31591. _this._deleteBuffer = deleteBuffer;
  31592. if (format) {
  31593. _this._format = format;
  31594. }
  31595. scene = _this.getScene();
  31596. if (!scene) {
  31597. return _this;
  31598. }
  31599. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  31600. var load = function () {
  31601. if (_this.onLoadObservable.hasObservers()) {
  31602. _this.onLoadObservable.notifyObservers(_this);
  31603. }
  31604. if (onLoad) {
  31605. onLoad();
  31606. }
  31607. if (!_this.isBlocking && scene) {
  31608. scene.resetCachedMaterial();
  31609. }
  31610. };
  31611. if (!_this.url) {
  31612. _this._delayedOnLoad = load;
  31613. _this._delayedOnError = onError;
  31614. return _this;
  31615. }
  31616. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  31617. if (!_this._texture) {
  31618. if (!scene.useDelayedTextureLoading) {
  31619. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  31620. if (deleteBuffer) {
  31621. delete _this._buffer;
  31622. }
  31623. }
  31624. else {
  31625. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31626. _this._delayedOnLoad = load;
  31627. _this._delayedOnError = onError;
  31628. }
  31629. }
  31630. else {
  31631. if (_this._texture.isReady) {
  31632. BABYLON.Tools.SetImmediate(function () { return load(); });
  31633. }
  31634. else {
  31635. _this._texture.onLoadedObservable.add(load);
  31636. }
  31637. }
  31638. return _this;
  31639. }
  31640. Object.defineProperty(Texture.prototype, "noMipmap", {
  31641. /**
  31642. * Are mip maps generated for this texture or not.
  31643. */
  31644. get: function () {
  31645. return this._noMipmap;
  31646. },
  31647. enumerable: true,
  31648. configurable: true
  31649. });
  31650. Object.defineProperty(Texture.prototype, "isBlocking", {
  31651. get: function () {
  31652. return this._isBlocking;
  31653. },
  31654. /**
  31655. * Is the texture preventing material to render while loading.
  31656. * If false, a default texture will be used instead of the loading one during the preparation step.
  31657. */
  31658. set: function (value) {
  31659. this._isBlocking = value;
  31660. },
  31661. enumerable: true,
  31662. configurable: true
  31663. });
  31664. Object.defineProperty(Texture.prototype, "samplingMode", {
  31665. /**
  31666. * Get the current sampling mode associated with the texture.
  31667. */
  31668. get: function () {
  31669. return this._samplingMode;
  31670. },
  31671. enumerable: true,
  31672. configurable: true
  31673. });
  31674. /**
  31675. * Update the url (and optional buffer) of this texture if url was null during construction.
  31676. * @param url the url of the texture
  31677. * @param buffer the buffer of the texture (defaults to null)
  31678. */
  31679. Texture.prototype.updateURL = function (url, buffer) {
  31680. if (buffer === void 0) { buffer = null; }
  31681. if (this.url) {
  31682. throw new Error("URL is already set");
  31683. }
  31684. this.url = url;
  31685. this._buffer = buffer;
  31686. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31687. this.delayLoad();
  31688. };
  31689. /**
  31690. * Finish the loading sequence of a texture flagged as delayed load.
  31691. * @hidden
  31692. */
  31693. Texture.prototype.delayLoad = function () {
  31694. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31695. return;
  31696. }
  31697. var scene = this.getScene();
  31698. if (!scene) {
  31699. return;
  31700. }
  31701. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31702. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  31703. if (!this._texture) {
  31704. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  31705. if (this._deleteBuffer) {
  31706. delete this._buffer;
  31707. }
  31708. }
  31709. else {
  31710. if (this._delayedOnLoad) {
  31711. if (this._texture.isReady) {
  31712. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  31713. }
  31714. else {
  31715. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  31716. }
  31717. }
  31718. }
  31719. this._delayedOnLoad = null;
  31720. this._delayedOnError = null;
  31721. };
  31722. /**
  31723. * Update the sampling mode of the texture.
  31724. * Default is Trilinear mode.
  31725. *
  31726. * | Value | Type | Description |
  31727. * | ----- | ------------------ | ----------- |
  31728. * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |
  31729. * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
  31730. * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
  31731. * | 4 | NEAREST_NEAREST_MIPNEAREST | |
  31732. * | 5 | NEAREST_LINEAR_MIPNEAREST | |
  31733. * | 6 | NEAREST_LINEAR_MIPLINEAR | |
  31734. * | 7 | NEAREST_LINEAR | |
  31735. * | 8 | NEAREST_NEAREST | |
  31736. * | 9 | LINEAR_NEAREST_MIPNEAREST | |
  31737. * | 10 | LINEAR_NEAREST_MIPLINEAR | |
  31738. * | 11 | LINEAR_LINEAR | |
  31739. * | 12 | LINEAR_NEAREST | |
  31740. *
  31741. * > _mag_: magnification filter (close to the viewer)
  31742. * > _min_: minification filter (far from the viewer)
  31743. * > _mip_: filter used between mip map levels
  31744. *@param samplingMode Define the new sampling mode of the texture
  31745. */
  31746. Texture.prototype.updateSamplingMode = function (samplingMode) {
  31747. if (!this._texture) {
  31748. return;
  31749. }
  31750. var scene = this.getScene();
  31751. if (!scene) {
  31752. return;
  31753. }
  31754. this._samplingMode = samplingMode;
  31755. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  31756. };
  31757. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  31758. x *= this.uScale;
  31759. y *= this.vScale;
  31760. x -= this.uRotationCenter * this.uScale;
  31761. y -= this.vRotationCenter * this.vScale;
  31762. z -= this.wRotationCenter;
  31763. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  31764. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  31765. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  31766. t.z += this.wRotationCenter;
  31767. };
  31768. /**
  31769. * Get the current texture matrix which includes the requested offsetting, tiling and rotation components.
  31770. * @returns the transform matrix of the texture.
  31771. */
  31772. Texture.prototype.getTextureMatrix = function () {
  31773. var _this = this;
  31774. if (this.uOffset === this._cachedUOffset &&
  31775. this.vOffset === this._cachedVOffset &&
  31776. this.uScale === this._cachedUScale &&
  31777. this.vScale === this._cachedVScale &&
  31778. this.uAng === this._cachedUAng &&
  31779. this.vAng === this._cachedVAng &&
  31780. this.wAng === this._cachedWAng) {
  31781. return this._cachedTextureMatrix;
  31782. }
  31783. this._cachedUOffset = this.uOffset;
  31784. this._cachedVOffset = this.vOffset;
  31785. this._cachedUScale = this.uScale;
  31786. this._cachedVScale = this.vScale;
  31787. this._cachedUAng = this.uAng;
  31788. this._cachedVAng = this.vAng;
  31789. this._cachedWAng = this.wAng;
  31790. if (!this._cachedTextureMatrix) {
  31791. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31792. this._rowGenerationMatrix = new BABYLON.Matrix();
  31793. this._t0 = BABYLON.Vector3.Zero();
  31794. this._t1 = BABYLON.Vector3.Zero();
  31795. this._t2 = BABYLON.Vector3.Zero();
  31796. }
  31797. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  31798. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  31799. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  31800. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  31801. this._t1.subtractInPlace(this._t0);
  31802. this._t2.subtractInPlace(this._t0);
  31803. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31804. this._cachedTextureMatrix.m[0] = this._t1.x;
  31805. this._cachedTextureMatrix.m[1] = this._t1.y;
  31806. this._cachedTextureMatrix.m[2] = this._t1.z;
  31807. this._cachedTextureMatrix.m[4] = this._t2.x;
  31808. this._cachedTextureMatrix.m[5] = this._t2.y;
  31809. this._cachedTextureMatrix.m[6] = this._t2.z;
  31810. this._cachedTextureMatrix.m[8] = this._t0.x;
  31811. this._cachedTextureMatrix.m[9] = this._t0.y;
  31812. this._cachedTextureMatrix.m[10] = this._t0.z;
  31813. var scene = this.getScene();
  31814. if (!scene) {
  31815. return this._cachedTextureMatrix;
  31816. }
  31817. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31818. return mat.hasTexture(_this);
  31819. });
  31820. return this._cachedTextureMatrix;
  31821. };
  31822. /**
  31823. * Get the current matrix used to apply reflection. This is useful to rotate an environment texture for instance.
  31824. * @returns The reflection texture transform
  31825. */
  31826. Texture.prototype.getReflectionTextureMatrix = function () {
  31827. var _this = this;
  31828. var scene = this.getScene();
  31829. if (!scene) {
  31830. return this._cachedTextureMatrix;
  31831. }
  31832. if (this.uOffset === this._cachedUOffset &&
  31833. this.vOffset === this._cachedVOffset &&
  31834. this.uScale === this._cachedUScale &&
  31835. this.vScale === this._cachedVScale &&
  31836. this.coordinatesMode === this._cachedCoordinatesMode) {
  31837. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  31838. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  31839. return this._cachedTextureMatrix;
  31840. }
  31841. }
  31842. else {
  31843. return this._cachedTextureMatrix;
  31844. }
  31845. }
  31846. if (!this._cachedTextureMatrix) {
  31847. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31848. }
  31849. if (!this._projectionModeMatrix) {
  31850. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  31851. }
  31852. this._cachedUOffset = this.uOffset;
  31853. this._cachedVOffset = this.vOffset;
  31854. this._cachedUScale = this.uScale;
  31855. this._cachedVScale = this.vScale;
  31856. this._cachedCoordinatesMode = this.coordinatesMode;
  31857. switch (this.coordinatesMode) {
  31858. case Texture.PLANAR_MODE:
  31859. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31860. this._cachedTextureMatrix[0] = this.uScale;
  31861. this._cachedTextureMatrix[5] = this.vScale;
  31862. this._cachedTextureMatrix[12] = this.uOffset;
  31863. this._cachedTextureMatrix[13] = this.vOffset;
  31864. break;
  31865. case Texture.PROJECTION_MODE:
  31866. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  31867. this._projectionModeMatrix.m[0] = 0.5;
  31868. this._projectionModeMatrix.m[5] = -0.5;
  31869. this._projectionModeMatrix.m[10] = 0.0;
  31870. this._projectionModeMatrix.m[12] = 0.5;
  31871. this._projectionModeMatrix.m[13] = 0.5;
  31872. this._projectionModeMatrix.m[14] = 1.0;
  31873. this._projectionModeMatrix.m[15] = 1.0;
  31874. var projectionMatrix = scene.getProjectionMatrix();
  31875. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  31876. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  31877. break;
  31878. default:
  31879. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31880. break;
  31881. }
  31882. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31883. return (mat.getActiveTextures().indexOf(_this) !== -1);
  31884. });
  31885. return this._cachedTextureMatrix;
  31886. };
  31887. /**
  31888. * Clones the texture.
  31889. * @returns the cloned texture
  31890. */
  31891. Texture.prototype.clone = function () {
  31892. var _this = this;
  31893. return BABYLON.SerializationHelper.Clone(function () {
  31894. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  31895. }, this);
  31896. };
  31897. /**
  31898. * Serialize the texture to a JSON representation we can easily use in the resepective Parse function.
  31899. * @returns The JSON representation of the texture
  31900. */
  31901. Texture.prototype.serialize = function () {
  31902. var serializationObject = _super.prototype.serialize.call(this);
  31903. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  31904. serializationObject.base64String = this._buffer;
  31905. serializationObject.name = serializationObject.name.replace("data:", "");
  31906. }
  31907. serializationObject.invertY = this._invertY;
  31908. serializationObject.samplingMode = this.samplingMode;
  31909. return serializationObject;
  31910. };
  31911. /**
  31912. * Get the current class name of the texture usefull for serialization or dynamic coding.
  31913. * @returns "Texture"
  31914. */
  31915. Texture.prototype.getClassName = function () {
  31916. return "Texture";
  31917. };
  31918. /**
  31919. * Dispose the texture and release its associated resources.
  31920. */
  31921. Texture.prototype.dispose = function () {
  31922. _super.prototype.dispose.call(this);
  31923. this.onLoadObservable.clear();
  31924. this._delayedOnLoad = null;
  31925. this._delayedOnError = null;
  31926. };
  31927. /**
  31928. * Parse the JSON representation of a texture in order to recreate the texture in the given scene.
  31929. * @param parsedTexture Define the JSON representation of the texture
  31930. * @param scene Define the scene the parsed texture should be instantiated in
  31931. * @param rootUrl Define the root url of the parsing sequence in the case of relative dependencies
  31932. * @returns The parsed texture if successful
  31933. */
  31934. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  31935. if (parsedTexture.customType) {
  31936. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  31937. // Update Sampling Mode
  31938. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  31939. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  31940. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  31941. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  31942. }
  31943. }
  31944. return parsedCustomTexture;
  31945. }
  31946. if (parsedTexture.isCube) {
  31947. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  31948. }
  31949. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  31950. return null;
  31951. }
  31952. var texture = BABYLON.SerializationHelper.Parse(function () {
  31953. var generateMipMaps = true;
  31954. if (parsedTexture.noMipmap) {
  31955. generateMipMaps = false;
  31956. }
  31957. if (parsedTexture.mirrorPlane) {
  31958. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31959. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  31960. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  31961. return mirrorTexture;
  31962. }
  31963. else if (parsedTexture.isRenderTarget) {
  31964. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31965. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  31966. return renderTargetTexture;
  31967. }
  31968. else {
  31969. var texture;
  31970. if (parsedTexture.base64String) {
  31971. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31972. }
  31973. else {
  31974. var url = rootUrl + parsedTexture.name;
  31975. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31976. url = parsedTexture.url;
  31977. }
  31978. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31979. }
  31980. return texture;
  31981. }
  31982. }, parsedTexture, scene);
  31983. // Update Sampling Mode
  31984. if (parsedTexture.samplingMode) {
  31985. var sampling = parsedTexture.samplingMode;
  31986. if (texture._samplingMode !== sampling) {
  31987. texture.updateSamplingMode(sampling);
  31988. }
  31989. }
  31990. // Animations
  31991. if (parsedTexture.animations) {
  31992. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31993. var parsedAnimation = parsedTexture.animations[animationIndex];
  31994. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31995. }
  31996. }
  31997. return texture;
  31998. };
  31999. /**
  32000. * Creates a texture from its base 64 representation.
  32001. * @param data Define the base64 payload without the data: prefix
  32002. * @param name Define the name of the texture in the scene useful fo caching purpose for instance
  32003. * @param scene Define the scene the texture should belong to
  32004. * @param noMipmap Forces the texture to not create mip map information if true
  32005. * @param invertY define if the texture needs to be inverted on the y axis during loading
  32006. * @param samplingMode define the sampling mode we want for the texture while fectching from it (Texture.NEAREST_SAMPLINGMODE...)
  32007. * @param onLoad define a callback triggered when the texture has been loaded
  32008. * @param onError define a callback triggered when an error occurred during the loading session
  32009. * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)
  32010. * @returns the created texture
  32011. */
  32012. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  32013. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  32014. if (onLoad === void 0) { onLoad = null; }
  32015. if (onError === void 0) { onError = null; }
  32016. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  32017. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  32018. };
  32019. /**
  32020. * Creates a texture from its data: representation. (data: will be added in case only the payload has been passed in)
  32021. * @param data Define the base64 payload without the data: prefix
  32022. * @param name Define the name of the texture in the scene useful fo caching purpose for instance
  32023. * @param buffer define the buffer to load the texture from in case the texture is loaded from a buffer representation
  32024. * @param scene Define the scene the texture should belong to
  32025. * @param deleteBuffer define if the buffer we are loading the texture from should be deleted after load
  32026. * @param noMipmap Forces the texture to not create mip map information if true
  32027. * @param invertY define if the texture needs to be inverted on the y axis during loading
  32028. * @param samplingMode define the sampling mode we want for the texture while fectching from it (Texture.NEAREST_SAMPLINGMODE...)
  32029. * @param onLoad define a callback triggered when the texture has been loaded
  32030. * @param onError define a callback triggered when an error occurred during the loading session
  32031. * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)
  32032. * @returns the created texture
  32033. */
  32034. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  32035. if (deleteBuffer === void 0) { deleteBuffer = false; }
  32036. if (noMipmap === void 0) { noMipmap = false; }
  32037. if (invertY === void 0) { invertY = true; }
  32038. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  32039. if (onLoad === void 0) { onLoad = null; }
  32040. if (onError === void 0) { onError = null; }
  32041. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  32042. if (name.substr(0, 5) !== "data:") {
  32043. name = "data:" + name;
  32044. }
  32045. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  32046. };
  32047. /** nearest is mag = nearest and min = nearest and mip = linear */
  32048. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  32049. /** nearest is mag = nearest and min = nearest and mip = linear */
  32050. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  32051. /** Bilinear is mag = linear and min = linear and mip = nearest */
  32052. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  32053. /** Bilinear is mag = linear and min = linear and mip = nearest */
  32054. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  32055. /** Trilinear is mag = linear and min = linear and mip = linear */
  32056. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  32057. /** Trilinear is mag = linear and min = linear and mip = linear */
  32058. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  32059. /** mag = nearest and min = nearest and mip = nearest */
  32060. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  32061. /** mag = nearest and min = linear and mip = nearest */
  32062. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  32063. /** mag = nearest and min = linear and mip = linear */
  32064. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  32065. /** mag = nearest and min = linear and mip = none */
  32066. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  32067. /** mag = nearest and min = nearest and mip = none */
  32068. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  32069. /** mag = linear and min = nearest and mip = nearest */
  32070. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  32071. /** mag = linear and min = nearest and mip = linear */
  32072. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  32073. /** mag = linear and min = linear and mip = none */
  32074. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  32075. /** mag = linear and min = nearest and mip = none */
  32076. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  32077. /** Explicit coordinates mode */
  32078. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  32079. /** Spherical coordinates mode */
  32080. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  32081. /** Planar coordinates mode */
  32082. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  32083. /** Cubic coordinates mode */
  32084. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  32085. /** Projection coordinates mode */
  32086. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  32087. /** Inverse Cubic coordinates mode */
  32088. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  32089. /** Inverse Cubic coordinates mode */
  32090. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  32091. /** Equirectangular coordinates mode */
  32092. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  32093. /** Equirectangular Fixed coordinates mode */
  32094. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  32095. /** Equirectangular Fixed Mirrored coordinates mode */
  32096. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  32097. /** Texture is not repeating outside of 0..1 UVs */
  32098. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  32099. /** Texture is repeating outside of 0..1 UVs */
  32100. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  32101. /** Texture is repeating and mirrored */
  32102. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  32103. /**
  32104. * 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
  32105. */
  32106. Texture.UseSerializedUrlIfAny = false;
  32107. __decorate([
  32108. BABYLON.serialize()
  32109. ], Texture.prototype, "url", void 0);
  32110. __decorate([
  32111. BABYLON.serialize()
  32112. ], Texture.prototype, "uOffset", void 0);
  32113. __decorate([
  32114. BABYLON.serialize()
  32115. ], Texture.prototype, "vOffset", void 0);
  32116. __decorate([
  32117. BABYLON.serialize()
  32118. ], Texture.prototype, "uScale", void 0);
  32119. __decorate([
  32120. BABYLON.serialize()
  32121. ], Texture.prototype, "vScale", void 0);
  32122. __decorate([
  32123. BABYLON.serialize()
  32124. ], Texture.prototype, "uAng", void 0);
  32125. __decorate([
  32126. BABYLON.serialize()
  32127. ], Texture.prototype, "vAng", void 0);
  32128. __decorate([
  32129. BABYLON.serialize()
  32130. ], Texture.prototype, "wAng", void 0);
  32131. __decorate([
  32132. BABYLON.serialize()
  32133. ], Texture.prototype, "uRotationCenter", void 0);
  32134. __decorate([
  32135. BABYLON.serialize()
  32136. ], Texture.prototype, "vRotationCenter", void 0);
  32137. __decorate([
  32138. BABYLON.serialize()
  32139. ], Texture.prototype, "wRotationCenter", void 0);
  32140. __decorate([
  32141. BABYLON.serialize()
  32142. ], Texture.prototype, "isBlocking", null);
  32143. return Texture;
  32144. }(BABYLON.BaseTexture));
  32145. BABYLON.Texture = Texture;
  32146. })(BABYLON || (BABYLON = {}));
  32147. //# sourceMappingURL=babylon.texture.js.map
  32148. var BABYLON;
  32149. (function (BABYLON) {
  32150. /**
  32151. * @hidden
  32152. **/
  32153. var _CreationDataStorage = /** @class */ (function () {
  32154. function _CreationDataStorage() {
  32155. }
  32156. return _CreationDataStorage;
  32157. }());
  32158. BABYLON._CreationDataStorage = _CreationDataStorage;
  32159. /**
  32160. * @hidden
  32161. **/
  32162. var _InstanceDataStorage = /** @class */ (function () {
  32163. function _InstanceDataStorage() {
  32164. this.visibleInstances = {};
  32165. this.renderIdForInstances = new Array();
  32166. this.batchCache = new _InstancesBatch();
  32167. this.instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  32168. }
  32169. return _InstanceDataStorage;
  32170. }());
  32171. /**
  32172. * @hidden
  32173. **/
  32174. var _InstancesBatch = /** @class */ (function () {
  32175. function _InstancesBatch() {
  32176. this.mustReturn = false;
  32177. this.visibleInstances = new Array();
  32178. this.renderSelf = new Array();
  32179. }
  32180. return _InstancesBatch;
  32181. }());
  32182. BABYLON._InstancesBatch = _InstancesBatch;
  32183. /**
  32184. * Class used to represent renderable models
  32185. */
  32186. var Mesh = /** @class */ (function (_super) {
  32187. __extends(Mesh, _super);
  32188. /**
  32189. * @constructor
  32190. * @param name The value used by scene.getMeshByName() to do a lookup.
  32191. * @param scene The scene to add this mesh to.
  32192. * @param parent The parent of this mesh, if it has one
  32193. * @param source An optional Mesh from which geometry is shared, cloned.
  32194. * @param doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  32195. * When false, achieved by calling a clone(), also passing False.
  32196. * This will make creation of children, recursive.
  32197. * @param clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  32198. */
  32199. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  32200. if (scene === void 0) { scene = null; }
  32201. if (parent === void 0) { parent = null; }
  32202. if (source === void 0) { source = null; }
  32203. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32204. var _this = _super.call(this, name, scene) || this;
  32205. // Members
  32206. /**
  32207. * Gets the delay loading state of the mesh (when delay loading is turned on)
  32208. * @see http://doc.babylonjs.com/how_to/using_the_incremental_loading_system
  32209. */
  32210. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  32211. /**
  32212. * Gets the list of instances created from this mesh
  32213. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  32214. */
  32215. _this.instances = new Array();
  32216. _this._LODLevels = new Array();
  32217. /** @hidden */
  32218. _this._instanceDataStorage = new _InstanceDataStorage();
  32219. // Use by builder only to know what orientation were the mesh build in.
  32220. /** @hidden */
  32221. _this._originalBuilderSideOrientation = Mesh.DEFAULTSIDE;
  32222. /**
  32223. * Use this property to change the original side orientation defined at construction time
  32224. */
  32225. _this.overrideMaterialSideOrientation = null;
  32226. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  32227. // Will be used to save a source mesh reference, If any
  32228. _this._source = null;
  32229. scene = _this.getScene();
  32230. if (source) {
  32231. // Geometry
  32232. if (source._geometry) {
  32233. source._geometry.applyToMesh(_this);
  32234. }
  32235. // Deep copy
  32236. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  32237. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  32238. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
  32239. ], ["_poseMatrix"]);
  32240. // Source mesh
  32241. _this._source = source;
  32242. // Construction Params
  32243. // Clone parameters allowing mesh to be updated in case of parametric shapes.
  32244. _this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
  32245. _this._creationDataStorage = source._creationDataStorage;
  32246. // Animation ranges
  32247. if (_this._source._ranges) {
  32248. var ranges = _this._source._ranges;
  32249. for (var name in ranges) {
  32250. if (!ranges.hasOwnProperty(name)) {
  32251. continue;
  32252. }
  32253. if (!ranges[name]) {
  32254. continue;
  32255. }
  32256. _this.createAnimationRange(name, ranges[name].from, ranges[name].to);
  32257. }
  32258. }
  32259. // Metadata
  32260. if (source.metadata && source.metadata.clone) {
  32261. _this.metadata = source.metadata.clone();
  32262. }
  32263. else {
  32264. _this.metadata = source.metadata;
  32265. }
  32266. // Tags
  32267. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  32268. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  32269. }
  32270. // Parent
  32271. _this.parent = source.parent;
  32272. // Pivot
  32273. _this.setPivotMatrix(source.getPivotMatrix());
  32274. _this.id = name + "." + source.id;
  32275. // Material
  32276. _this.material = source.material;
  32277. var index;
  32278. if (!doNotCloneChildren) {
  32279. // Children
  32280. var directDescendants = source.getDescendants(true);
  32281. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  32282. var child = directDescendants[index_1];
  32283. if (child.clone) {
  32284. child.clone(name + "." + child.name, _this);
  32285. }
  32286. }
  32287. }
  32288. // Physics clone
  32289. var physicsEngine = _this.getScene().getPhysicsEngine();
  32290. if (clonePhysicsImpostor && physicsEngine) {
  32291. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  32292. if (impostor) {
  32293. _this.physicsImpostor = impostor.clone(_this);
  32294. }
  32295. }
  32296. // Particles
  32297. for (index = 0; index < scene.particleSystems.length; index++) {
  32298. var system = scene.particleSystems[index];
  32299. if (system.emitter === source) {
  32300. system.clone(system.name, _this);
  32301. }
  32302. }
  32303. _this.refreshBoundingInfo();
  32304. _this.computeWorldMatrix(true);
  32305. }
  32306. // Parent
  32307. if (parent !== null) {
  32308. _this.parent = parent;
  32309. }
  32310. return _this;
  32311. }
  32312. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  32313. /**
  32314. * An event triggered before rendering the mesh
  32315. */
  32316. get: function () {
  32317. if (!this._onBeforeRenderObservable) {
  32318. this._onBeforeRenderObservable = new BABYLON.Observable();
  32319. }
  32320. return this._onBeforeRenderObservable;
  32321. },
  32322. enumerable: true,
  32323. configurable: true
  32324. });
  32325. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  32326. /**
  32327. * An event triggered after rendering the mesh
  32328. */
  32329. get: function () {
  32330. if (!this._onAfterRenderObservable) {
  32331. this._onAfterRenderObservable = new BABYLON.Observable();
  32332. }
  32333. return this._onAfterRenderObservable;
  32334. },
  32335. enumerable: true,
  32336. configurable: true
  32337. });
  32338. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  32339. /**
  32340. * An event triggered before drawing the mesh
  32341. */
  32342. get: function () {
  32343. if (!this._onBeforeDrawObservable) {
  32344. this._onBeforeDrawObservable = new BABYLON.Observable();
  32345. }
  32346. return this._onBeforeDrawObservable;
  32347. },
  32348. enumerable: true,
  32349. configurable: true
  32350. });
  32351. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  32352. /**
  32353. * Sets a callback to call before drawing the mesh. It is recommended to use onBeforeDrawObservable instead
  32354. */
  32355. set: function (callback) {
  32356. if (this._onBeforeDrawObserver) {
  32357. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  32358. }
  32359. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  32360. },
  32361. enumerable: true,
  32362. configurable: true
  32363. });
  32364. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  32365. /**
  32366. * Gets or sets the morph target manager
  32367. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  32368. */
  32369. get: function () {
  32370. return this._morphTargetManager;
  32371. },
  32372. set: function (value) {
  32373. if (this._morphTargetManager === value) {
  32374. return;
  32375. }
  32376. this._morphTargetManager = value;
  32377. this._syncGeometryWithMorphTargetManager();
  32378. },
  32379. enumerable: true,
  32380. configurable: true
  32381. });
  32382. Object.defineProperty(Mesh.prototype, "source", {
  32383. /**
  32384. * Gets the source mesh (the one used to clone this one from)
  32385. */
  32386. get: function () {
  32387. return this._source;
  32388. },
  32389. enumerable: true,
  32390. configurable: true
  32391. });
  32392. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  32393. /**
  32394. * Gets or sets a boolean indicating that this mesh does not use index buffer
  32395. */
  32396. get: function () {
  32397. return this._unIndexed;
  32398. },
  32399. set: function (value) {
  32400. if (this._unIndexed !== value) {
  32401. this._unIndexed = value;
  32402. this._markSubMeshesAsAttributesDirty();
  32403. }
  32404. },
  32405. enumerable: true,
  32406. configurable: true
  32407. });
  32408. // Methods
  32409. /**
  32410. * Gets the class name
  32411. * @returns the string "Mesh".
  32412. */
  32413. Mesh.prototype.getClassName = function () {
  32414. return "Mesh";
  32415. };
  32416. /**
  32417. * Returns a description of this mesh
  32418. * @param fullDetails define if full details about this mesh must be used
  32419. * @returns a descriptive string representing this mesh
  32420. */
  32421. Mesh.prototype.toString = function (fullDetails) {
  32422. var ret = _super.prototype.toString.call(this, fullDetails);
  32423. ret += ", n vertices: " + this.getTotalVertices();
  32424. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  32425. if (this.animations) {
  32426. for (var i = 0; i < this.animations.length; i++) {
  32427. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  32428. }
  32429. }
  32430. if (fullDetails) {
  32431. if (this._geometry) {
  32432. var ib = this.getIndices();
  32433. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32434. if (vb && ib) {
  32435. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  32436. }
  32437. }
  32438. else {
  32439. ret += ", flat shading: UNKNOWN";
  32440. }
  32441. }
  32442. return ret;
  32443. };
  32444. /** @hidden */
  32445. Mesh.prototype._unBindEffect = function () {
  32446. _super.prototype._unBindEffect.call(this);
  32447. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  32448. var instance = _a[_i];
  32449. instance._unBindEffect();
  32450. }
  32451. };
  32452. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  32453. /**
  32454. * Gets a boolean indicating if this mesh has LOD
  32455. */
  32456. get: function () {
  32457. return this._LODLevels.length > 0;
  32458. },
  32459. enumerable: true,
  32460. configurable: true
  32461. });
  32462. /**
  32463. * Gets the list of MeshLODLevel associated with the current mesh
  32464. * @returns an array of MeshLODLevel
  32465. */
  32466. Mesh.prototype.getLODLevels = function () {
  32467. return this._LODLevels;
  32468. };
  32469. Mesh.prototype._sortLODLevels = function () {
  32470. this._LODLevels.sort(function (a, b) {
  32471. if (a.distance < b.distance) {
  32472. return 1;
  32473. }
  32474. if (a.distance > b.distance) {
  32475. return -1;
  32476. }
  32477. return 0;
  32478. });
  32479. };
  32480. /**
  32481. * Add a mesh as LOD level triggered at the given distance.
  32482. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32483. * @param distance The distance from the center of the object to show this level
  32484. * @param mesh The mesh to be added as LOD level (can be null)
  32485. * @return This mesh (for chaining)
  32486. */
  32487. Mesh.prototype.addLODLevel = function (distance, mesh) {
  32488. if (mesh && mesh._masterMesh) {
  32489. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  32490. return this;
  32491. }
  32492. var level = new BABYLON.MeshLODLevel(distance, mesh);
  32493. this._LODLevels.push(level);
  32494. if (mesh) {
  32495. mesh._masterMesh = this;
  32496. }
  32497. this._sortLODLevels();
  32498. return this;
  32499. };
  32500. /**
  32501. * Returns the LOD level mesh at the passed distance or null if not found.
  32502. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32503. * @param distance The distance from the center of the object to show this level
  32504. * @returns a Mesh or `null`
  32505. */
  32506. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  32507. for (var index = 0; index < this._LODLevels.length; index++) {
  32508. var level = this._LODLevels[index];
  32509. if (level.distance === distance) {
  32510. return level.mesh;
  32511. }
  32512. }
  32513. return null;
  32514. };
  32515. /**
  32516. * Remove a mesh from the LOD array
  32517. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32518. * @param mesh defines the mesh to be removed
  32519. * @return This mesh (for chaining)
  32520. */
  32521. Mesh.prototype.removeLODLevel = function (mesh) {
  32522. for (var index = 0; index < this._LODLevels.length; index++) {
  32523. if (this._LODLevels[index].mesh === mesh) {
  32524. this._LODLevels.splice(index, 1);
  32525. if (mesh) {
  32526. mesh._masterMesh = null;
  32527. }
  32528. }
  32529. }
  32530. this._sortLODLevels();
  32531. return this;
  32532. };
  32533. /**
  32534. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  32535. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32536. * @param camera defines the camera to use to compute distance
  32537. * @param boundingSphere defines a custom bounding sphere to use instead of the one from this mesh
  32538. * @return This mesh (for chaining)
  32539. */
  32540. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  32541. if (!this._LODLevels || this._LODLevels.length === 0) {
  32542. return this;
  32543. }
  32544. var bSphere;
  32545. if (boundingSphere) {
  32546. bSphere = boundingSphere;
  32547. }
  32548. else {
  32549. var boundingInfo = this.getBoundingInfo();
  32550. bSphere = boundingInfo.boundingSphere;
  32551. }
  32552. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  32553. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  32554. if (this.onLODLevelSelection) {
  32555. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  32556. }
  32557. return this;
  32558. }
  32559. for (var index = 0; index < this._LODLevels.length; index++) {
  32560. var level = this._LODLevels[index];
  32561. if (level.distance < distanceToCamera) {
  32562. if (level.mesh) {
  32563. level.mesh._preActivate();
  32564. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  32565. }
  32566. if (this.onLODLevelSelection) {
  32567. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  32568. }
  32569. return level.mesh;
  32570. }
  32571. }
  32572. if (this.onLODLevelSelection) {
  32573. this.onLODLevelSelection(distanceToCamera, this, this);
  32574. }
  32575. return this;
  32576. };
  32577. Object.defineProperty(Mesh.prototype, "geometry", {
  32578. /**
  32579. * Gets the mesh internal Geometry object
  32580. */
  32581. get: function () {
  32582. return this._geometry;
  32583. },
  32584. enumerable: true,
  32585. configurable: true
  32586. });
  32587. /**
  32588. * Returns the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  32589. * @returns the total number of vertices
  32590. */
  32591. Mesh.prototype.getTotalVertices = function () {
  32592. if (this._geometry === null || this._geometry === undefined) {
  32593. return 0;
  32594. }
  32595. return this._geometry.getTotalVertices();
  32596. };
  32597. /**
  32598. * Returns the content of an associated vertex buffer
  32599. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  32600. * - BABYLON.VertexBuffer.PositionKind
  32601. * - BABYLON.VertexBuffer.UVKind
  32602. * - BABYLON.VertexBuffer.UV2Kind
  32603. * - BABYLON.VertexBuffer.UV3Kind
  32604. * - BABYLON.VertexBuffer.UV4Kind
  32605. * - BABYLON.VertexBuffer.UV5Kind
  32606. * - BABYLON.VertexBuffer.UV6Kind
  32607. * - BABYLON.VertexBuffer.ColorKind
  32608. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32609. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32610. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32611. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32612. * @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
  32613. * @param forceCopy defines a boolean forcing the copy of the buffer no matter what the value of copyWhenShared is
  32614. * @returns a FloatArray or null if the mesh has no geometry or no vertex buffer for this kind.
  32615. */
  32616. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  32617. if (!this._geometry) {
  32618. return null;
  32619. }
  32620. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  32621. };
  32622. /**
  32623. * Returns the mesh VertexBuffer object from the requested `kind`
  32624. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  32625. * - BABYLON.VertexBuffer.PositionKind
  32626. * - BABYLON.VertexBuffer.UVKind
  32627. * - BABYLON.VertexBuffer.UV2Kind
  32628. * - BABYLON.VertexBuffer.UV3Kind
  32629. * - BABYLON.VertexBuffer.UV4Kind
  32630. * - BABYLON.VertexBuffer.UV5Kind
  32631. * - BABYLON.VertexBuffer.UV6Kind
  32632. * - BABYLON.VertexBuffer.ColorKind
  32633. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32634. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32635. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32636. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32637. * @returns a FloatArray or null if the mesh has no vertex buffer for this kind.
  32638. */
  32639. Mesh.prototype.getVertexBuffer = function (kind) {
  32640. if (!this._geometry) {
  32641. return null;
  32642. }
  32643. return this._geometry.getVertexBuffer(kind);
  32644. };
  32645. /**
  32646. * Tests if a specific vertex buffer is associated with this mesh
  32647. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  32648. * - BABYLON.VertexBuffer.PositionKind
  32649. * - BABYLON.VertexBuffer.UVKind
  32650. * - BABYLON.VertexBuffer.UV2Kind
  32651. * - BABYLON.VertexBuffer.UV3Kind
  32652. * - BABYLON.VertexBuffer.UV4Kind
  32653. * - BABYLON.VertexBuffer.UV5Kind
  32654. * - BABYLON.VertexBuffer.UV6Kind
  32655. * - BABYLON.VertexBuffer.ColorKind
  32656. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32657. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32658. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32659. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32660. * @returns a boolean
  32661. */
  32662. Mesh.prototype.isVerticesDataPresent = function (kind) {
  32663. if (!this._geometry) {
  32664. if (this._delayInfo) {
  32665. return this._delayInfo.indexOf(kind) !== -1;
  32666. }
  32667. return false;
  32668. }
  32669. return this._geometry.isVerticesDataPresent(kind);
  32670. };
  32671. /**
  32672. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  32673. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  32674. * - BABYLON.VertexBuffer.PositionKind
  32675. * - BABYLON.VertexBuffer.UVKind
  32676. * - BABYLON.VertexBuffer.UV2Kind
  32677. * - BABYLON.VertexBuffer.UV3Kind
  32678. * - BABYLON.VertexBuffer.UV4Kind
  32679. * - BABYLON.VertexBuffer.UV5Kind
  32680. * - BABYLON.VertexBuffer.UV6Kind
  32681. * - BABYLON.VertexBuffer.ColorKind
  32682. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32683. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32684. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32685. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32686. * @returns a boolean
  32687. */
  32688. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  32689. if (!this._geometry) {
  32690. if (this._delayInfo) {
  32691. return this._delayInfo.indexOf(kind) !== -1;
  32692. }
  32693. return false;
  32694. }
  32695. return this._geometry.isVertexBufferUpdatable(kind);
  32696. };
  32697. /**
  32698. * Returns a string which contains the list of existing `kinds` of Vertex Data associated with this mesh.
  32699. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  32700. * - BABYLON.VertexBuffer.PositionKind
  32701. * - BABYLON.VertexBuffer.UVKind
  32702. * - BABYLON.VertexBuffer.UV2Kind
  32703. * - BABYLON.VertexBuffer.UV3Kind
  32704. * - BABYLON.VertexBuffer.UV4Kind
  32705. * - BABYLON.VertexBuffer.UV5Kind
  32706. * - BABYLON.VertexBuffer.UV6Kind
  32707. * - BABYLON.VertexBuffer.ColorKind
  32708. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32709. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32710. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32711. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32712. * @returns an array of strings
  32713. */
  32714. Mesh.prototype.getVerticesDataKinds = function () {
  32715. if (!this._geometry) {
  32716. var result = new Array();
  32717. if (this._delayInfo) {
  32718. this._delayInfo.forEach(function (kind, index, array) {
  32719. result.push(kind);
  32720. });
  32721. }
  32722. return result;
  32723. }
  32724. return this._geometry.getVerticesDataKinds();
  32725. };
  32726. /**
  32727. * Returns a positive integer : the total number of indices in this mesh geometry.
  32728. * @returns the numner of indices or zero if the mesh has no geometry.
  32729. */
  32730. Mesh.prototype.getTotalIndices = function () {
  32731. if (!this._geometry) {
  32732. return 0;
  32733. }
  32734. return this._geometry.getTotalIndices();
  32735. };
  32736. /**
  32737. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  32738. * @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.
  32739. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  32740. * @returns the indices array or an empty array if the mesh has no geometry
  32741. */
  32742. Mesh.prototype.getIndices = function (copyWhenShared, forceCopy) {
  32743. if (!this._geometry) {
  32744. return [];
  32745. }
  32746. return this._geometry.getIndices(copyWhenShared, forceCopy);
  32747. };
  32748. Object.defineProperty(Mesh.prototype, "isBlocked", {
  32749. get: function () {
  32750. return this._masterMesh !== null && this._masterMesh !== undefined;
  32751. },
  32752. enumerable: true,
  32753. configurable: true
  32754. });
  32755. /**
  32756. * Determine if the current mesh is ready to be rendered
  32757. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  32758. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  32759. * @returns true if all associated assets are ready (material, textures, shaders)
  32760. */
  32761. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  32762. if (completeCheck === void 0) { completeCheck = false; }
  32763. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  32764. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32765. return false;
  32766. }
  32767. if (!_super.prototype.isReady.call(this, completeCheck)) {
  32768. return false;
  32769. }
  32770. if (!this.subMeshes || this.subMeshes.length === 0) {
  32771. return true;
  32772. }
  32773. if (!completeCheck) {
  32774. return true;
  32775. }
  32776. var engine = this.getEngine();
  32777. var scene = this.getScene();
  32778. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  32779. this.computeWorldMatrix();
  32780. var mat = this.material || scene.defaultMaterial;
  32781. if (mat) {
  32782. if (mat.storeEffectOnSubMeshes) {
  32783. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32784. var subMesh = _a[_i];
  32785. var effectiveMaterial = subMesh.getMaterial();
  32786. if (effectiveMaterial) {
  32787. if (effectiveMaterial.storeEffectOnSubMeshes) {
  32788. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32789. return false;
  32790. }
  32791. }
  32792. else {
  32793. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32794. return false;
  32795. }
  32796. }
  32797. }
  32798. }
  32799. }
  32800. else {
  32801. if (!mat.isReady(this, hardwareInstancedRendering)) {
  32802. return false;
  32803. }
  32804. }
  32805. }
  32806. // Shadows
  32807. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  32808. var light = _c[_b];
  32809. var generator = light.getShadowGenerator();
  32810. if (generator) {
  32811. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  32812. var subMesh = _e[_d];
  32813. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  32814. return false;
  32815. }
  32816. }
  32817. }
  32818. }
  32819. // LOD
  32820. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  32821. var lod = _g[_f];
  32822. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  32823. return false;
  32824. }
  32825. }
  32826. return true;
  32827. };
  32828. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  32829. /**
  32830. * 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.
  32831. */
  32832. get: function () {
  32833. return this._areNormalsFrozen;
  32834. },
  32835. enumerable: true,
  32836. configurable: true
  32837. });
  32838. /**
  32839. * 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.
  32840. * @returns the current mesh
  32841. */
  32842. Mesh.prototype.freezeNormals = function () {
  32843. this._areNormalsFrozen = true;
  32844. return this;
  32845. };
  32846. /**
  32847. * 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
  32848. * @returns the current mesh
  32849. */
  32850. Mesh.prototype.unfreezeNormals = function () {
  32851. this._areNormalsFrozen = false;
  32852. return this;
  32853. };
  32854. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  32855. /**
  32856. * Sets a value overriding the instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  32857. */
  32858. set: function (count) {
  32859. this._instanceDataStorage.overridenInstanceCount = count;
  32860. },
  32861. enumerable: true,
  32862. configurable: true
  32863. });
  32864. // Methods
  32865. /** @hidden */
  32866. Mesh.prototype._preActivate = function () {
  32867. var sceneRenderId = this.getScene().getRenderId();
  32868. if (this._preActivateId === sceneRenderId) {
  32869. return this;
  32870. }
  32871. this._preActivateId = sceneRenderId;
  32872. this._instanceDataStorage.visibleInstances = null;
  32873. return this;
  32874. };
  32875. /** @hidden */
  32876. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  32877. if (this._instanceDataStorage.visibleInstances) {
  32878. this._instanceDataStorage.visibleInstances.intermediateDefaultRenderId = renderId;
  32879. }
  32880. return this;
  32881. };
  32882. /** @hidden */
  32883. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  32884. if (!this._instanceDataStorage.visibleInstances) {
  32885. this._instanceDataStorage.visibleInstances = {};
  32886. this._instanceDataStorage.visibleInstances.defaultRenderId = renderId;
  32887. this._instanceDataStorage.visibleInstances.selfDefaultRenderId = this._renderId;
  32888. }
  32889. if (!this._instanceDataStorage.visibleInstances[renderId]) {
  32890. this._instanceDataStorage.visibleInstances[renderId] = new Array();
  32891. }
  32892. this._instanceDataStorage.visibleInstances[renderId].push(instance);
  32893. return this;
  32894. };
  32895. /**
  32896. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  32897. * This means the mesh underlying bounding box and sphere are recomputed.
  32898. * @returns the current mesh
  32899. */
  32900. Mesh.prototype.refreshBoundingInfo = function () {
  32901. return this._refreshBoundingInfo(false);
  32902. };
  32903. /** @hidden */
  32904. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  32905. if (this._boundingInfo && this._boundingInfo.isLocked) {
  32906. return this;
  32907. }
  32908. var data = this._getPositionData(applySkeleton);
  32909. if (data) {
  32910. var bias = this.geometry ? this.geometry.boundingBias : null;
  32911. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices(), bias);
  32912. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  32913. }
  32914. if (this.subMeshes) {
  32915. for (var index = 0; index < this.subMeshes.length; index++) {
  32916. this.subMeshes[index].refreshBoundingInfo();
  32917. }
  32918. }
  32919. this._updateBoundingInfo();
  32920. return this;
  32921. };
  32922. Mesh.prototype._getPositionData = function (applySkeleton) {
  32923. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32924. if (data && applySkeleton && this.skeleton) {
  32925. data = BABYLON.Tools.Slice(data);
  32926. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32927. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32928. if (matricesWeightsData && matricesIndicesData) {
  32929. var needExtras = this.numBoneInfluencers > 4;
  32930. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  32931. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  32932. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  32933. var tempVector = BABYLON.Tmp.Vector3[0];
  32934. var finalMatrix = BABYLON.Tmp.Matrix[0];
  32935. var tempMatrix = BABYLON.Tmp.Matrix[1];
  32936. var matWeightIdx = 0;
  32937. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  32938. finalMatrix.reset();
  32939. var inf;
  32940. var weight;
  32941. for (inf = 0; inf < 4; inf++) {
  32942. weight = matricesWeightsData[matWeightIdx + inf];
  32943. if (weight > 0) {
  32944. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32945. finalMatrix.addToSelf(tempMatrix);
  32946. }
  32947. }
  32948. if (needExtras) {
  32949. for (inf = 0; inf < 4; inf++) {
  32950. weight = matricesWeightsExtraData[matWeightIdx + inf];
  32951. if (weight > 0) {
  32952. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32953. finalMatrix.addToSelf(tempMatrix);
  32954. }
  32955. }
  32956. }
  32957. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  32958. tempVector.toArray(data, index);
  32959. }
  32960. }
  32961. }
  32962. return data;
  32963. };
  32964. /** @hidden */
  32965. Mesh.prototype._createGlobalSubMesh = function (force) {
  32966. var totalVertices = this.getTotalVertices();
  32967. if (!totalVertices || !this.getIndices()) {
  32968. return null;
  32969. }
  32970. // Check if we need to recreate the submeshes
  32971. if (this.subMeshes && this.subMeshes.length > 0) {
  32972. var ib = this.getIndices();
  32973. if (!ib) {
  32974. return null;
  32975. }
  32976. var totalIndices = ib.length;
  32977. var needToRecreate = false;
  32978. if (force) {
  32979. needToRecreate = true;
  32980. }
  32981. else {
  32982. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32983. var submesh = _a[_i];
  32984. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  32985. needToRecreate = true;
  32986. break;
  32987. }
  32988. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  32989. needToRecreate = true;
  32990. break;
  32991. }
  32992. }
  32993. }
  32994. if (!needToRecreate) {
  32995. return this.subMeshes[0];
  32996. }
  32997. }
  32998. this.releaseSubMeshes();
  32999. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  33000. };
  33001. /**
  33002. * This function will subdivide the mesh into multiple submeshes
  33003. * @param count defines the expected number of submeshes
  33004. */
  33005. Mesh.prototype.subdivide = function (count) {
  33006. if (count < 1) {
  33007. return;
  33008. }
  33009. var totalIndices = this.getTotalIndices();
  33010. var subdivisionSize = (totalIndices / count) | 0;
  33011. var offset = 0;
  33012. // Ensure that subdivisionSize is a multiple of 3
  33013. while (subdivisionSize % 3 !== 0) {
  33014. subdivisionSize++;
  33015. }
  33016. this.releaseSubMeshes();
  33017. for (var index = 0; index < count; index++) {
  33018. if (offset >= totalIndices) {
  33019. break;
  33020. }
  33021. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  33022. offset += subdivisionSize;
  33023. }
  33024. this.synchronizeInstances();
  33025. };
  33026. /**
  33027. * Copy a FloatArray into a specific associated vertex buffer
  33028. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  33029. * - BABYLON.VertexBuffer.PositionKind
  33030. * - BABYLON.VertexBuffer.UVKind
  33031. * - BABYLON.VertexBuffer.UV2Kind
  33032. * - BABYLON.VertexBuffer.UV3Kind
  33033. * - BABYLON.VertexBuffer.UV4Kind
  33034. * - BABYLON.VertexBuffer.UV5Kind
  33035. * - BABYLON.VertexBuffer.UV6Kind
  33036. * - BABYLON.VertexBuffer.ColorKind
  33037. * - BABYLON.VertexBuffer.MatricesIndicesKind
  33038. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  33039. * - BABYLON.VertexBuffer.MatricesWeightsKind
  33040. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  33041. * @param data defines the data source
  33042. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  33043. * @param stride defines the data stride size (can be null)
  33044. * @returns the current mesh
  33045. */
  33046. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  33047. if (updatable === void 0) { updatable = false; }
  33048. if (!this._geometry) {
  33049. var vertexData = new BABYLON.VertexData();
  33050. vertexData.set(data, kind);
  33051. var scene = this.getScene();
  33052. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  33053. }
  33054. else {
  33055. this._geometry.setVerticesData(kind, data, updatable, stride);
  33056. }
  33057. return this;
  33058. };
  33059. /**
  33060. * Flags an associated vertex buffer as updatable
  33061. * @param kind defines which buffer to use (positions, indices, normals, etc). Possible `kind` values :
  33062. * - BABYLON.VertexBuffer.PositionKind
  33063. * - BABYLON.VertexBuffer.UVKind
  33064. * - BABYLON.VertexBuffer.UV2Kind
  33065. * - BABYLON.VertexBuffer.UV3Kind
  33066. * - BABYLON.VertexBuffer.UV4Kind
  33067. * - BABYLON.VertexBuffer.UV5Kind
  33068. * - BABYLON.VertexBuffer.UV6Kind
  33069. * - BABYLON.VertexBuffer.ColorKind
  33070. * - BABYLON.VertexBuffer.MatricesIndicesKind
  33071. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  33072. * - BABYLON.VertexBuffer.MatricesWeightsKind
  33073. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  33074. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  33075. */
  33076. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  33077. if (updatable === void 0) { updatable = true; }
  33078. var vb = this.getVertexBuffer(kind);
  33079. if (!vb || vb.isUpdatable() === updatable) {
  33080. return;
  33081. }
  33082. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  33083. };
  33084. /**
  33085. * Sets the mesh global Vertex Buffer
  33086. * @param buffer defines the buffer to use
  33087. * @returns the current mesh
  33088. */
  33089. Mesh.prototype.setVerticesBuffer = function (buffer) {
  33090. if (!this._geometry) {
  33091. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  33092. }
  33093. this._geometry.setVerticesBuffer(buffer);
  33094. return this;
  33095. };
  33096. /**
  33097. * Update a specific associated vertex buffer
  33098. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  33099. * - BABYLON.VertexBuffer.PositionKind
  33100. * - BABYLON.VertexBuffer.UVKind
  33101. * - BABYLON.VertexBuffer.UV2Kind
  33102. * - BABYLON.VertexBuffer.UV3Kind
  33103. * - BABYLON.VertexBuffer.UV4Kind
  33104. * - BABYLON.VertexBuffer.UV5Kind
  33105. * - BABYLON.VertexBuffer.UV6Kind
  33106. * - BABYLON.VertexBuffer.ColorKind
  33107. * - BABYLON.VertexBuffer.MatricesIndicesKind
  33108. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  33109. * - BABYLON.VertexBuffer.MatricesWeightsKind
  33110. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  33111. * @param data defines the data source
  33112. * @param updateExtends defines if extends info of the mesh must be updated (can be null). This is mostly useful for "position" kind
  33113. * @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)
  33114. * @returns the current mesh
  33115. */
  33116. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  33117. if (!this._geometry) {
  33118. return this;
  33119. }
  33120. if (!makeItUnique) {
  33121. this._geometry.updateVerticesData(kind, data, updateExtends);
  33122. }
  33123. else {
  33124. this.makeGeometryUnique();
  33125. this.updateVerticesData(kind, data, updateExtends, false);
  33126. }
  33127. return this;
  33128. };
  33129. /**
  33130. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  33131. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  33132. * @param positionFunction is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything
  33133. * @param computeNormals is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update
  33134. * @returns the current mesh
  33135. */
  33136. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  33137. if (computeNormals === void 0) { computeNormals = true; }
  33138. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33139. if (!positions) {
  33140. return this;
  33141. }
  33142. positionFunction(positions);
  33143. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  33144. if (computeNormals) {
  33145. var indices = this.getIndices();
  33146. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33147. if (!normals) {
  33148. return this;
  33149. }
  33150. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  33151. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  33152. }
  33153. return this;
  33154. };
  33155. /**
  33156. * Creates a un-shared specific occurence of the geometry for the mesh.
  33157. * @returns the current mesh
  33158. */
  33159. Mesh.prototype.makeGeometryUnique = function () {
  33160. if (!this._geometry) {
  33161. return this;
  33162. }
  33163. var oldGeometry = this._geometry;
  33164. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  33165. oldGeometry.releaseForMesh(this, true);
  33166. geometry.applyToMesh(this);
  33167. return this;
  33168. };
  33169. /**
  33170. * Set the index buffer of this mesh
  33171. * @param indices defines the source data
  33172. * @param totalVertices defines the total number of vertices referenced by this index data (can be null)
  33173. * @param updatable defines if the updated index buffer must be flagged as updatable (default is false)
  33174. * @returns the current mesh
  33175. */
  33176. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  33177. if (totalVertices === void 0) { totalVertices = null; }
  33178. if (updatable === void 0) { updatable = false; }
  33179. if (!this._geometry) {
  33180. var vertexData = new BABYLON.VertexData();
  33181. vertexData.indices = indices;
  33182. var scene = this.getScene();
  33183. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  33184. }
  33185. else {
  33186. this._geometry.setIndices(indices, totalVertices, updatable);
  33187. }
  33188. return this;
  33189. };
  33190. /**
  33191. * Update the current index buffer
  33192. * @param indices defines the source data
  33193. * @param offset defines the offset in the index buffer where to store the new data (can be null)
  33194. * @returns the current mesh
  33195. */
  33196. Mesh.prototype.updateIndices = function (indices, offset) {
  33197. if (!this._geometry) {
  33198. return this;
  33199. }
  33200. this._geometry.updateIndices(indices, offset);
  33201. return this;
  33202. };
  33203. /**
  33204. * Invert the geometry to move from a right handed system to a left handed one.
  33205. * @returns the current mesh
  33206. */
  33207. Mesh.prototype.toLeftHanded = function () {
  33208. if (!this._geometry) {
  33209. return this;
  33210. }
  33211. this._geometry.toLeftHanded();
  33212. return this;
  33213. };
  33214. /** @hidden */
  33215. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  33216. if (!this._geometry) {
  33217. return this;
  33218. }
  33219. var engine = this.getScene().getEngine();
  33220. // Wireframe
  33221. var indexToBind;
  33222. if (this._unIndexed) {
  33223. indexToBind = null;
  33224. }
  33225. else {
  33226. switch (fillMode) {
  33227. case BABYLON.Material.PointFillMode:
  33228. indexToBind = null;
  33229. break;
  33230. case BABYLON.Material.WireFrameFillMode:
  33231. indexToBind = subMesh._getLinesIndexBuffer(this.getIndices(), engine);
  33232. break;
  33233. default:
  33234. case BABYLON.Material.TriangleFillMode:
  33235. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  33236. break;
  33237. }
  33238. }
  33239. // VBOs
  33240. this._geometry._bind(effect, indexToBind);
  33241. return this;
  33242. };
  33243. /** @hidden */
  33244. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  33245. if (alternate === void 0) { alternate = false; }
  33246. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  33247. return this;
  33248. }
  33249. if (this._onBeforeDrawObservable) {
  33250. this._onBeforeDrawObservable.notifyObservers(this);
  33251. }
  33252. var scene = this.getScene();
  33253. var engine = scene.getEngine();
  33254. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  33255. // or triangles as points
  33256. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  33257. }
  33258. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  33259. // Triangles as wireframe
  33260. engine.drawElementsType(fillMode, 0, subMesh._linesIndexCount, instancesCount);
  33261. }
  33262. else {
  33263. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  33264. }
  33265. if (scene._isAlternateRenderingEnabled && !alternate) {
  33266. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  33267. if (!effect || !scene.activeCamera) {
  33268. return this;
  33269. }
  33270. scene._switchToAlternateCameraConfiguration(true);
  33271. this._effectiveMaterial.bindView(effect);
  33272. this._effectiveMaterial.bindViewProjection(effect);
  33273. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  33274. this._draw(subMesh, fillMode, instancesCount, true);
  33275. engine.setViewport(scene.activeCamera.viewport);
  33276. scene._switchToAlternateCameraConfiguration(false);
  33277. this._effectiveMaterial.bindView(effect);
  33278. this._effectiveMaterial.bindViewProjection(effect);
  33279. }
  33280. return this;
  33281. };
  33282. /**
  33283. * Registers for this mesh a javascript function called just before the rendering process
  33284. * @param func defines the function to call before rendering this mesh
  33285. * @returns the current mesh
  33286. */
  33287. Mesh.prototype.registerBeforeRender = function (func) {
  33288. this.onBeforeRenderObservable.add(func);
  33289. return this;
  33290. };
  33291. /**
  33292. * Disposes a previously registered javascript function called before the rendering
  33293. * @param func defines the function to remove
  33294. * @returns the current mesh
  33295. */
  33296. Mesh.prototype.unregisterBeforeRender = function (func) {
  33297. this.onBeforeRenderObservable.removeCallback(func);
  33298. return this;
  33299. };
  33300. /**
  33301. * Registers for this mesh a javascript function called just after the rendering is complete
  33302. * @param func defines the function to call after rendering this mesh
  33303. * @returns the current mesh
  33304. */
  33305. Mesh.prototype.registerAfterRender = function (func) {
  33306. this.onAfterRenderObservable.add(func);
  33307. return this;
  33308. };
  33309. /**
  33310. * Disposes a previously registered javascript function called after the rendering.
  33311. * @param func defines the function to remove
  33312. * @returns the current mesh
  33313. */
  33314. Mesh.prototype.unregisterAfterRender = function (func) {
  33315. this.onAfterRenderObservable.removeCallback(func);
  33316. return this;
  33317. };
  33318. /** @hidden */
  33319. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  33320. var scene = this.getScene();
  33321. var batchCache = this._instanceDataStorage.batchCache;
  33322. batchCache.mustReturn = false;
  33323. batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  33324. batchCache.visibleInstances[subMeshId] = null;
  33325. if (this._instanceDataStorage.visibleInstances) {
  33326. var visibleInstances = this._instanceDataStorage.visibleInstances;
  33327. var currentRenderId = scene.getRenderId();
  33328. var defaultRenderId = (scene._isInIntermediateRendering() ? visibleInstances.intermediateDefaultRenderId : visibleInstances.defaultRenderId);
  33329. batchCache.visibleInstances[subMeshId] = visibleInstances[currentRenderId];
  33330. var selfRenderId = this._renderId;
  33331. if (!batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  33332. batchCache.visibleInstances[subMeshId] = visibleInstances[defaultRenderId];
  33333. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  33334. selfRenderId = Math.max(visibleInstances.selfDefaultRenderId, currentRenderId);
  33335. }
  33336. var visibleInstancesForSubMesh = batchCache.visibleInstances[subMeshId];
  33337. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  33338. if (this._instanceDataStorage.renderIdForInstances[subMeshId] === currentRenderId) {
  33339. batchCache.mustReturn = true;
  33340. return batchCache;
  33341. }
  33342. if (currentRenderId !== selfRenderId) {
  33343. batchCache.renderSelf[subMeshId] = false;
  33344. }
  33345. }
  33346. this._instanceDataStorage.renderIdForInstances[subMeshId] = currentRenderId;
  33347. }
  33348. return batchCache;
  33349. };
  33350. /** @hidden */
  33351. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  33352. var visibleInstances = batch.visibleInstances[subMesh._id];
  33353. if (!visibleInstances) {
  33354. return this;
  33355. }
  33356. var matricesCount = visibleInstances.length + 1;
  33357. var bufferSize = matricesCount * 16 * 4;
  33358. var instanceStorage = this._instanceDataStorage;
  33359. var currentInstancesBufferSize = instanceStorage.instancesBufferSize;
  33360. var instancesBuffer = instanceStorage.instancesBuffer;
  33361. while (instanceStorage.instancesBufferSize < bufferSize) {
  33362. instanceStorage.instancesBufferSize *= 2;
  33363. }
  33364. if (!instanceStorage.instancesData || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
  33365. instanceStorage.instancesData = new Float32Array(instanceStorage.instancesBufferSize / 4);
  33366. }
  33367. var offset = 0;
  33368. var instancesCount = 0;
  33369. var world = this.getWorldMatrix();
  33370. if (batch.renderSelf[subMesh._id]) {
  33371. world.copyToArray(instanceStorage.instancesData, offset);
  33372. offset += 16;
  33373. instancesCount++;
  33374. }
  33375. if (visibleInstances) {
  33376. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  33377. var instance = visibleInstances[instanceIndex];
  33378. instance.getWorldMatrix().copyToArray(instanceStorage.instancesData, offset);
  33379. offset += 16;
  33380. instancesCount++;
  33381. }
  33382. }
  33383. if (!instancesBuffer || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
  33384. if (instancesBuffer) {
  33385. instancesBuffer.dispose();
  33386. }
  33387. instancesBuffer = new BABYLON.Buffer(engine, instanceStorage.instancesData, true, 16, false, true);
  33388. instanceStorage.instancesBuffer = instancesBuffer;
  33389. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  33390. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  33391. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  33392. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  33393. }
  33394. else {
  33395. instancesBuffer.updateDirectly(instanceStorage.instancesData, 0, instancesCount);
  33396. }
  33397. this._bind(subMesh, effect, fillMode);
  33398. this._draw(subMesh, fillMode, instancesCount);
  33399. engine.unbindInstanceAttributes();
  33400. return this;
  33401. };
  33402. /** @hidden */
  33403. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  33404. var scene = this.getScene();
  33405. var engine = scene.getEngine();
  33406. if (hardwareInstancedRendering) {
  33407. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  33408. }
  33409. else {
  33410. if (batch.renderSelf[subMesh._id]) {
  33411. // Draw
  33412. if (onBeforeDraw) {
  33413. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  33414. }
  33415. this._draw(subMesh, fillMode, this._instanceDataStorage.overridenInstanceCount);
  33416. }
  33417. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  33418. if (visibleInstancesForSubMesh) {
  33419. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  33420. var instance = visibleInstancesForSubMesh[instanceIndex];
  33421. // World
  33422. var world = instance.getWorldMatrix();
  33423. if (onBeforeDraw) {
  33424. onBeforeDraw(true, world, effectiveMaterial);
  33425. }
  33426. // Draw
  33427. this._draw(subMesh, fillMode);
  33428. }
  33429. }
  33430. }
  33431. return this;
  33432. };
  33433. /**
  33434. * 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
  33435. * @param subMesh defines the subMesh to render
  33436. * @param enableAlphaMode defines if alpha mode can be changed
  33437. * @returns the current mesh
  33438. */
  33439. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  33440. if (this._checkOcclusionQuery()) {
  33441. return this;
  33442. }
  33443. var scene = this.getScene();
  33444. // Managing instances
  33445. var batch = this._getInstancesRenderList(subMesh._id);
  33446. if (batch.mustReturn) {
  33447. return this;
  33448. }
  33449. // Checking geometry state
  33450. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  33451. return this;
  33452. }
  33453. if (this._onBeforeRenderObservable) {
  33454. this._onBeforeRenderObservable.notifyObservers(this);
  33455. }
  33456. var engine = scene.getEngine();
  33457. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  33458. // Material
  33459. var material = subMesh.getMaterial();
  33460. if (!material) {
  33461. return this;
  33462. }
  33463. this._effectiveMaterial = material;
  33464. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  33465. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  33466. return this;
  33467. }
  33468. }
  33469. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  33470. return this;
  33471. }
  33472. // Alpha mode
  33473. if (enableAlphaMode) {
  33474. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  33475. }
  33476. for (var _i = 0, _a = scene._beforeRenderingMeshStage; _i < _a.length; _i++) {
  33477. var step = _a[_i];
  33478. step.action(this, subMesh, batch);
  33479. }
  33480. var effect;
  33481. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  33482. effect = subMesh.effect;
  33483. }
  33484. else {
  33485. effect = this._effectiveMaterial.getEffect();
  33486. }
  33487. if (!effect) {
  33488. return this;
  33489. }
  33490. var sideOrientation = this.overrideMaterialSideOrientation;
  33491. if (sideOrientation == null) {
  33492. sideOrientation = this._effectiveMaterial.sideOrientation;
  33493. if (this._getWorldMatrixDeterminant() < 0) {
  33494. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  33495. }
  33496. }
  33497. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  33498. if (this._effectiveMaterial.forceDepthWrite) {
  33499. engine.setDepthWrite(true);
  33500. }
  33501. // Bind
  33502. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  33503. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  33504. this._bind(subMesh, effect, fillMode);
  33505. }
  33506. var world = this.getWorldMatrix();
  33507. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  33508. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  33509. }
  33510. else {
  33511. this._effectiveMaterial.bind(world, this);
  33512. }
  33513. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  33514. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  33515. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  33516. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  33517. }
  33518. // Draw
  33519. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  33520. // Unbind
  33521. this._effectiveMaterial.unbind();
  33522. for (var _b = 0, _c = scene._afterRenderingMeshStage; _b < _c.length; _b++) {
  33523. var step = _c[_b];
  33524. step.action(this, subMesh, batch);
  33525. }
  33526. if (this._onAfterRenderObservable) {
  33527. this._onAfterRenderObservable.notifyObservers(this);
  33528. }
  33529. return this;
  33530. };
  33531. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  33532. if (isInstance && effectiveMaterial) {
  33533. effectiveMaterial.bindOnlyWorldMatrix(world);
  33534. }
  33535. };
  33536. /**
  33537. * Renormalize the mesh and patch it up if there are no weights
  33538. * Similar to normalization by adding the weights compute the reciprocal and multiply all elements, this wil ensure that everything adds to 1.
  33539. * However in the case of zero weights then we set just a single influence to 1.
  33540. * We check in the function for extra's present and if so we use the normalizeSkinWeightsWithExtras rather than the FourWeights version.
  33541. */
  33542. Mesh.prototype.cleanMatrixWeights = function () {
  33543. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33544. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  33545. this.normalizeSkinWeightsAndExtra();
  33546. }
  33547. else {
  33548. this.normalizeSkinFourWeights();
  33549. }
  33550. }
  33551. };
  33552. // faster 4 weight version.
  33553. Mesh.prototype.normalizeSkinFourWeights = function () {
  33554. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33555. var numWeights = matricesWeights.length;
  33556. for (var a = 0; a < numWeights; a += 4) {
  33557. // accumulate weights
  33558. var t = matricesWeights[a] + matricesWeights[a + 1] + matricesWeights[a + 2] + matricesWeights[a + 3];
  33559. // check for invalid weight and just set it to 1.
  33560. if (t === 0) {
  33561. matricesWeights[a] = 1;
  33562. }
  33563. else {
  33564. // renormalize so everything adds to 1 use reciprical
  33565. var recip = 1 / t;
  33566. matricesWeights[a] *= recip;
  33567. matricesWeights[a + 1] *= recip;
  33568. matricesWeights[a + 2] *= recip;
  33569. matricesWeights[a + 3] *= recip;
  33570. }
  33571. }
  33572. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  33573. };
  33574. // handle special case of extra verts. (in theory gltf can handle 12 influences)
  33575. Mesh.prototype.normalizeSkinWeightsAndExtra = function () {
  33576. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  33577. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33578. var numWeights = matricesWeights.length;
  33579. for (var a = 0; a < numWeights; a += 4) {
  33580. // accumulate weights
  33581. var t = matricesWeights[a] + matricesWeights[a + 1] + matricesWeights[a + 2] + matricesWeights[a + 3];
  33582. t += matricesWeightsExtra[a] + matricesWeightsExtra[a + 1] + matricesWeightsExtra[a + 2] + matricesWeightsExtra[a + 3];
  33583. // check for invalid weight and just set it to 1.
  33584. if (t === 0) {
  33585. matricesWeights[a] = 1;
  33586. }
  33587. else {
  33588. // renormalize so everything adds to 1 use reciprical
  33589. var recip = 1 / t;
  33590. matricesWeights[a] *= recip;
  33591. matricesWeights[a + 1] *= recip;
  33592. matricesWeights[a + 2] *= recip;
  33593. matricesWeights[a + 3] *= recip;
  33594. // same goes for extras
  33595. matricesWeightsExtra[a] *= recip;
  33596. matricesWeightsExtra[a + 1] *= recip;
  33597. matricesWeightsExtra[a + 2] *= recip;
  33598. matricesWeightsExtra[a + 3] *= recip;
  33599. }
  33600. }
  33601. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  33602. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsExtra);
  33603. };
  33604. /**
  33605. * ValidateSkinning is used to determine that a mesh has valid skinning data along with skin metrics, if missing weights,
  33606. * or not normalized it is returned as invalid mesh the string can be used for console logs, or on screen messages to let
  33607. * the user know there was an issue with importing the mesh
  33608. * @returns a validation object with skinned, valid and report string
  33609. */
  33610. Mesh.prototype.validateSkinning = function () {
  33611. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  33612. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33613. if (matricesWeights === null || this.skeleton == null) {
  33614. return { skinned: false, valid: true, report: "not skinned" };
  33615. }
  33616. var numWeights = matricesWeights.length;
  33617. var numberNotSorted = 0;
  33618. var missingWeights = 0;
  33619. var maxUsedWeights = 0;
  33620. var numberNotNormalized = 0;
  33621. var numInfluences = matricesWeightsExtra === null ? 4 : 8;
  33622. var usedWeightCounts = new Array();
  33623. for (var a = 0; a <= numInfluences; a++) {
  33624. usedWeightCounts[a] = 0;
  33625. }
  33626. var toleranceEpsilon = 0.001;
  33627. for (var a = 0; a < numWeights; a += 4) {
  33628. var lastWeight = matricesWeights[a];
  33629. var t = lastWeight;
  33630. var usedWeights = t === 0 ? 0 : 1;
  33631. for (var b = 1; b < numInfluences; b++) {
  33632. var d = b < 4 ? matricesWeights[a + b] : matricesWeightsExtra[a + b - 4];
  33633. if (d > lastWeight) {
  33634. numberNotSorted++;
  33635. }
  33636. if (d !== 0) {
  33637. usedWeights++;
  33638. }
  33639. t += d;
  33640. lastWeight = d;
  33641. }
  33642. // count the buffer weights usage
  33643. usedWeightCounts[usedWeights]++;
  33644. // max influences
  33645. if (usedWeights > maxUsedWeights) {
  33646. maxUsedWeights = usedWeights;
  33647. }
  33648. // check for invalid weight and just set it to 1.
  33649. if (t === 0) {
  33650. missingWeights++;
  33651. }
  33652. else {
  33653. // renormalize so everything adds to 1 use reciprical
  33654. var recip = 1 / t;
  33655. var tolerance = 0;
  33656. for (b = 0; b < numInfluences; b++) {
  33657. if (b < 4) {
  33658. tolerance += Math.abs(matricesWeights[a + b] - (matricesWeights[a + b] * recip));
  33659. }
  33660. else {
  33661. tolerance += Math.abs(matricesWeightsExtra[a + b - 4] - (matricesWeightsExtra[a + b - 4] * recip));
  33662. }
  33663. }
  33664. // arbitary epsilon value for dicdating not normalized
  33665. if (tolerance > toleranceEpsilon) {
  33666. numberNotNormalized++;
  33667. }
  33668. }
  33669. }
  33670. // validate bone indices are in range of the skeleton
  33671. var numBones = this.skeleton.bones.length;
  33672. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33673. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  33674. var numBadBoneIndices = 0;
  33675. for (var a = 0; a < numWeights; a++) {
  33676. for (var b = 0; b < numInfluences; b++) {
  33677. var index = b < 4 ? matricesIndices[b] : matricesIndicesExtra[b - 4];
  33678. if (index >= numBones || index < 0) {
  33679. numBadBoneIndices++;
  33680. }
  33681. }
  33682. }
  33683. // log mesh stats
  33684. var output = "Number of Weights = " + numWeights / 4 + "\nMaximum influences = " + maxUsedWeights +
  33685. "\nMissing Weights = " + missingWeights + "\nNot Sorted = " + numberNotSorted +
  33686. "\nNot Normalized = " + numberNotNormalized + "\nWeightCounts = [" + usedWeightCounts + "]" +
  33687. "\nNumber of bones = " + numBones + "\nBad Bone Indices = " + numBadBoneIndices;
  33688. return { skinned: true, valid: missingWeights === 0 && numberNotNormalized === 0 && numBadBoneIndices === 0, report: output };
  33689. };
  33690. /** @hidden */
  33691. Mesh.prototype._checkDelayState = function () {
  33692. var scene = this.getScene();
  33693. if (this._geometry) {
  33694. this._geometry.load(scene);
  33695. }
  33696. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  33697. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  33698. this._queueLoad(scene);
  33699. }
  33700. return this;
  33701. };
  33702. Mesh.prototype._queueLoad = function (scene) {
  33703. var _this = this;
  33704. scene._addPendingData(this);
  33705. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  33706. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  33707. if (data instanceof ArrayBuffer) {
  33708. _this._delayLoadingFunction(data, _this);
  33709. }
  33710. else {
  33711. _this._delayLoadingFunction(JSON.parse(data), _this);
  33712. }
  33713. _this.instances.forEach(function (instance) {
  33714. instance._syncSubMeshes();
  33715. });
  33716. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33717. scene._removePendingData(_this);
  33718. }, function () { }, scene.database, getBinaryData);
  33719. return this;
  33720. };
  33721. /**
  33722. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  33723. * A mesh is in the frustum if its bounding box intersects the frustum
  33724. * @param frustumPlanes defines the frustum to test
  33725. * @returns true if the mesh is in the frustum planes
  33726. */
  33727. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  33728. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  33729. return false;
  33730. }
  33731. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  33732. return false;
  33733. }
  33734. this._checkDelayState();
  33735. return true;
  33736. };
  33737. /**
  33738. * Sets the mesh material by the material or multiMaterial `id` property
  33739. * @param id is a string identifying the material or the multiMaterial
  33740. * @returns the current mesh
  33741. */
  33742. Mesh.prototype.setMaterialByID = function (id) {
  33743. var materials = this.getScene().materials;
  33744. var index;
  33745. for (index = materials.length - 1; index > -1; index--) {
  33746. if (materials[index].id === id) {
  33747. this.material = materials[index];
  33748. return this;
  33749. }
  33750. }
  33751. // Multi
  33752. var multiMaterials = this.getScene().multiMaterials;
  33753. for (index = multiMaterials.length - 1; index > -1; index--) {
  33754. if (multiMaterials[index].id === id) {
  33755. this.material = multiMaterials[index];
  33756. return this;
  33757. }
  33758. }
  33759. return this;
  33760. };
  33761. /**
  33762. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  33763. * @returns an array of IAnimatable
  33764. */
  33765. Mesh.prototype.getAnimatables = function () {
  33766. var results = new Array();
  33767. if (this.material) {
  33768. results.push(this.material);
  33769. }
  33770. if (this.skeleton) {
  33771. results.push(this.skeleton);
  33772. }
  33773. return results;
  33774. };
  33775. /**
  33776. * Modifies the mesh geometry according to the passed transformation matrix.
  33777. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  33778. * The mesh normals are modified using the same transformation.
  33779. * Note that, under the hood, this method sets a new VertexBuffer each call.
  33780. * @param transform defines the transform matrix to use
  33781. * @see http://doc.babylonjs.com/resources/baking_transformations
  33782. * @returns the current mesh
  33783. */
  33784. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  33785. // Position
  33786. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33787. return this;
  33788. }
  33789. var submeshes = this.subMeshes.splice(0);
  33790. this._resetPointsArrayCache();
  33791. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33792. var temp = new Array();
  33793. var index;
  33794. for (index = 0; index < data.length; index += 3) {
  33795. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  33796. }
  33797. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  33798. // Normals
  33799. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33800. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33801. temp = [];
  33802. for (index = 0; index < data.length; index += 3) {
  33803. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  33804. }
  33805. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  33806. }
  33807. // flip faces?
  33808. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  33809. this.flipFaces();
  33810. }
  33811. // Restore submeshes
  33812. this.releaseSubMeshes();
  33813. this.subMeshes = submeshes;
  33814. return this;
  33815. };
  33816. /**
  33817. * Modifies the mesh geometry according to its own current World Matrix.
  33818. * The mesh World Matrix is then reset.
  33819. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  33820. * Note that, under the hood, this method sets a new VertexBuffer each call.
  33821. * @see http://doc.babylonjs.com/resources/baking_transformations
  33822. * @returns the current mesh
  33823. */
  33824. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  33825. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  33826. this.scaling.copyFromFloats(1, 1, 1);
  33827. this.position.copyFromFloats(0, 0, 0);
  33828. this.rotation.copyFromFloats(0, 0, 0);
  33829. //only if quaternion is already set
  33830. if (this.rotationQuaternion) {
  33831. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  33832. }
  33833. this._worldMatrix = BABYLON.Matrix.Identity();
  33834. return this;
  33835. };
  33836. Object.defineProperty(Mesh.prototype, "_positions", {
  33837. // Cache
  33838. /** @hidden */
  33839. get: function () {
  33840. if (this._geometry) {
  33841. return this._geometry._positions;
  33842. }
  33843. return null;
  33844. },
  33845. enumerable: true,
  33846. configurable: true
  33847. });
  33848. /** @hidden */
  33849. Mesh.prototype._resetPointsArrayCache = function () {
  33850. if (this._geometry) {
  33851. this._geometry._resetPointsArrayCache();
  33852. }
  33853. return this;
  33854. };
  33855. /** @hidden */
  33856. Mesh.prototype._generatePointsArray = function () {
  33857. if (this._geometry) {
  33858. return this._geometry._generatePointsArray();
  33859. }
  33860. return false;
  33861. };
  33862. /**
  33863. * Returns a new Mesh object generated from the current mesh properties.
  33864. * This method must not get confused with createInstance()
  33865. * @param name is a string, the name given to the new mesh
  33866. * @param newParent can be any Node object (default `null`)
  33867. * @param doNotCloneChildren allows/denies the recursive cloning of the original mesh children if any (default `false`)
  33868. * @param clonePhysicsImpostor allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any (default `true`)
  33869. * @returns a new mesh
  33870. */
  33871. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  33872. if (name === void 0) { name = ""; }
  33873. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  33874. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  33875. };
  33876. /**
  33877. * Releases resources associated with this mesh.
  33878. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  33879. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  33880. */
  33881. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  33882. var _this = this;
  33883. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  33884. this.morphTargetManager = null;
  33885. if (this._geometry) {
  33886. this._geometry.releaseForMesh(this, true);
  33887. }
  33888. if (this._onBeforeDrawObservable) {
  33889. this._onBeforeDrawObservable.clear();
  33890. }
  33891. if (this._onBeforeRenderObservable) {
  33892. this._onBeforeRenderObservable.clear();
  33893. }
  33894. if (this._onAfterRenderObservable) {
  33895. this._onAfterRenderObservable.clear();
  33896. }
  33897. // Sources
  33898. var meshes = this.getScene().meshes;
  33899. meshes.forEach(function (abstractMesh) {
  33900. var mesh = abstractMesh;
  33901. if (mesh._source && mesh._source === _this) {
  33902. mesh._source = null;
  33903. }
  33904. });
  33905. this._source = null;
  33906. // Instances
  33907. if (this._instanceDataStorage.instancesBuffer) {
  33908. this._instanceDataStorage.instancesBuffer.dispose();
  33909. this._instanceDataStorage.instancesBuffer = null;
  33910. }
  33911. while (this.instances.length) {
  33912. this.instances[0].dispose();
  33913. }
  33914. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  33915. };
  33916. /**
  33917. * Modifies the mesh geometry according to a displacement map.
  33918. * 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.
  33919. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  33920. * @param url is a string, the URL from the image file is to be downloaded.
  33921. * @param minHeight is the lower limit of the displacement.
  33922. * @param maxHeight is the upper limit of the displacement.
  33923. * @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.
  33924. * @param uvOffset is an optional vector2 used to offset UV.
  33925. * @param uvScale is an optional vector2 used to scale UV.
  33926. * @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.
  33927. * @returns the Mesh.
  33928. */
  33929. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate) {
  33930. var _this = this;
  33931. if (forceUpdate === void 0) { forceUpdate = false; }
  33932. var scene = this.getScene();
  33933. var onload = function (img) {
  33934. // Getting height map data
  33935. var canvas = document.createElement("canvas");
  33936. var context = canvas.getContext("2d");
  33937. var heightMapWidth = img.width;
  33938. var heightMapHeight = img.height;
  33939. canvas.width = heightMapWidth;
  33940. canvas.height = heightMapHeight;
  33941. context.drawImage(img, 0, 0);
  33942. // Create VertexData from map data
  33943. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  33944. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  33945. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
  33946. //execute success callback, if set
  33947. if (onSuccess) {
  33948. onSuccess(_this);
  33949. }
  33950. };
  33951. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  33952. return this;
  33953. };
  33954. /**
  33955. * Modifies the mesh geometry according to a displacementMap buffer.
  33956. * 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.
  33957. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  33958. * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  33959. * @param heightMapWidth is the width of the buffer image.
  33960. * @param heightMapHeight is the height of the buffer image.
  33961. * @param minHeight is the lower limit of the displacement.
  33962. * @param maxHeight is the upper limit of the displacement.
  33963. * @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.
  33964. * @param uvOffset is an optional vector2 used to offset UV.
  33965. * @param uvScale is an optional vector2 used to scale UV.
  33966. * @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.
  33967. * @returns the Mesh.
  33968. */
  33969. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate) {
  33970. if (forceUpdate === void 0) { forceUpdate = false; }
  33971. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  33972. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  33973. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33974. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  33975. return this;
  33976. }
  33977. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, true, true);
  33978. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33979. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33980. var position = BABYLON.Vector3.Zero();
  33981. var normal = BABYLON.Vector3.Zero();
  33982. var uv = BABYLON.Vector2.Zero();
  33983. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  33984. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  33985. for (var index = 0; index < positions.length; index += 3) {
  33986. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  33987. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  33988. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  33989. // Compute height
  33990. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  33991. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  33992. var pos = (u + v * heightMapWidth) * 4;
  33993. var r = buffer[pos] / 255.0;
  33994. var g = buffer[pos + 1] / 255.0;
  33995. var b = buffer[pos + 2] / 255.0;
  33996. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  33997. normal.normalize();
  33998. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  33999. position = position.add(normal);
  34000. position.toArray(positions, index);
  34001. }
  34002. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  34003. if (forceUpdate) {
  34004. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  34005. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  34006. }
  34007. else {
  34008. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  34009. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  34010. }
  34011. return this;
  34012. };
  34013. /**
  34014. * Modify the mesh to get a flat shading rendering.
  34015. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  34016. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  34017. * @returns current mesh
  34018. */
  34019. Mesh.prototype.convertToFlatShadedMesh = function () {
  34020. var kinds = this.getVerticesDataKinds();
  34021. var vbs = {};
  34022. var data = {};
  34023. var newdata = {};
  34024. var updatableNormals = false;
  34025. var kindIndex;
  34026. var kind;
  34027. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34028. kind = kinds[kindIndex];
  34029. var vertexBuffer = this.getVertexBuffer(kind);
  34030. if (kind === BABYLON.VertexBuffer.NormalKind) {
  34031. updatableNormals = vertexBuffer.isUpdatable();
  34032. kinds.splice(kindIndex, 1);
  34033. kindIndex--;
  34034. continue;
  34035. }
  34036. vbs[kind] = vertexBuffer;
  34037. data[kind] = vbs[kind].getData();
  34038. newdata[kind] = [];
  34039. }
  34040. // Save previous submeshes
  34041. var previousSubmeshes = this.subMeshes.slice(0);
  34042. var indices = this.getIndices();
  34043. var totalIndices = this.getTotalIndices();
  34044. // Generating unique vertices per face
  34045. var index;
  34046. for (index = 0; index < totalIndices; index++) {
  34047. var vertexIndex = indices[index];
  34048. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34049. kind = kinds[kindIndex];
  34050. var stride = vbs[kind].getStrideSize();
  34051. for (var offset = 0; offset < stride; offset++) {
  34052. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  34053. }
  34054. }
  34055. }
  34056. // Updating faces & normal
  34057. var normals = [];
  34058. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  34059. for (index = 0; index < totalIndices; index += 3) {
  34060. indices[index] = index;
  34061. indices[index + 1] = index + 1;
  34062. indices[index + 2] = index + 2;
  34063. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  34064. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  34065. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  34066. var p1p2 = p1.subtract(p2);
  34067. var p3p2 = p3.subtract(p2);
  34068. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  34069. // Store same normals for every vertex
  34070. for (var localIndex = 0; localIndex < 3; localIndex++) {
  34071. normals.push(normal.x);
  34072. normals.push(normal.y);
  34073. normals.push(normal.z);
  34074. }
  34075. }
  34076. this.setIndices(indices);
  34077. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  34078. // Updating vertex buffers
  34079. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34080. kind = kinds[kindIndex];
  34081. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  34082. }
  34083. // Updating submeshes
  34084. this.releaseSubMeshes();
  34085. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  34086. var previousOne = previousSubmeshes[submeshIndex];
  34087. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  34088. }
  34089. this.synchronizeInstances();
  34090. return this;
  34091. };
  34092. /**
  34093. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  34094. * In other words, more vertices, no more indices and a single bigger VBO.
  34095. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  34096. * @returns current mesh
  34097. */
  34098. Mesh.prototype.convertToUnIndexedMesh = function () {
  34099. var kinds = this.getVerticesDataKinds();
  34100. var vbs = {};
  34101. var data = {};
  34102. var newdata = {};
  34103. var kindIndex;
  34104. var kind;
  34105. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34106. kind = kinds[kindIndex];
  34107. var vertexBuffer = this.getVertexBuffer(kind);
  34108. vbs[kind] = vertexBuffer;
  34109. data[kind] = vbs[kind].getData();
  34110. newdata[kind] = [];
  34111. }
  34112. // Save previous submeshes
  34113. var previousSubmeshes = this.subMeshes.slice(0);
  34114. var indices = this.getIndices();
  34115. var totalIndices = this.getTotalIndices();
  34116. // Generating unique vertices per face
  34117. var index;
  34118. for (index = 0; index < totalIndices; index++) {
  34119. var vertexIndex = indices[index];
  34120. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34121. kind = kinds[kindIndex];
  34122. var stride = vbs[kind].getStrideSize();
  34123. for (var offset = 0; offset < stride; offset++) {
  34124. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  34125. }
  34126. }
  34127. }
  34128. // Updating indices
  34129. for (index = 0; index < totalIndices; index += 3) {
  34130. indices[index] = index;
  34131. indices[index + 1] = index + 1;
  34132. indices[index + 2] = index + 2;
  34133. }
  34134. this.setIndices(indices);
  34135. // Updating vertex buffers
  34136. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34137. kind = kinds[kindIndex];
  34138. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  34139. }
  34140. // Updating submeshes
  34141. this.releaseSubMeshes();
  34142. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  34143. var previousOne = previousSubmeshes[submeshIndex];
  34144. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  34145. }
  34146. this._unIndexed = true;
  34147. this.synchronizeInstances();
  34148. return this;
  34149. };
  34150. /**
  34151. * Inverses facet orientations.
  34152. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  34153. * @param flipNormals will also inverts the normals
  34154. * @returns current mesh
  34155. */
  34156. Mesh.prototype.flipFaces = function (flipNormals) {
  34157. if (flipNormals === void 0) { flipNormals = false; }
  34158. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  34159. var i;
  34160. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  34161. for (i = 0; i < vertex_data.normals.length; i++) {
  34162. vertex_data.normals[i] *= -1;
  34163. }
  34164. }
  34165. if (vertex_data.indices) {
  34166. var temp;
  34167. for (i = 0; i < vertex_data.indices.length; i += 3) {
  34168. // reassign indices
  34169. temp = vertex_data.indices[i + 1];
  34170. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  34171. vertex_data.indices[i + 2] = temp;
  34172. }
  34173. }
  34174. vertex_data.applyToMesh(this);
  34175. return this;
  34176. };
  34177. // Instances
  34178. /**
  34179. * Creates a new InstancedMesh object from the mesh model.
  34180. * Warning : this method is not supported for Line mesh and LineSystem
  34181. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  34182. * @param name defines the name of the new instance
  34183. * @returns a new InstancedMesh
  34184. */
  34185. Mesh.prototype.createInstance = function (name) {
  34186. return new BABYLON.InstancedMesh(name, this);
  34187. };
  34188. /**
  34189. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  34190. * After this call, all the mesh instances have the same submeshes than the current mesh.
  34191. * @returns the current mesh
  34192. */
  34193. Mesh.prototype.synchronizeInstances = function () {
  34194. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  34195. var instance = this.instances[instanceIndex];
  34196. instance._syncSubMeshes();
  34197. }
  34198. return this;
  34199. };
  34200. /**
  34201. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  34202. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  34203. * This should be used together with the simplification to avoid disappearing triangles.
  34204. * @param successCallback an optional success callback to be called after the optimization finished.
  34205. * @returns the current mesh
  34206. */
  34207. Mesh.prototype.optimizeIndices = function (successCallback) {
  34208. var _this = this;
  34209. var indices = this.getIndices();
  34210. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34211. if (!positions || !indices) {
  34212. return this;
  34213. }
  34214. var vectorPositions = new Array();
  34215. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  34216. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  34217. }
  34218. var dupes = new Array();
  34219. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  34220. var realPos = vectorPositions.length - 1 - iteration;
  34221. var testedPosition = vectorPositions[realPos];
  34222. for (var j = 0; j < realPos; ++j) {
  34223. var againstPosition = vectorPositions[j];
  34224. if (testedPosition.equals(againstPosition)) {
  34225. dupes[realPos] = j;
  34226. break;
  34227. }
  34228. }
  34229. }, function () {
  34230. for (var i = 0; i < indices.length; ++i) {
  34231. indices[i] = dupes[indices[i]] || indices[i];
  34232. }
  34233. //indices are now reordered
  34234. var originalSubMeshes = _this.subMeshes.slice(0);
  34235. _this.setIndices(indices);
  34236. _this.subMeshes = originalSubMeshes;
  34237. if (successCallback) {
  34238. successCallback(_this);
  34239. }
  34240. });
  34241. return this;
  34242. };
  34243. /**
  34244. * Serialize current mesh
  34245. * @param serializationObject defines the object which will receive the serialization data
  34246. */
  34247. Mesh.prototype.serialize = function (serializationObject) {
  34248. serializationObject.name = this.name;
  34249. serializationObject.id = this.id;
  34250. serializationObject.type = this.getClassName();
  34251. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  34252. serializationObject.tags = BABYLON.Tags.GetTags(this);
  34253. }
  34254. serializationObject.position = this.position.asArray();
  34255. if (this.rotationQuaternion) {
  34256. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  34257. }
  34258. else if (this.rotation) {
  34259. serializationObject.rotation = this.rotation.asArray();
  34260. }
  34261. serializationObject.scaling = this.scaling.asArray();
  34262. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  34263. serializationObject.isEnabled = this.isEnabled(false);
  34264. serializationObject.isVisible = this.isVisible;
  34265. serializationObject.infiniteDistance = this.infiniteDistance;
  34266. serializationObject.pickable = this.isPickable;
  34267. serializationObject.receiveShadows = this.receiveShadows;
  34268. serializationObject.billboardMode = this.billboardMode;
  34269. serializationObject.visibility = this.visibility;
  34270. serializationObject.checkCollisions = this.checkCollisions;
  34271. serializationObject.isBlocker = this.isBlocker;
  34272. // Parent
  34273. if (this.parent) {
  34274. serializationObject.parentId = this.parent.id;
  34275. }
  34276. // Geometry
  34277. serializationObject.isUnIndexed = this.isUnIndexed;
  34278. var geometry = this._geometry;
  34279. if (geometry) {
  34280. var geometryId = geometry.id;
  34281. serializationObject.geometryId = geometryId;
  34282. // SubMeshes
  34283. serializationObject.subMeshes = [];
  34284. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  34285. var subMesh = this.subMeshes[subIndex];
  34286. serializationObject.subMeshes.push({
  34287. materialIndex: subMesh.materialIndex,
  34288. verticesStart: subMesh.verticesStart,
  34289. verticesCount: subMesh.verticesCount,
  34290. indexStart: subMesh.indexStart,
  34291. indexCount: subMesh.indexCount
  34292. });
  34293. }
  34294. }
  34295. // Material
  34296. if (this.material) {
  34297. serializationObject.materialId = this.material.id;
  34298. }
  34299. else {
  34300. this.material = null;
  34301. }
  34302. // Morph targets
  34303. if (this.morphTargetManager) {
  34304. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  34305. }
  34306. // Skeleton
  34307. if (this.skeleton) {
  34308. serializationObject.skeletonId = this.skeleton.id;
  34309. }
  34310. // Physics
  34311. //TODO implement correct serialization for physics impostors.
  34312. var impostor = this.getPhysicsImpostor();
  34313. if (impostor) {
  34314. serializationObject.physicsMass = impostor.getParam("mass");
  34315. serializationObject.physicsFriction = impostor.getParam("friction");
  34316. serializationObject.physicsRestitution = impostor.getParam("mass");
  34317. serializationObject.physicsImpostor = impostor.type;
  34318. }
  34319. // Metadata
  34320. if (this.metadata) {
  34321. serializationObject.metadata = this.metadata;
  34322. }
  34323. // Instances
  34324. serializationObject.instances = [];
  34325. for (var index = 0; index < this.instances.length; index++) {
  34326. var instance = this.instances[index];
  34327. if (instance.doNotSerialize) {
  34328. continue;
  34329. }
  34330. var serializationInstance = {
  34331. name: instance.name,
  34332. id: instance.id,
  34333. position: instance.position.asArray(),
  34334. scaling: instance.scaling.asArray()
  34335. };
  34336. if (instance.parent) {
  34337. serializationInstance.parentId = instance.parent.id;
  34338. }
  34339. if (instance.rotationQuaternion) {
  34340. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  34341. }
  34342. else if (instance.rotation) {
  34343. serializationInstance.rotation = instance.rotation.asArray();
  34344. }
  34345. serializationObject.instances.push(serializationInstance);
  34346. // Animations
  34347. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  34348. serializationInstance.ranges = instance.serializeAnimationRanges();
  34349. }
  34350. //
  34351. // Animations
  34352. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  34353. serializationObject.ranges = this.serializeAnimationRanges();
  34354. // Layer mask
  34355. serializationObject.layerMask = this.layerMask;
  34356. // Alpha
  34357. serializationObject.alphaIndex = this.alphaIndex;
  34358. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  34359. // Overlay
  34360. serializationObject.overlayAlpha = this.overlayAlpha;
  34361. serializationObject.overlayColor = this.overlayColor.asArray();
  34362. serializationObject.renderOverlay = this.renderOverlay;
  34363. // Fog
  34364. serializationObject.applyFog = this.applyFog;
  34365. // Action Manager
  34366. if (this.actionManager) {
  34367. serializationObject.actions = this.actionManager.serialize(this.name);
  34368. }
  34369. };
  34370. /** @hidden */
  34371. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  34372. if (!this.geometry) {
  34373. return;
  34374. }
  34375. this._markSubMeshesAsAttributesDirty();
  34376. var morphTargetManager = this._morphTargetManager;
  34377. if (morphTargetManager && morphTargetManager.vertexCount) {
  34378. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  34379. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  34380. this.morphTargetManager = null;
  34381. return;
  34382. }
  34383. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  34384. var morphTarget = morphTargetManager.getActiveTarget(index);
  34385. var positions = morphTarget.getPositions();
  34386. if (!positions) {
  34387. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  34388. return;
  34389. }
  34390. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  34391. var normals = morphTarget.getNormals();
  34392. if (normals) {
  34393. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  34394. }
  34395. var tangents = morphTarget.getTangents();
  34396. if (tangents) {
  34397. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  34398. }
  34399. }
  34400. }
  34401. else {
  34402. var index = 0;
  34403. // Positions
  34404. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  34405. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  34406. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  34407. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  34408. }
  34409. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  34410. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  34411. }
  34412. index++;
  34413. }
  34414. }
  34415. };
  34416. // Statics
  34417. /**
  34418. * Returns a new Mesh object parsed from the source provided.
  34419. * @param parsedMesh is the source
  34420. * @param scene defines the hosting scene
  34421. * @param rootUrl is the root URL to prefix the `delayLoadingFile` property with
  34422. * @returns a new Mesh
  34423. */
  34424. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  34425. var mesh;
  34426. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  34427. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  34428. }
  34429. else {
  34430. mesh = new Mesh(parsedMesh.name, scene);
  34431. }
  34432. mesh.id = parsedMesh.id;
  34433. if (BABYLON.Tags) {
  34434. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  34435. }
  34436. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  34437. if (parsedMesh.metadata !== undefined) {
  34438. mesh.metadata = parsedMesh.metadata;
  34439. }
  34440. if (parsedMesh.rotationQuaternion) {
  34441. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  34442. }
  34443. else if (parsedMesh.rotation) {
  34444. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  34445. }
  34446. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  34447. if (parsedMesh.localMatrix) {
  34448. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  34449. }
  34450. else if (parsedMesh.pivotMatrix) {
  34451. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  34452. }
  34453. mesh.setEnabled(parsedMesh.isEnabled);
  34454. mesh.isVisible = parsedMesh.isVisible;
  34455. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  34456. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  34457. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  34458. if (parsedMesh.applyFog !== undefined) {
  34459. mesh.applyFog = parsedMesh.applyFog;
  34460. }
  34461. if (parsedMesh.pickable !== undefined) {
  34462. mesh.isPickable = parsedMesh.pickable;
  34463. }
  34464. if (parsedMesh.alphaIndex !== undefined) {
  34465. mesh.alphaIndex = parsedMesh.alphaIndex;
  34466. }
  34467. mesh.receiveShadows = parsedMesh.receiveShadows;
  34468. mesh.billboardMode = parsedMesh.billboardMode;
  34469. if (parsedMesh.visibility !== undefined) {
  34470. mesh.visibility = parsedMesh.visibility;
  34471. }
  34472. mesh.checkCollisions = parsedMesh.checkCollisions;
  34473. if (parsedMesh.isBlocker !== undefined) {
  34474. mesh.isBlocker = parsedMesh.isBlocker;
  34475. }
  34476. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  34477. // freezeWorldMatrix
  34478. if (parsedMesh.freezeWorldMatrix) {
  34479. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  34480. }
  34481. // Parent
  34482. if (parsedMesh.parentId) {
  34483. mesh._waitingParentId = parsedMesh.parentId;
  34484. }
  34485. // Actions
  34486. if (parsedMesh.actions !== undefined) {
  34487. mesh._waitingActions = parsedMesh.actions;
  34488. }
  34489. // Overlay
  34490. if (parsedMesh.overlayAlpha !== undefined) {
  34491. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  34492. }
  34493. if (parsedMesh.overlayColor !== undefined) {
  34494. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  34495. }
  34496. if (parsedMesh.renderOverlay !== undefined) {
  34497. mesh.renderOverlay = parsedMesh.renderOverlay;
  34498. }
  34499. // Geometry
  34500. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  34501. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  34502. if (parsedMesh.delayLoadingFile) {
  34503. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  34504. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  34505. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  34506. if (parsedMesh._binaryInfo) {
  34507. mesh._binaryInfo = parsedMesh._binaryInfo;
  34508. }
  34509. mesh._delayInfo = [];
  34510. if (parsedMesh.hasUVs) {
  34511. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  34512. }
  34513. if (parsedMesh.hasUVs2) {
  34514. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  34515. }
  34516. if (parsedMesh.hasUVs3) {
  34517. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  34518. }
  34519. if (parsedMesh.hasUVs4) {
  34520. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  34521. }
  34522. if (parsedMesh.hasUVs5) {
  34523. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  34524. }
  34525. if (parsedMesh.hasUVs6) {
  34526. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  34527. }
  34528. if (parsedMesh.hasColors) {
  34529. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  34530. }
  34531. if (parsedMesh.hasMatricesIndices) {
  34532. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34533. }
  34534. if (parsedMesh.hasMatricesWeights) {
  34535. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34536. }
  34537. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  34538. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  34539. mesh._checkDelayState();
  34540. }
  34541. }
  34542. else {
  34543. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  34544. }
  34545. // Material
  34546. if (parsedMesh.materialId) {
  34547. mesh.setMaterialByID(parsedMesh.materialId);
  34548. }
  34549. else {
  34550. mesh.material = null;
  34551. }
  34552. // Morph targets
  34553. if (parsedMesh.morphTargetManagerId > -1) {
  34554. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  34555. }
  34556. // Skeleton
  34557. if (parsedMesh.skeletonId > -1) {
  34558. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  34559. if (parsedMesh.numBoneInfluencers) {
  34560. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  34561. }
  34562. }
  34563. // Animations
  34564. if (parsedMesh.animations) {
  34565. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  34566. var parsedAnimation = parsedMesh.animations[animationIndex];
  34567. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  34568. }
  34569. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  34570. }
  34571. if (parsedMesh.autoAnimate) {
  34572. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  34573. }
  34574. // Layer Mask
  34575. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  34576. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  34577. }
  34578. else {
  34579. mesh.layerMask = 0x0FFFFFFF;
  34580. }
  34581. // Physics
  34582. if (parsedMesh.physicsImpostor) {
  34583. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  34584. mass: parsedMesh.physicsMass,
  34585. friction: parsedMesh.physicsFriction,
  34586. restitution: parsedMesh.physicsRestitution
  34587. }, scene);
  34588. }
  34589. // Instances
  34590. if (parsedMesh.instances) {
  34591. for (var index = 0; index < parsedMesh.instances.length; index++) {
  34592. var parsedInstance = parsedMesh.instances[index];
  34593. var instance = mesh.createInstance(parsedInstance.name);
  34594. if (parsedInstance.id) {
  34595. instance.id = parsedInstance.id;
  34596. }
  34597. if (BABYLON.Tags) {
  34598. if (parsedInstance.tags) {
  34599. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  34600. }
  34601. else {
  34602. BABYLON.Tags.AddTagsTo(instance, parsedMesh.tags);
  34603. }
  34604. }
  34605. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  34606. if (parsedInstance.parentId) {
  34607. instance._waitingParentId = parsedInstance.parentId;
  34608. }
  34609. if (parsedInstance.rotationQuaternion) {
  34610. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  34611. }
  34612. else if (parsedInstance.rotation) {
  34613. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  34614. }
  34615. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  34616. if (parsedInstance.checkCollisions != undefined && parsedInstance.checkCollisions != null) {
  34617. instance.checkCollisions = parsedInstance.checkCollisions;
  34618. }
  34619. if (parsedInstance.pickable != undefined && parsedInstance.pickable != null) {
  34620. instance.isPickable = parsedInstance.pickable;
  34621. }
  34622. if (parsedInstance.showBoundingBox != undefined && parsedInstance.showBoundingBox != null) {
  34623. instance.showBoundingBox = parsedInstance.showBoundingBox;
  34624. }
  34625. if (parsedInstance.showSubMeshesBoundingBox != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  34626. instance.showSubMeshesBoundingBox = parsedInstance.showSubMeshesBoundingBox;
  34627. }
  34628. if (parsedInstance.alphaIndex != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  34629. instance.alphaIndex = parsedInstance.alphaIndex;
  34630. }
  34631. // Physics
  34632. if (parsedInstance.physicsImpostor) {
  34633. instance.physicsImpostor = new BABYLON.PhysicsImpostor(instance, parsedInstance.physicsImpostor, {
  34634. mass: parsedInstance.physicsMass,
  34635. friction: parsedInstance.physicsFriction,
  34636. restitution: parsedInstance.physicsRestitution
  34637. }, scene);
  34638. }
  34639. // Animation
  34640. if (parsedInstance.animations) {
  34641. for (animationIndex = 0; animationIndex < parsedInstance.animations.length; animationIndex++) {
  34642. parsedAnimation = parsedInstance.animations[animationIndex];
  34643. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  34644. }
  34645. BABYLON.Node.ParseAnimationRanges(instance, parsedInstance, scene);
  34646. if (parsedInstance.autoAnimate) {
  34647. scene.beginAnimation(instance, parsedInstance.autoAnimateFrom, parsedInstance.autoAnimateTo, parsedInstance.autoAnimateLoop, parsedInstance.autoAnimateSpeed || 1.0);
  34648. }
  34649. }
  34650. }
  34651. }
  34652. return mesh;
  34653. };
  34654. /**
  34655. * Creates a ribbon mesh. Please consider using the same method from the MeshBuilder class instead
  34656. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  34657. * @param name defines the name of the mesh to create
  34658. * @param pathArray is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  34659. * @param closeArray creates a seam between the first and the last paths of the path array (default is false)
  34660. * @param closePath creates a seam between the first and the last points of each path of the path array
  34661. * @param offset is taken in account only if the `pathArray` is containing a single path
  34662. * @param scene defines the hosting scene
  34663. * @param updatable defines if the mesh must be flagged as updatable
  34664. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34665. * @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)
  34666. * @returns a new Mesh
  34667. */
  34668. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  34669. if (closeArray === void 0) { closeArray = false; }
  34670. if (updatable === void 0) { updatable = false; }
  34671. return BABYLON.MeshBuilder.CreateRibbon(name, {
  34672. pathArray: pathArray,
  34673. closeArray: closeArray,
  34674. closePath: closePath,
  34675. offset: offset,
  34676. updatable: updatable,
  34677. sideOrientation: sideOrientation,
  34678. instance: instance
  34679. }, scene);
  34680. };
  34681. /**
  34682. * Creates a plane polygonal mesh. By default, this is a disc. Please consider using the same method from the MeshBuilder class instead
  34683. * @param name defines the name of the mesh to create
  34684. * @param radius sets the radius size (float) of the polygon (default 0.5)
  34685. * @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
  34686. * @param scene defines the hosting scene
  34687. * @param updatable defines if the mesh must be flagged as updatable
  34688. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34689. * @returns a new Mesh
  34690. */
  34691. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  34692. if (scene === void 0) { scene = null; }
  34693. var options = {
  34694. radius: radius,
  34695. tessellation: tessellation,
  34696. sideOrientation: sideOrientation,
  34697. updatable: updatable
  34698. };
  34699. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  34700. };
  34701. /**
  34702. * Creates a box mesh. Please consider using the same method from the MeshBuilder class instead
  34703. * @param name defines the name of the mesh to create
  34704. * @param size sets the size (float) of each box side (default 1)
  34705. * @param scene defines the hosting scene
  34706. * @param updatable defines if the mesh must be flagged as updatable
  34707. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34708. * @returns a new Mesh
  34709. */
  34710. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  34711. if (scene === void 0) { scene = null; }
  34712. var options = {
  34713. size: size,
  34714. sideOrientation: sideOrientation,
  34715. updatable: updatable
  34716. };
  34717. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  34718. };
  34719. /**
  34720. * Creates a sphere mesh. Please consider using the same method from the MeshBuilder class instead
  34721. * @param name defines the name of the mesh to create
  34722. * @param segments sets the sphere number of horizontal stripes (positive integer, default 32)
  34723. * @param diameter sets the diameter size (float) of the sphere (default 1)
  34724. * @param scene defines the hosting scene
  34725. * @param updatable defines if the mesh must be flagged as updatable
  34726. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34727. * @returns a new Mesh
  34728. */
  34729. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  34730. var options = {
  34731. segments: segments,
  34732. diameterX: diameter,
  34733. diameterY: diameter,
  34734. diameterZ: diameter,
  34735. sideOrientation: sideOrientation,
  34736. updatable: updatable
  34737. };
  34738. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  34739. };
  34740. /**
  34741. * Creates a cylinder or a cone mesh. Please consider using the same method from the MeshBuilder class instead
  34742. * @param name defines the name of the mesh to create
  34743. * @param height sets the height size (float) of the cylinder/cone (float, default 2)
  34744. * @param diameterTop set the top cap diameter (floats, default 1)
  34745. * @param diameterBottom set the bottom cap diameter (floats, default 1). This value can't be zero
  34746. * @param tessellation sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance
  34747. * @param subdivisions sets the number of rings along the cylinder height (positive integer, default 1)
  34748. * @param scene defines the hosting scene
  34749. * @param updatable defines if the mesh must be flagged as updatable
  34750. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34751. * @returns a new Mesh
  34752. */
  34753. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  34754. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  34755. if (scene !== undefined) {
  34756. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  34757. updatable = scene;
  34758. }
  34759. scene = subdivisions;
  34760. subdivisions = 1;
  34761. }
  34762. var options = {
  34763. height: height,
  34764. diameterTop: diameterTop,
  34765. diameterBottom: diameterBottom,
  34766. tessellation: tessellation,
  34767. subdivisions: subdivisions,
  34768. sideOrientation: sideOrientation,
  34769. updatable: updatable
  34770. };
  34771. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  34772. };
  34773. // Torus (Code from SharpDX.org)
  34774. /**
  34775. * Creates a torus mesh. Please consider using the same method from the MeshBuilder class instead
  34776. * @param name defines the name of the mesh to create
  34777. * @param diameter sets the diameter size (float) of the torus (default 1)
  34778. * @param thickness sets the diameter size of the tube of the torus (float, default 0.5)
  34779. * @param tessellation sets the number of torus sides (postive integer, default 16)
  34780. * @param scene defines the hosting scene
  34781. * @param updatable defines if the mesh must be flagged as updatable
  34782. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34783. * @returns a new Mesh
  34784. */
  34785. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  34786. var options = {
  34787. diameter: diameter,
  34788. thickness: thickness,
  34789. tessellation: tessellation,
  34790. sideOrientation: sideOrientation,
  34791. updatable: updatable
  34792. };
  34793. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  34794. };
  34795. /**
  34796. * Creates a torus knot mesh. Please consider using the same method from the MeshBuilder class instead
  34797. * @param name defines the name of the mesh to create
  34798. * @param radius sets the global radius size (float) of the torus knot (default 2)
  34799. * @param tube sets the diameter size of the tube of the torus (float, default 0.5)
  34800. * @param radialSegments sets the number of sides on each tube segments (positive integer, default 32)
  34801. * @param tubularSegments sets the number of tubes to decompose the knot into (positive integer, default 32)
  34802. * @param p the number of windings on X axis (positive integers, default 2)
  34803. * @param q the number of windings on Y axis (positive integers, default 3)
  34804. * @param scene defines the hosting scene
  34805. * @param updatable defines if the mesh must be flagged as updatable
  34806. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34807. * @returns a new Mesh
  34808. */
  34809. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  34810. var options = {
  34811. radius: radius,
  34812. tube: tube,
  34813. radialSegments: radialSegments,
  34814. tubularSegments: tubularSegments,
  34815. p: p,
  34816. q: q,
  34817. sideOrientation: sideOrientation,
  34818. updatable: updatable
  34819. };
  34820. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  34821. };
  34822. /**
  34823. * Creates a line mesh. Please consider using the same method from the MeshBuilder class instead.
  34824. * @param name defines the name of the mesh to create
  34825. * @param points is an array successive Vector3
  34826. * @param scene defines the hosting scene
  34827. * @param updatable defines if the mesh must be flagged as updatable
  34828. * @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).
  34829. * @returns a new Mesh
  34830. */
  34831. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  34832. if (scene === void 0) { scene = null; }
  34833. if (updatable === void 0) { updatable = false; }
  34834. if (instance === void 0) { instance = null; }
  34835. var options = {
  34836. points: points,
  34837. updatable: updatable,
  34838. instance: instance
  34839. };
  34840. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  34841. };
  34842. /**
  34843. * Creates a dashed line mesh. Please consider using the same method from the MeshBuilder class instead
  34844. * @param name defines the name of the mesh to create
  34845. * @param points is an array successive Vector3
  34846. * @param dashSize is the size of the dashes relatively the dash number (positive float, default 3)
  34847. * @param gapSize is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  34848. * @param dashNb is the intended total number of dashes (positive integer, default 200)
  34849. * @param scene defines the hosting scene
  34850. * @param updatable defines if the mesh must be flagged as updatable
  34851. * @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)
  34852. * @returns a new Mesh
  34853. */
  34854. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  34855. if (scene === void 0) { scene = null; }
  34856. var options = {
  34857. points: points,
  34858. dashSize: dashSize,
  34859. gapSize: gapSize,
  34860. dashNb: dashNb,
  34861. updatable: updatable,
  34862. instance: instance
  34863. };
  34864. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  34865. };
  34866. /**
  34867. * Creates a polygon mesh.
  34868. * Please consider using the same method from the MeshBuilder class instead.
  34869. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  34870. * 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.
  34871. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34872. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34873. * Remember you can only change the shape positions, not their number when updating a polygon.
  34874. */
  34875. /**
  34876. * Creates a polygon mesh.Please consider using the same method from the MeshBuilder class instead
  34877. * @see http://doc.babylonjs.com/how_to/parametric_shapes#non-regular-polygon
  34878. * @param name defines the name of the mesh to create
  34879. * @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
  34880. * @param scene defines the hosting scene
  34881. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  34882. * @param updatable defines if the mesh must be flagged as updatable
  34883. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34884. * @returns a new Mesh
  34885. */
  34886. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  34887. var options = {
  34888. shape: shape,
  34889. holes: holes,
  34890. updatable: updatable,
  34891. sideOrientation: sideOrientation
  34892. };
  34893. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  34894. };
  34895. /**
  34896. * Creates an extruded polygon mesh, with depth in the Y direction. Please consider using the same method from the MeshBuilder class instead.
  34897. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-non-regular-polygon
  34898. * @param name defines the name of the mesh to create
  34899. * @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
  34900. * @param depth defines the height of extrusion
  34901. * @param scene defines the hosting scene
  34902. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  34903. * @param updatable defines if the mesh must be flagged as updatable
  34904. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34905. * @returns a new Mesh
  34906. */
  34907. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  34908. var options = {
  34909. shape: shape,
  34910. holes: holes,
  34911. depth: depth,
  34912. updatable: updatable,
  34913. sideOrientation: sideOrientation
  34914. };
  34915. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  34916. };
  34917. /**
  34918. * Creates an extruded shape mesh.
  34919. * 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
  34920. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  34921. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  34922. * @param name defines the name of the mesh to create
  34923. * @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
  34924. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  34925. * @param scale is the value to scale the shape
  34926. * @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
  34927. * @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
  34928. * @param scene defines the hosting scene
  34929. * @param updatable defines if the mesh must be flagged as updatable
  34930. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34931. * @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)
  34932. * @returns a new Mesh
  34933. */
  34934. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  34935. if (scene === void 0) { scene = null; }
  34936. var options = {
  34937. shape: shape,
  34938. path: path,
  34939. scale: scale,
  34940. rotation: rotation,
  34941. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  34942. sideOrientation: sideOrientation,
  34943. instance: instance,
  34944. updatable: updatable
  34945. };
  34946. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  34947. };
  34948. /**
  34949. * Creates an custom extruded shape mesh.
  34950. * The custom extrusion is a parametric shape.
  34951. * It has no predefined shape. Its final shape will depend on the input parameters.
  34952. * Please consider using the same method from the MeshBuilder class instead
  34953. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  34954. * @param name defines the name of the mesh to create
  34955. * @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
  34956. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  34957. * @param scaleFunction is a custom Javascript function called on each path point
  34958. * @param rotationFunction is a custom Javascript function called on each path point
  34959. * @param ribbonCloseArray forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  34960. * @param ribbonClosePath forces the extrusion underlying ribbon to close its `pathArray`
  34961. * @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
  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. * @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)
  34966. * @returns a new Mesh
  34967. */
  34968. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  34969. var options = {
  34970. shape: shape,
  34971. path: path,
  34972. scaleFunction: scaleFunction,
  34973. rotationFunction: rotationFunction,
  34974. ribbonCloseArray: ribbonCloseArray,
  34975. ribbonClosePath: ribbonClosePath,
  34976. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  34977. sideOrientation: sideOrientation,
  34978. instance: instance,
  34979. updatable: updatable
  34980. };
  34981. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  34982. };
  34983. /**
  34984. * Creates lathe mesh.
  34985. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  34986. * Please consider using the same method from the MeshBuilder class instead
  34987. * @param name defines the name of the mesh to create
  34988. * @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
  34989. * @param radius is the radius value of the lathe
  34990. * @param tessellation is the side number of the lathe.
  34991. * @param scene defines the hosting scene
  34992. * @param updatable defines if the mesh must be flagged as updatable
  34993. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34994. * @returns a new Mesh
  34995. */
  34996. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  34997. var options = {
  34998. shape: shape,
  34999. radius: radius,
  35000. tessellation: tessellation,
  35001. sideOrientation: sideOrientation,
  35002. updatable: updatable
  35003. };
  35004. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  35005. };
  35006. /**
  35007. * Creates a plane mesh. Please consider using the same method from the MeshBuilder class instead
  35008. * @param name defines the name of the mesh to create
  35009. * @param size sets the size (float) of both sides of the plane at once (default 1)
  35010. * @param scene defines the hosting scene
  35011. * @param updatable defines if the mesh must be flagged as updatable
  35012. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35013. * @returns a new Mesh
  35014. */
  35015. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  35016. var options = {
  35017. size: size,
  35018. width: size,
  35019. height: size,
  35020. sideOrientation: sideOrientation,
  35021. updatable: updatable
  35022. };
  35023. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  35024. };
  35025. /**
  35026. * Creates a ground mesh.
  35027. * Please consider using the same method from the MeshBuilder class instead
  35028. * @param name defines the name of the mesh to create
  35029. * @param width set the width of the ground
  35030. * @param height set the height of the ground
  35031. * @param subdivisions sets the number of subdivisions per side
  35032. * @param scene defines the hosting scene
  35033. * @param updatable defines if the mesh must be flagged as updatable
  35034. * @returns a new Mesh
  35035. */
  35036. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  35037. var options = {
  35038. width: width,
  35039. height: height,
  35040. subdivisions: subdivisions,
  35041. updatable: updatable
  35042. };
  35043. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  35044. };
  35045. /**
  35046. * Creates a tiled ground mesh.
  35047. * Please consider using the same method from the MeshBuilder class instead
  35048. * @param name defines the name of the mesh to create
  35049. * @param xmin set the ground minimum X coordinate
  35050. * @param zmin set the ground minimum Y coordinate
  35051. * @param xmax set the ground maximum X coordinate
  35052. * @param zmax set the ground maximum Z coordinate
  35053. * @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
  35054. * @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
  35055. * @param scene defines the hosting scene
  35056. * @param updatable defines if the mesh must be flagged as updatable
  35057. * @returns a new Mesh
  35058. */
  35059. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  35060. var options = {
  35061. xmin: xmin,
  35062. zmin: zmin,
  35063. xmax: xmax,
  35064. zmax: zmax,
  35065. subdivisions: subdivisions,
  35066. precision: precision,
  35067. updatable: updatable
  35068. };
  35069. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  35070. };
  35071. /**
  35072. * Creates a ground mesh from a height map.
  35073. * Please consider using the same method from the MeshBuilder class instead
  35074. * @see http://doc.babylonjs.com/babylon101/height_map
  35075. * @param name defines the name of the mesh to create
  35076. * @param url sets the URL of the height map image resource
  35077. * @param width set the ground width size
  35078. * @param height set the ground height size
  35079. * @param subdivisions sets the number of subdivision per side
  35080. * @param minHeight is the minimum altitude on the ground
  35081. * @param maxHeight is the maximum altitude on the ground
  35082. * @param scene defines the hosting scene
  35083. * @param updatable defines if the mesh must be flagged as updatable
  35084. * @param onReady is a callback function that will be called once the mesh is built (the height map download can last some time)
  35085. * @param alphaFilter will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  35086. * @returns a new Mesh
  35087. */
  35088. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady, alphaFilter) {
  35089. var options = {
  35090. width: width,
  35091. height: height,
  35092. subdivisions: subdivisions,
  35093. minHeight: minHeight,
  35094. maxHeight: maxHeight,
  35095. updatable: updatable,
  35096. onReady: onReady,
  35097. alphaFilter: alphaFilter
  35098. };
  35099. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  35100. };
  35101. /**
  35102. * Creates a tube mesh.
  35103. * The tube is a parametric shape.
  35104. * It has no predefined shape. Its final shape will depend on the input parameters.
  35105. * Please consider using the same method from the MeshBuilder class instead
  35106. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  35107. * @param name defines the name of the mesh to create
  35108. * @param path is a required array of successive Vector3. It is the curve used as the axis of the tube
  35109. * @param radius sets the tube radius size
  35110. * @param tessellation is the number of sides on the tubular surface
  35111. * @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
  35112. * @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
  35113. * @param scene defines the hosting scene
  35114. * @param updatable defines if the mesh must be flagged as updatable
  35115. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35116. * @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)
  35117. * @returns a new Mesh
  35118. */
  35119. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  35120. var options = {
  35121. path: path,
  35122. radius: radius,
  35123. tessellation: tessellation,
  35124. radiusFunction: radiusFunction,
  35125. arc: 1,
  35126. cap: cap,
  35127. updatable: updatable,
  35128. sideOrientation: sideOrientation,
  35129. instance: instance
  35130. };
  35131. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  35132. };
  35133. /**
  35134. * Creates a polyhedron mesh.
  35135. * Please consider using the same method from the MeshBuilder class instead.
  35136. * * 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
  35137. * * The parameter `size` (positive float, default 1) sets the polygon size
  35138. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  35139. * * 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`
  35140. * * 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
  35141. * * 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)`)
  35142. * * 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
  35143. * * 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
  35144. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  35145. * * 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
  35146. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  35147. * @param name defines the name of the mesh to create
  35148. * @param options defines the options used to create the mesh
  35149. * @param scene defines the hosting scene
  35150. * @returns a new Mesh
  35151. */
  35152. Mesh.CreatePolyhedron = function (name, options, scene) {
  35153. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  35154. };
  35155. /**
  35156. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  35157. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  35158. * * 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`)
  35159. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  35160. * * 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
  35161. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  35162. * * 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
  35163. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  35164. * @param name defines the name of the mesh
  35165. * @param options defines the options used to create the mesh
  35166. * @param scene defines the hosting scene
  35167. * @returns a new Mesh
  35168. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  35169. */
  35170. Mesh.CreateIcoSphere = function (name, options, scene) {
  35171. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  35172. };
  35173. /**
  35174. * Creates a decal mesh.
  35175. * Please consider using the same method from the MeshBuilder class instead.
  35176. * A decal is a mesh usually applied as a model onto the surface of another mesh
  35177. * @param name defines the name of the mesh
  35178. * @param sourceMesh defines the mesh receiving the decal
  35179. * @param position sets the position of the decal in world coordinates
  35180. * @param normal sets the normal of the mesh where the decal is applied onto in world coordinates
  35181. * @param size sets the decal scaling
  35182. * @param angle sets the angle to rotate the decal
  35183. * @returns a new Mesh
  35184. */
  35185. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  35186. var options = {
  35187. position: position,
  35188. normal: normal,
  35189. size: size,
  35190. angle: angle
  35191. };
  35192. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  35193. };
  35194. // Skeletons
  35195. /**
  35196. * Prepare internal position array for software CPU skinning
  35197. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh
  35198. */
  35199. Mesh.prototype.setPositionsForCPUSkinning = function () {
  35200. if (!this._sourcePositions) {
  35201. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35202. if (!source) {
  35203. return this._sourcePositions;
  35204. }
  35205. this._sourcePositions = new Float32Array(source);
  35206. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35207. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  35208. }
  35209. }
  35210. return this._sourcePositions;
  35211. };
  35212. /**
  35213. * Prepare internal normal array for software CPU skinning
  35214. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  35215. */
  35216. Mesh.prototype.setNormalsForCPUSkinning = function () {
  35217. if (!this._sourceNormals) {
  35218. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  35219. if (!source) {
  35220. return this._sourceNormals;
  35221. }
  35222. this._sourceNormals = new Float32Array(source);
  35223. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35224. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  35225. }
  35226. }
  35227. return this._sourceNormals;
  35228. };
  35229. /**
  35230. * Updates the vertex buffer by applying transformation from the bones
  35231. * @param skeleton defines the skeleton to apply to current mesh
  35232. * @returns the current mesh
  35233. */
  35234. Mesh.prototype.applySkeleton = function (skeleton) {
  35235. if (!this.geometry) {
  35236. return this;
  35237. }
  35238. if (this.geometry._softwareSkinningFrameId == this.getScene().getFrameId()) {
  35239. return this;
  35240. }
  35241. this.geometry._softwareSkinningFrameId = this.getScene().getFrameId();
  35242. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35243. return this;
  35244. }
  35245. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35246. return this;
  35247. }
  35248. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35249. return this;
  35250. }
  35251. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35252. return this;
  35253. }
  35254. if (!this._sourcePositions) {
  35255. var submeshes = this.subMeshes.slice();
  35256. this.setPositionsForCPUSkinning();
  35257. this.subMeshes = submeshes;
  35258. }
  35259. if (!this._sourceNormals) {
  35260. this.setNormalsForCPUSkinning();
  35261. }
  35262. // positionsData checks for not being Float32Array will only pass at most once
  35263. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35264. if (!positionsData) {
  35265. return this;
  35266. }
  35267. if (!(positionsData instanceof Float32Array)) {
  35268. positionsData = new Float32Array(positionsData);
  35269. }
  35270. // normalsData checks for not being Float32Array will only pass at most once
  35271. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  35272. if (!normalsData) {
  35273. return this;
  35274. }
  35275. if (!(normalsData instanceof Float32Array)) {
  35276. normalsData = new Float32Array(normalsData);
  35277. }
  35278. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35279. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  35280. if (!matricesWeightsData || !matricesIndicesData) {
  35281. return this;
  35282. }
  35283. var needExtras = this.numBoneInfluencers > 4;
  35284. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  35285. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  35286. var skeletonMatrices = skeleton.getTransformMatrices(this);
  35287. var tempVector3 = BABYLON.Vector3.Zero();
  35288. var finalMatrix = new BABYLON.Matrix();
  35289. var tempMatrix = new BABYLON.Matrix();
  35290. var matWeightIdx = 0;
  35291. var inf;
  35292. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  35293. var weight;
  35294. for (inf = 0; inf < 4; inf++) {
  35295. weight = matricesWeightsData[matWeightIdx + inf];
  35296. if (weight > 0) {
  35297. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  35298. finalMatrix.addToSelf(tempMatrix);
  35299. }
  35300. }
  35301. if (needExtras) {
  35302. for (inf = 0; inf < 4; inf++) {
  35303. weight = matricesWeightsExtraData[matWeightIdx + inf];
  35304. if (weight > 0) {
  35305. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  35306. finalMatrix.addToSelf(tempMatrix);
  35307. }
  35308. }
  35309. }
  35310. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  35311. tempVector3.toArray(positionsData, index);
  35312. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  35313. tempVector3.toArray(normalsData, index);
  35314. finalMatrix.reset();
  35315. }
  35316. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  35317. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  35318. return this;
  35319. };
  35320. // Tools
  35321. /**
  35322. * 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
  35323. * @param meshes defines the list of meshes to scan
  35324. * @returns an object `{min:` Vector3`, max:` Vector3`}`
  35325. */
  35326. Mesh.MinMax = function (meshes) {
  35327. var minVector = null;
  35328. var maxVector = null;
  35329. meshes.forEach(function (mesh, index, array) {
  35330. var boundingInfo = mesh.getBoundingInfo();
  35331. var boundingBox = boundingInfo.boundingBox;
  35332. if (!minVector || !maxVector) {
  35333. minVector = boundingBox.minimumWorld;
  35334. maxVector = boundingBox.maximumWorld;
  35335. }
  35336. else {
  35337. minVector.minimizeInPlace(boundingBox.minimumWorld);
  35338. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  35339. }
  35340. });
  35341. if (!minVector || !maxVector) {
  35342. return {
  35343. min: BABYLON.Vector3.Zero(),
  35344. max: BABYLON.Vector3.Zero()
  35345. };
  35346. }
  35347. return {
  35348. min: minVector,
  35349. max: maxVector
  35350. };
  35351. };
  35352. /**
  35353. * Returns the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array
  35354. * @param meshesOrMinMaxVector could be an array of meshes or a `{min:` Vector3`, max:` Vector3`}` object
  35355. * @returns a vector3
  35356. */
  35357. Mesh.Center = function (meshesOrMinMaxVector) {
  35358. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  35359. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  35360. };
  35361. /**
  35362. * Merge the array of meshes into a single mesh for performance reasons.
  35363. * @param meshes defines he vertices source. They should all be of the same material. Entries can empty
  35364. * @param disposeSource when true (default), dispose of the vertices from the source meshes
  35365. * @param allow32BitsIndices when the sum of the vertices > 64k, this must be set to true
  35366. * @param meshSubclass when set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  35367. * @param subdivideWithSubMeshes when true (false default), subdivide mesh to his subMesh array with meshes source.
  35368. * @returns a new mesh
  35369. */
  35370. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  35371. if (disposeSource === void 0) { disposeSource = true; }
  35372. var index;
  35373. if (!allow32BitsIndices) {
  35374. var totalVertices = 0;
  35375. // Counting vertices
  35376. for (index = 0; index < meshes.length; index++) {
  35377. if (meshes[index]) {
  35378. totalVertices += meshes[index].getTotalVertices();
  35379. if (totalVertices > 65536) {
  35380. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  35381. return null;
  35382. }
  35383. }
  35384. }
  35385. }
  35386. // Merge
  35387. var vertexData = null;
  35388. var otherVertexData;
  35389. var indiceArray = new Array();
  35390. var source = null;
  35391. for (index = 0; index < meshes.length; index++) {
  35392. if (meshes[index]) {
  35393. var wm = meshes[index].computeWorldMatrix(true);
  35394. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  35395. otherVertexData.transform(wm);
  35396. if (vertexData) {
  35397. vertexData.merge(otherVertexData, allow32BitsIndices);
  35398. }
  35399. else {
  35400. vertexData = otherVertexData;
  35401. source = meshes[index];
  35402. }
  35403. if (subdivideWithSubMeshes) {
  35404. indiceArray.push(meshes[index].getTotalIndices());
  35405. }
  35406. }
  35407. }
  35408. source = source;
  35409. if (!meshSubclass) {
  35410. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  35411. }
  35412. vertexData.applyToMesh(meshSubclass);
  35413. // Setting properties
  35414. meshSubclass.material = source.material;
  35415. meshSubclass.checkCollisions = source.checkCollisions;
  35416. // Cleaning
  35417. if (disposeSource) {
  35418. for (index = 0; index < meshes.length; index++) {
  35419. if (meshes[index]) {
  35420. meshes[index].dispose();
  35421. }
  35422. }
  35423. }
  35424. // Subdivide
  35425. if (subdivideWithSubMeshes) {
  35426. //-- removal of global submesh
  35427. meshSubclass.releaseSubMeshes();
  35428. index = 0;
  35429. var offset = 0;
  35430. //-- apply subdivision according to index table
  35431. while (index < indiceArray.length) {
  35432. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  35433. offset += indiceArray[index];
  35434. index++;
  35435. }
  35436. }
  35437. return meshSubclass;
  35438. };
  35439. // Consts
  35440. /**
  35441. * Mesh side orientation : usually the external or front surface
  35442. */
  35443. Mesh.FRONTSIDE = 0;
  35444. /**
  35445. * Mesh side orientation : usually the internal or back surface
  35446. */
  35447. Mesh.BACKSIDE = 1;
  35448. /**
  35449. * Mesh side orientation : both internal and external or front and back surfaces
  35450. */
  35451. Mesh.DOUBLESIDE = 2;
  35452. /**
  35453. * Mesh side orientation : by default, `FRONTSIDE`
  35454. */
  35455. Mesh.DEFAULTSIDE = 0;
  35456. /**
  35457. * Mesh cap setting : no cap
  35458. */
  35459. Mesh.NO_CAP = 0;
  35460. /**
  35461. * Mesh cap setting : one cap at the beginning of the mesh
  35462. */
  35463. Mesh.CAP_START = 1;
  35464. /**
  35465. * Mesh cap setting : one cap at the end of the mesh
  35466. */
  35467. Mesh.CAP_END = 2;
  35468. /**
  35469. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  35470. */
  35471. Mesh.CAP_ALL = 3;
  35472. return Mesh;
  35473. }(BABYLON.AbstractMesh));
  35474. BABYLON.Mesh = Mesh;
  35475. })(BABYLON || (BABYLON = {}));
  35476. //# sourceMappingURL=babylon.mesh.js.map
  35477. var BABYLON;
  35478. (function (BABYLON) {
  35479. /**
  35480. * Base class for submeshes
  35481. */
  35482. var BaseSubMesh = /** @class */ (function () {
  35483. function BaseSubMesh() {
  35484. }
  35485. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  35486. /**
  35487. * Gets associated effect
  35488. */
  35489. get: function () {
  35490. return this._materialEffect;
  35491. },
  35492. enumerable: true,
  35493. configurable: true
  35494. });
  35495. /**
  35496. * Sets associated effect (effect used to render this submesh)
  35497. * @param effect defines the effect to associate with
  35498. * @param defines defines the set of defines used to compile this effect
  35499. */
  35500. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  35501. if (defines === void 0) { defines = null; }
  35502. if (this._materialEffect === effect) {
  35503. if (!effect) {
  35504. this._materialDefines = null;
  35505. }
  35506. return;
  35507. }
  35508. this._materialDefines = defines;
  35509. this._materialEffect = effect;
  35510. };
  35511. return BaseSubMesh;
  35512. }());
  35513. BABYLON.BaseSubMesh = BaseSubMesh;
  35514. /**
  35515. * Defines a subdivision inside a mesh
  35516. */
  35517. var SubMesh = /** @class */ (function (_super) {
  35518. __extends(SubMesh, _super);
  35519. /**
  35520. * Creates a new submesh
  35521. * @param materialIndex defines the material index to use
  35522. * @param verticesStart defines vertex index start
  35523. * @param verticesCount defines vertices count
  35524. * @param indexStart defines index start
  35525. * @param indexCount defines indices count
  35526. * @param mesh defines the parent mesh
  35527. * @param renderingMesh defines an optional rendering mesh
  35528. * @param createBoundingBox defines if bounding box should be created for this submesh
  35529. */
  35530. function SubMesh(
  35531. /** the material index to use */
  35532. materialIndex,
  35533. /** vertex index start */
  35534. verticesStart,
  35535. /** vertices count */
  35536. verticesCount,
  35537. /** index start */
  35538. indexStart,
  35539. /** indices count */
  35540. indexCount, mesh, renderingMesh, createBoundingBox) {
  35541. if (createBoundingBox === void 0) { createBoundingBox = true; }
  35542. var _this = _super.call(this) || this;
  35543. _this.materialIndex = materialIndex;
  35544. _this.verticesStart = verticesStart;
  35545. _this.verticesCount = verticesCount;
  35546. _this.indexStart = indexStart;
  35547. _this.indexCount = indexCount;
  35548. /** @hidden */
  35549. _this._renderId = 0;
  35550. _this._mesh = mesh;
  35551. _this._renderingMesh = renderingMesh || mesh;
  35552. mesh.subMeshes.push(_this);
  35553. _this._trianglePlanes = [];
  35554. _this._id = mesh.subMeshes.length - 1;
  35555. if (createBoundingBox) {
  35556. _this.refreshBoundingInfo();
  35557. mesh.computeWorldMatrix(true);
  35558. }
  35559. return _this;
  35560. }
  35561. /**
  35562. * Add a new submesh to a mesh
  35563. * @param materialIndex defines the material index to use
  35564. * @param verticesStart defines vertex index start
  35565. * @param verticesCount defines vertices count
  35566. * @param indexStart defines index start
  35567. * @param indexCount defines indices count
  35568. * @param mesh defines the parent mesh
  35569. * @param renderingMesh defines an optional rendering mesh
  35570. * @param createBoundingBox defines if bounding box should be created for this submesh
  35571. * @returns the new submesh
  35572. */
  35573. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  35574. if (createBoundingBox === void 0) { createBoundingBox = true; }
  35575. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  35576. };
  35577. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  35578. /**
  35579. * Returns true if this submesh covers the entire parent mesh
  35580. * @ignorenaming
  35581. */
  35582. get: function () {
  35583. return (this.verticesStart === 0 && this.verticesCount === this._mesh.getTotalVertices());
  35584. },
  35585. enumerable: true,
  35586. configurable: true
  35587. });
  35588. /**
  35589. * Returns the submesh BoudingInfo object
  35590. * @returns current bounding info (or mesh's one if the submesh is global)
  35591. */
  35592. SubMesh.prototype.getBoundingInfo = function () {
  35593. if (this.IsGlobal) {
  35594. return this._mesh.getBoundingInfo();
  35595. }
  35596. return this._boundingInfo;
  35597. };
  35598. /**
  35599. * Sets the submesh BoundingInfo
  35600. * @param boundingInfo defines the new bounding info to use
  35601. * @returns the SubMesh
  35602. */
  35603. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  35604. this._boundingInfo = boundingInfo;
  35605. return this;
  35606. };
  35607. /**
  35608. * Returns the mesh of the current submesh
  35609. * @return the parent mesh
  35610. */
  35611. SubMesh.prototype.getMesh = function () {
  35612. return this._mesh;
  35613. };
  35614. /**
  35615. * Returns the rendering mesh of the submesh
  35616. * @returns the rendering mesh (could be different from parent mesh)
  35617. */
  35618. SubMesh.prototype.getRenderingMesh = function () {
  35619. return this._renderingMesh;
  35620. };
  35621. /**
  35622. * Returns the submesh material
  35623. * @returns null or the current material
  35624. */
  35625. SubMesh.prototype.getMaterial = function () {
  35626. var rootMaterial = this._renderingMesh.material;
  35627. if (rootMaterial === null || rootMaterial === undefined) {
  35628. return this._mesh.getScene().defaultMaterial;
  35629. }
  35630. else if (rootMaterial.getSubMaterial) {
  35631. var multiMaterial = rootMaterial;
  35632. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  35633. if (this._currentMaterial !== effectiveMaterial) {
  35634. this._currentMaterial = effectiveMaterial;
  35635. this._materialDefines = null;
  35636. }
  35637. return effectiveMaterial;
  35638. }
  35639. return rootMaterial;
  35640. };
  35641. // Methods
  35642. /**
  35643. * Sets a new updated BoundingInfo object to the submesh
  35644. * @returns the SubMesh
  35645. */
  35646. SubMesh.prototype.refreshBoundingInfo = function () {
  35647. this._lastColliderWorldVertices = null;
  35648. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  35649. return this;
  35650. }
  35651. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35652. if (!data) {
  35653. this._boundingInfo = this._mesh.getBoundingInfo();
  35654. return this;
  35655. }
  35656. var indices = this._renderingMesh.getIndices();
  35657. var extend;
  35658. //is this the only submesh?
  35659. if (this.indexStart === 0 && this.indexCount === indices.length) {
  35660. var boundingInfo = this._renderingMesh.getBoundingInfo();
  35661. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  35662. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  35663. }
  35664. else {
  35665. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  35666. }
  35667. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  35668. return this;
  35669. };
  35670. /** @hidden */
  35671. SubMesh.prototype._checkCollision = function (collider) {
  35672. var boundingInfo = this.getBoundingInfo();
  35673. return boundingInfo._checkCollision(collider);
  35674. };
  35675. /**
  35676. * Updates the submesh BoundingInfo
  35677. * @param world defines the world matrix to use to update the bounding info
  35678. * @returns the submesh
  35679. */
  35680. SubMesh.prototype.updateBoundingInfo = function (world) {
  35681. var boundingInfo = this.getBoundingInfo();
  35682. if (!boundingInfo) {
  35683. this.refreshBoundingInfo();
  35684. boundingInfo = this.getBoundingInfo();
  35685. }
  35686. boundingInfo.update(world);
  35687. return this;
  35688. };
  35689. /**
  35690. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  35691. * @param frustumPlanes defines the frustum planes
  35692. * @returns true if the submesh is intersecting with the frustum
  35693. */
  35694. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  35695. var boundingInfo = this.getBoundingInfo();
  35696. if (!boundingInfo) {
  35697. return false;
  35698. }
  35699. return boundingInfo.isInFrustum(frustumPlanes, this._mesh.cullingStrategy);
  35700. };
  35701. /**
  35702. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes
  35703. * @param frustumPlanes defines the frustum planes
  35704. * @returns true if the submesh is inside the frustum
  35705. */
  35706. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  35707. var boundingInfo = this.getBoundingInfo();
  35708. if (!boundingInfo) {
  35709. return false;
  35710. }
  35711. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  35712. };
  35713. /**
  35714. * Renders the submesh
  35715. * @param enableAlphaMode defines if alpha needs to be used
  35716. * @returns the submesh
  35717. */
  35718. SubMesh.prototype.render = function (enableAlphaMode) {
  35719. this._renderingMesh.render(this, enableAlphaMode);
  35720. return this;
  35721. };
  35722. /**
  35723. * @hidden
  35724. */
  35725. SubMesh.prototype._getLinesIndexBuffer = function (indices, engine) {
  35726. if (!this._linesIndexBuffer) {
  35727. var linesIndices = [];
  35728. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  35729. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  35730. }
  35731. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  35732. this._linesIndexCount = linesIndices.length;
  35733. }
  35734. return this._linesIndexBuffer;
  35735. };
  35736. /**
  35737. * Checks if the submesh intersects with a ray
  35738. * @param ray defines the ray to test
  35739. * @returns true is the passed ray intersects the submesh bounding box
  35740. */
  35741. SubMesh.prototype.canIntersects = function (ray) {
  35742. var boundingInfo = this.getBoundingInfo();
  35743. if (!boundingInfo) {
  35744. return false;
  35745. }
  35746. return ray.intersectsBox(boundingInfo.boundingBox);
  35747. };
  35748. /**
  35749. * Intersects current submesh with a ray
  35750. * @param ray defines the ray to test
  35751. * @param positions defines mesh's positions array
  35752. * @param indices defines mesh's indices array
  35753. * @param fastCheck defines if only bounding info should be used
  35754. * @returns intersection info or null if no intersection
  35755. */
  35756. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  35757. var material = this.getMaterial();
  35758. if (!material) {
  35759. return null;
  35760. }
  35761. switch (material.fillMode) {
  35762. case BABYLON.Material.PointListDrawMode:
  35763. case BABYLON.Material.LineListDrawMode:
  35764. case BABYLON.Material.LineLoopDrawMode:
  35765. case BABYLON.Material.LineStripDrawMode:
  35766. case BABYLON.Material.TriangleFanDrawMode:
  35767. case BABYLON.Material.TriangleStripDrawMode:
  35768. return null;
  35769. }
  35770. // LineMesh first as it's also a Mesh...
  35771. if (BABYLON.LinesMesh) {
  35772. var mesh = this._mesh instanceof BABYLON.InstancedMesh ? this._mesh.sourceMesh : this._mesh;
  35773. if (mesh instanceof BABYLON.LinesMesh) {
  35774. var linesMesh = mesh;
  35775. return this._intersectLines(ray, positions, indices, linesMesh.intersectionThreshold, fastCheck);
  35776. }
  35777. }
  35778. return this._intersectTriangles(ray, positions, indices, fastCheck);
  35779. };
  35780. /** @hidden */
  35781. SubMesh.prototype._intersectLines = function (ray, positions, indices, intersectionThreshold, fastCheck) {
  35782. var intersectInfo = null;
  35783. // Line test
  35784. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  35785. var p0 = positions[indices[index]];
  35786. var p1 = positions[indices[index + 1]];
  35787. var length = ray.intersectionSegment(p0, p1, intersectionThreshold);
  35788. if (length < 0) {
  35789. continue;
  35790. }
  35791. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  35792. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  35793. if (fastCheck) {
  35794. break;
  35795. }
  35796. }
  35797. }
  35798. return intersectInfo;
  35799. };
  35800. /** @hidden */
  35801. SubMesh.prototype._intersectTriangles = function (ray, positions, indices, fastCheck) {
  35802. var intersectInfo = null;
  35803. // Triangles test
  35804. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  35805. var p0 = positions[indices[index]];
  35806. var p1 = positions[indices[index + 1]];
  35807. var p2 = positions[indices[index + 2]];
  35808. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  35809. if (currentIntersectInfo) {
  35810. if (currentIntersectInfo.distance < 0) {
  35811. continue;
  35812. }
  35813. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  35814. intersectInfo = currentIntersectInfo;
  35815. intersectInfo.faceId = index / 3;
  35816. if (fastCheck) {
  35817. break;
  35818. }
  35819. }
  35820. }
  35821. }
  35822. return intersectInfo;
  35823. };
  35824. /** @hidden */
  35825. SubMesh.prototype._rebuild = function () {
  35826. if (this._linesIndexBuffer) {
  35827. this._linesIndexBuffer = null;
  35828. }
  35829. };
  35830. // Clone
  35831. /**
  35832. * Creates a new submesh from the passed mesh
  35833. * @param newMesh defines the new hosting mesh
  35834. * @param newRenderingMesh defines an optional rendering mesh
  35835. * @returns the new submesh
  35836. */
  35837. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  35838. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  35839. if (!this.IsGlobal) {
  35840. var boundingInfo = this.getBoundingInfo();
  35841. if (!boundingInfo) {
  35842. return result;
  35843. }
  35844. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  35845. }
  35846. return result;
  35847. };
  35848. // Dispose
  35849. /**
  35850. * Release associated resources
  35851. */
  35852. SubMesh.prototype.dispose = function () {
  35853. if (this._linesIndexBuffer) {
  35854. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  35855. this._linesIndexBuffer = null;
  35856. }
  35857. // Remove from mesh
  35858. var index = this._mesh.subMeshes.indexOf(this);
  35859. this._mesh.subMeshes.splice(index, 1);
  35860. };
  35861. // Statics
  35862. /**
  35863. * Creates a new submesh from indices data
  35864. * @param materialIndex the index of the main mesh material
  35865. * @param startIndex the index where to start the copy in the mesh indices array
  35866. * @param indexCount the number of indices to copy then from the startIndex
  35867. * @param mesh the main mesh to create the submesh from
  35868. * @param renderingMesh the optional rendering mesh
  35869. * @returns a new submesh
  35870. */
  35871. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  35872. var minVertexIndex = Number.MAX_VALUE;
  35873. var maxVertexIndex = -Number.MAX_VALUE;
  35874. renderingMesh = (renderingMesh || mesh);
  35875. var indices = renderingMesh.getIndices();
  35876. for (var index = startIndex; index < startIndex + indexCount; index++) {
  35877. var vertexIndex = indices[index];
  35878. if (vertexIndex < minVertexIndex) {
  35879. minVertexIndex = vertexIndex;
  35880. }
  35881. if (vertexIndex > maxVertexIndex) {
  35882. maxVertexIndex = vertexIndex;
  35883. }
  35884. }
  35885. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  35886. };
  35887. return SubMesh;
  35888. }(BaseSubMesh));
  35889. BABYLON.SubMesh = SubMesh;
  35890. })(BABYLON || (BABYLON = {}));
  35891. //# sourceMappingURL=babylon.subMesh.js.map
  35892. var __assign = (this && this.__assign) || function () {
  35893. __assign = Object.assign || function(t) {
  35894. for (var s, i = 1, n = arguments.length; i < n; i++) {
  35895. s = arguments[i];
  35896. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  35897. t[p] = s[p];
  35898. }
  35899. return t;
  35900. };
  35901. return __assign.apply(this, arguments);
  35902. };
  35903. var BABYLON;
  35904. (function (BABYLON) {
  35905. /**
  35906. * Manages the defines for the Material
  35907. */
  35908. var MaterialDefines = /** @class */ (function () {
  35909. function MaterialDefines() {
  35910. this._isDirty = true;
  35911. /** @hidden */
  35912. this._areLightsDirty = true;
  35913. /** @hidden */
  35914. this._areAttributesDirty = true;
  35915. /** @hidden */
  35916. this._areTexturesDirty = true;
  35917. /** @hidden */
  35918. this._areFresnelDirty = true;
  35919. /** @hidden */
  35920. this._areMiscDirty = true;
  35921. /** @hidden */
  35922. this._areImageProcessingDirty = true;
  35923. /** @hidden */
  35924. this._normals = false;
  35925. /** @hidden */
  35926. this._uvs = false;
  35927. /** @hidden */
  35928. this._needNormals = false;
  35929. /** @hidden */
  35930. this._needUVs = false;
  35931. }
  35932. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  35933. /**
  35934. * Specifies if the material needs to be re-calculated
  35935. */
  35936. get: function () {
  35937. return this._isDirty;
  35938. },
  35939. enumerable: true,
  35940. configurable: true
  35941. });
  35942. /**
  35943. * Marks the material to indicate that it has been re-calculated
  35944. */
  35945. MaterialDefines.prototype.markAsProcessed = function () {
  35946. this._isDirty = false;
  35947. this._areAttributesDirty = false;
  35948. this._areTexturesDirty = false;
  35949. this._areFresnelDirty = false;
  35950. this._areLightsDirty = false;
  35951. this._areMiscDirty = false;
  35952. this._areImageProcessingDirty = false;
  35953. };
  35954. /**
  35955. * Marks the material to indicate that it needs to be re-calculated
  35956. */
  35957. MaterialDefines.prototype.markAsUnprocessed = function () {
  35958. this._isDirty = true;
  35959. };
  35960. /**
  35961. * Marks the material to indicate all of its defines need to be re-calculated
  35962. */
  35963. MaterialDefines.prototype.markAllAsDirty = function () {
  35964. this._areTexturesDirty = true;
  35965. this._areAttributesDirty = true;
  35966. this._areLightsDirty = true;
  35967. this._areFresnelDirty = true;
  35968. this._areMiscDirty = true;
  35969. this._areImageProcessingDirty = true;
  35970. this._isDirty = true;
  35971. };
  35972. /**
  35973. * Marks the material to indicate that image processing needs to be re-calculated
  35974. */
  35975. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  35976. this._areImageProcessingDirty = true;
  35977. this._isDirty = true;
  35978. };
  35979. /**
  35980. * Marks the material to indicate the lights need to be re-calculated
  35981. */
  35982. MaterialDefines.prototype.markAsLightDirty = function () {
  35983. this._areLightsDirty = true;
  35984. this._isDirty = true;
  35985. };
  35986. /**
  35987. * Marks the attribute state as changed
  35988. */
  35989. MaterialDefines.prototype.markAsAttributesDirty = function () {
  35990. this._areAttributesDirty = true;
  35991. this._isDirty = true;
  35992. };
  35993. /**
  35994. * Marks the texture state as changed
  35995. */
  35996. MaterialDefines.prototype.markAsTexturesDirty = function () {
  35997. this._areTexturesDirty = true;
  35998. this._isDirty = true;
  35999. };
  36000. /**
  36001. * Marks the fresnel state as changed
  36002. */
  36003. MaterialDefines.prototype.markAsFresnelDirty = function () {
  36004. this._areFresnelDirty = true;
  36005. this._isDirty = true;
  36006. };
  36007. /**
  36008. * Marks the misc state as changed
  36009. */
  36010. MaterialDefines.prototype.markAsMiscDirty = function () {
  36011. this._areMiscDirty = true;
  36012. this._isDirty = true;
  36013. };
  36014. /**
  36015. * Rebuilds the material defines
  36016. */
  36017. MaterialDefines.prototype.rebuild = function () {
  36018. if (this._keys) {
  36019. delete this._keys;
  36020. }
  36021. this._keys = [];
  36022. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  36023. var key = _a[_i];
  36024. if (key[0] === "_") {
  36025. continue;
  36026. }
  36027. this._keys.push(key);
  36028. }
  36029. };
  36030. /**
  36031. * Specifies if two material defines are equal
  36032. * @param other - A material define instance to compare to
  36033. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  36034. */
  36035. MaterialDefines.prototype.isEqual = function (other) {
  36036. if (this._keys.length !== other._keys.length) {
  36037. return false;
  36038. }
  36039. for (var index = 0; index < this._keys.length; index++) {
  36040. var prop = this._keys[index];
  36041. if (this[prop] !== other[prop]) {
  36042. return false;
  36043. }
  36044. }
  36045. return true;
  36046. };
  36047. /**
  36048. * Clones this instance's defines to another instance
  36049. * @param other - material defines to clone values to
  36050. */
  36051. MaterialDefines.prototype.cloneTo = function (other) {
  36052. if (this._keys.length !== other._keys.length) {
  36053. other._keys = this._keys.slice(0);
  36054. }
  36055. for (var index = 0; index < this._keys.length; index++) {
  36056. var prop = this._keys[index];
  36057. other[prop] = this[prop];
  36058. }
  36059. };
  36060. /**
  36061. * Resets the material define values
  36062. */
  36063. MaterialDefines.prototype.reset = function () {
  36064. for (var index = 0; index < this._keys.length; index++) {
  36065. var prop = this._keys[index];
  36066. var type = typeof this[prop];
  36067. switch (type) {
  36068. case "number":
  36069. this[prop] = 0;
  36070. break;
  36071. case "string":
  36072. this[prop] = "";
  36073. break;
  36074. default:
  36075. this[prop] = false;
  36076. break;
  36077. }
  36078. }
  36079. };
  36080. /**
  36081. * Converts the material define values to a string
  36082. * @returns - String of material define information
  36083. */
  36084. MaterialDefines.prototype.toString = function () {
  36085. var result = "";
  36086. for (var index = 0; index < this._keys.length; index++) {
  36087. var prop = this._keys[index];
  36088. var value = this[prop];
  36089. var type = typeof value;
  36090. switch (type) {
  36091. case "number":
  36092. case "string":
  36093. result += "#define " + prop + " " + value + "\n";
  36094. break;
  36095. default:
  36096. if (value) {
  36097. result += "#define " + prop + "\n";
  36098. }
  36099. break;
  36100. }
  36101. }
  36102. return result;
  36103. };
  36104. return MaterialDefines;
  36105. }());
  36106. BABYLON.MaterialDefines = MaterialDefines;
  36107. /**
  36108. * Base class for the main features of a material in Babylon.js
  36109. */
  36110. var Material = /** @class */ (function () {
  36111. /**
  36112. * Creates a material instance
  36113. * @param name defines the name of the material
  36114. * @param scene defines the scene to reference
  36115. * @param doNotAdd specifies if the material should be added to the scene
  36116. */
  36117. function Material(name, scene, doNotAdd) {
  36118. /**
  36119. * Specifies if the ready state should be checked on each call
  36120. */
  36121. this.checkReadyOnEveryCall = false;
  36122. /**
  36123. * Specifies if the ready state should be checked once
  36124. */
  36125. this.checkReadyOnlyOnce = false;
  36126. /**
  36127. * The state of the material
  36128. */
  36129. this.state = "";
  36130. /**
  36131. * The alpha value of the material
  36132. */
  36133. this._alpha = 1.0;
  36134. /**
  36135. * Specifies if back face culling is enabled
  36136. */
  36137. this._backFaceCulling = true;
  36138. /**
  36139. * Specifies if the material should be serialized
  36140. */
  36141. this.doNotSerialize = false;
  36142. /**
  36143. * Specifies if the effect should be stored on sub meshes
  36144. */
  36145. this.storeEffectOnSubMeshes = false;
  36146. /**
  36147. * An event triggered when the material is disposed
  36148. */
  36149. this.onDisposeObservable = new BABYLON.Observable();
  36150. /**
  36151. * Stores the value of the alpha mode
  36152. */
  36153. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  36154. /**
  36155. * Stores the state of the need depth pre-pass value
  36156. */
  36157. this._needDepthPrePass = false;
  36158. /**
  36159. * Specifies if depth writing should be disabled
  36160. */
  36161. this.disableDepthWrite = false;
  36162. /**
  36163. * Specifies if depth writing should be forced
  36164. */
  36165. this.forceDepthWrite = false;
  36166. /**
  36167. * Specifies if there should be a separate pass for culling
  36168. */
  36169. this.separateCullingPass = false;
  36170. /**
  36171. * Stores the state specifing if fog should be enabled
  36172. */
  36173. this._fogEnabled = true;
  36174. /**
  36175. * Stores the size of points
  36176. */
  36177. this.pointSize = 1.0;
  36178. /**
  36179. * Stores the z offset value
  36180. */
  36181. this.zOffset = 0;
  36182. /**
  36183. * @hidden
  36184. * Specifies if the material was previously ready
  36185. */
  36186. this._wasPreviouslyReady = false;
  36187. /**
  36188. * Stores the fill mode state
  36189. */
  36190. this._fillMode = Material.TriangleFillMode;
  36191. this.name = name;
  36192. this.id = name || BABYLON.Tools.RandomId();
  36193. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  36194. this.uniqueId = this._scene.getUniqueId();
  36195. if (this._scene.useRightHandedSystem) {
  36196. this.sideOrientation = Material.ClockWiseSideOrientation;
  36197. }
  36198. else {
  36199. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  36200. }
  36201. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  36202. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  36203. if (!doNotAdd) {
  36204. this._scene.materials.push(this);
  36205. this._scene.onNewMaterialAddedObservable.notifyObservers(this);
  36206. }
  36207. }
  36208. Object.defineProperty(Material, "TriangleFillMode", {
  36209. /**
  36210. * Returns the triangle fill mode
  36211. */
  36212. get: function () {
  36213. return Material._TriangleFillMode;
  36214. },
  36215. enumerable: true,
  36216. configurable: true
  36217. });
  36218. Object.defineProperty(Material, "WireFrameFillMode", {
  36219. /**
  36220. * Returns the wireframe mode
  36221. */
  36222. get: function () {
  36223. return Material._WireFrameFillMode;
  36224. },
  36225. enumerable: true,
  36226. configurable: true
  36227. });
  36228. Object.defineProperty(Material, "PointFillMode", {
  36229. /**
  36230. * Returns the point fill mode
  36231. */
  36232. get: function () {
  36233. return Material._PointFillMode;
  36234. },
  36235. enumerable: true,
  36236. configurable: true
  36237. });
  36238. Object.defineProperty(Material, "PointListDrawMode", {
  36239. /**
  36240. * Returns the point list draw mode
  36241. */
  36242. get: function () {
  36243. return Material._PointListDrawMode;
  36244. },
  36245. enumerable: true,
  36246. configurable: true
  36247. });
  36248. Object.defineProperty(Material, "LineListDrawMode", {
  36249. /**
  36250. * Returns the line list draw mode
  36251. */
  36252. get: function () {
  36253. return Material._LineListDrawMode;
  36254. },
  36255. enumerable: true,
  36256. configurable: true
  36257. });
  36258. Object.defineProperty(Material, "LineLoopDrawMode", {
  36259. /**
  36260. * Returns the line loop draw mode
  36261. */
  36262. get: function () {
  36263. return Material._LineLoopDrawMode;
  36264. },
  36265. enumerable: true,
  36266. configurable: true
  36267. });
  36268. Object.defineProperty(Material, "LineStripDrawMode", {
  36269. /**
  36270. * Returns the line strip draw mode
  36271. */
  36272. get: function () {
  36273. return Material._LineStripDrawMode;
  36274. },
  36275. enumerable: true,
  36276. configurable: true
  36277. });
  36278. Object.defineProperty(Material, "TriangleStripDrawMode", {
  36279. /**
  36280. * Returns the triangle strip draw mode
  36281. */
  36282. get: function () {
  36283. return Material._TriangleStripDrawMode;
  36284. },
  36285. enumerable: true,
  36286. configurable: true
  36287. });
  36288. Object.defineProperty(Material, "TriangleFanDrawMode", {
  36289. /**
  36290. * Returns the triangle fan draw mode
  36291. */
  36292. get: function () {
  36293. return Material._TriangleFanDrawMode;
  36294. },
  36295. enumerable: true,
  36296. configurable: true
  36297. });
  36298. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  36299. /**
  36300. * Returns the clock-wise side orientation
  36301. */
  36302. get: function () {
  36303. return Material._ClockWiseSideOrientation;
  36304. },
  36305. enumerable: true,
  36306. configurable: true
  36307. });
  36308. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  36309. /**
  36310. * Returns the counter clock-wise side orientation
  36311. */
  36312. get: function () {
  36313. return Material._CounterClockWiseSideOrientation;
  36314. },
  36315. enumerable: true,
  36316. configurable: true
  36317. });
  36318. Object.defineProperty(Material.prototype, "alpha", {
  36319. /**
  36320. * Gets the alpha value of the material
  36321. */
  36322. get: function () {
  36323. return this._alpha;
  36324. },
  36325. /**
  36326. * Sets the alpha value of the material
  36327. */
  36328. set: function (value) {
  36329. if (this._alpha === value) {
  36330. return;
  36331. }
  36332. this._alpha = value;
  36333. this.markAsDirty(Material.MiscDirtyFlag);
  36334. },
  36335. enumerable: true,
  36336. configurable: true
  36337. });
  36338. Object.defineProperty(Material.prototype, "backFaceCulling", {
  36339. /**
  36340. * Gets the back-face culling state
  36341. */
  36342. get: function () {
  36343. return this._backFaceCulling;
  36344. },
  36345. /**
  36346. * Sets the back-face culling state
  36347. */
  36348. set: function (value) {
  36349. if (this._backFaceCulling === value) {
  36350. return;
  36351. }
  36352. this._backFaceCulling = value;
  36353. this.markAsDirty(Material.TextureDirtyFlag);
  36354. },
  36355. enumerable: true,
  36356. configurable: true
  36357. });
  36358. Object.defineProperty(Material.prototype, "hasRenderTargetTextures", {
  36359. /**
  36360. * Gets a boolean indicating that current material needs to register RTT
  36361. */
  36362. get: function () {
  36363. return false;
  36364. },
  36365. enumerable: true,
  36366. configurable: true
  36367. });
  36368. Object.defineProperty(Material.prototype, "onDispose", {
  36369. /**
  36370. * Called during a dispose event
  36371. */
  36372. set: function (callback) {
  36373. if (this._onDisposeObserver) {
  36374. this.onDisposeObservable.remove(this._onDisposeObserver);
  36375. }
  36376. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  36377. },
  36378. enumerable: true,
  36379. configurable: true
  36380. });
  36381. Object.defineProperty(Material.prototype, "onBindObservable", {
  36382. /**
  36383. * An event triggered when the material is bound
  36384. */
  36385. get: function () {
  36386. if (!this._onBindObservable) {
  36387. this._onBindObservable = new BABYLON.Observable();
  36388. }
  36389. return this._onBindObservable;
  36390. },
  36391. enumerable: true,
  36392. configurable: true
  36393. });
  36394. Object.defineProperty(Material.prototype, "onBind", {
  36395. /**
  36396. * Called during a bind event
  36397. */
  36398. set: function (callback) {
  36399. if (this._onBindObserver) {
  36400. this.onBindObservable.remove(this._onBindObserver);
  36401. }
  36402. this._onBindObserver = this.onBindObservable.add(callback);
  36403. },
  36404. enumerable: true,
  36405. configurable: true
  36406. });
  36407. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  36408. /**
  36409. * An event triggered when the material is unbound
  36410. */
  36411. get: function () {
  36412. if (!this._onUnBindObservable) {
  36413. this._onUnBindObservable = new BABYLON.Observable();
  36414. }
  36415. return this._onUnBindObservable;
  36416. },
  36417. enumerable: true,
  36418. configurable: true
  36419. });
  36420. Object.defineProperty(Material.prototype, "alphaMode", {
  36421. /**
  36422. * Gets the value of the alpha mode
  36423. */
  36424. get: function () {
  36425. return this._alphaMode;
  36426. },
  36427. /**
  36428. * Sets the value of the alpha mode.
  36429. *
  36430. * | Value | Type | Description |
  36431. * | --- | --- | --- |
  36432. * | 0 | ALPHA_DISABLE | |
  36433. * | 1 | ALPHA_ADD | |
  36434. * | 2 | ALPHA_COMBINE | |
  36435. * | 3 | ALPHA_SUBTRACT | |
  36436. * | 4 | ALPHA_MULTIPLY | |
  36437. * | 5 | ALPHA_MAXIMIZED | |
  36438. * | 6 | ALPHA_ONEONE | |
  36439. * | 7 | ALPHA_PREMULTIPLIED | |
  36440. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  36441. * | 9 | ALPHA_INTERPOLATE | |
  36442. * | 10 | ALPHA_SCREENMODE | |
  36443. *
  36444. */
  36445. set: function (value) {
  36446. if (this._alphaMode === value) {
  36447. return;
  36448. }
  36449. this._alphaMode = value;
  36450. this.markAsDirty(Material.TextureDirtyFlag);
  36451. },
  36452. enumerable: true,
  36453. configurable: true
  36454. });
  36455. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  36456. /**
  36457. * Gets the depth pre-pass value
  36458. */
  36459. get: function () {
  36460. return this._needDepthPrePass;
  36461. },
  36462. /**
  36463. * Sets the need depth pre-pass value
  36464. */
  36465. set: function (value) {
  36466. if (this._needDepthPrePass === value) {
  36467. return;
  36468. }
  36469. this._needDepthPrePass = value;
  36470. if (this._needDepthPrePass) {
  36471. this.checkReadyOnEveryCall = true;
  36472. }
  36473. },
  36474. enumerable: true,
  36475. configurable: true
  36476. });
  36477. Object.defineProperty(Material.prototype, "fogEnabled", {
  36478. /**
  36479. * Gets the value of the fog enabled state
  36480. */
  36481. get: function () {
  36482. return this._fogEnabled;
  36483. },
  36484. /**
  36485. * Sets the state for enabling fog
  36486. */
  36487. set: function (value) {
  36488. if (this._fogEnabled === value) {
  36489. return;
  36490. }
  36491. this._fogEnabled = value;
  36492. this.markAsDirty(Material.MiscDirtyFlag);
  36493. },
  36494. enumerable: true,
  36495. configurable: true
  36496. });
  36497. Object.defineProperty(Material.prototype, "wireframe", {
  36498. /**
  36499. * Gets a value specifying if wireframe mode is enabled
  36500. */
  36501. get: function () {
  36502. switch (this._fillMode) {
  36503. case Material.WireFrameFillMode:
  36504. case Material.LineListDrawMode:
  36505. case Material.LineLoopDrawMode:
  36506. case Material.LineStripDrawMode:
  36507. return true;
  36508. }
  36509. return this._scene.forceWireframe;
  36510. },
  36511. /**
  36512. * Sets the state of wireframe mode
  36513. */
  36514. set: function (value) {
  36515. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  36516. },
  36517. enumerable: true,
  36518. configurable: true
  36519. });
  36520. Object.defineProperty(Material.prototype, "pointsCloud", {
  36521. /**
  36522. * Gets the value specifying if point clouds are enabled
  36523. */
  36524. get: function () {
  36525. switch (this._fillMode) {
  36526. case Material.PointFillMode:
  36527. case Material.PointListDrawMode:
  36528. return true;
  36529. }
  36530. return this._scene.forcePointsCloud;
  36531. },
  36532. /**
  36533. * Sets the state of point cloud mode
  36534. */
  36535. set: function (value) {
  36536. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  36537. },
  36538. enumerable: true,
  36539. configurable: true
  36540. });
  36541. Object.defineProperty(Material.prototype, "fillMode", {
  36542. /**
  36543. * Gets the material fill mode
  36544. */
  36545. get: function () {
  36546. return this._fillMode;
  36547. },
  36548. /**
  36549. * Sets the material fill mode
  36550. */
  36551. set: function (value) {
  36552. if (this._fillMode === value) {
  36553. return;
  36554. }
  36555. this._fillMode = value;
  36556. this.markAsDirty(Material.MiscDirtyFlag);
  36557. },
  36558. enumerable: true,
  36559. configurable: true
  36560. });
  36561. /**
  36562. * Returns a string representation of the current material
  36563. * @param fullDetails defines a boolean indicating which levels of logging is desired
  36564. * @returns a string with material information
  36565. */
  36566. Material.prototype.toString = function (fullDetails) {
  36567. var ret = "Name: " + this.name;
  36568. if (fullDetails) {
  36569. }
  36570. return ret;
  36571. };
  36572. /**
  36573. * Gets the class name of the material
  36574. * @returns a string with the class name of the material
  36575. */
  36576. Material.prototype.getClassName = function () {
  36577. return "Material";
  36578. };
  36579. Object.defineProperty(Material.prototype, "isFrozen", {
  36580. /**
  36581. * Specifies if updates for the material been locked
  36582. */
  36583. get: function () {
  36584. return this.checkReadyOnlyOnce;
  36585. },
  36586. enumerable: true,
  36587. configurable: true
  36588. });
  36589. /**
  36590. * Locks updates for the material
  36591. */
  36592. Material.prototype.freeze = function () {
  36593. this.checkReadyOnlyOnce = true;
  36594. };
  36595. /**
  36596. * Unlocks updates for the material
  36597. */
  36598. Material.prototype.unfreeze = function () {
  36599. this.checkReadyOnlyOnce = false;
  36600. };
  36601. /**
  36602. * Specifies if the material is ready to be used
  36603. * @param mesh defines the mesh to check
  36604. * @param useInstances specifies if instances should be used
  36605. * @returns a boolean indicating if the material is ready to be used
  36606. */
  36607. Material.prototype.isReady = function (mesh, useInstances) {
  36608. return true;
  36609. };
  36610. /**
  36611. * Specifies that the submesh is ready to be used
  36612. * @param mesh defines the mesh to check
  36613. * @param subMesh defines which submesh to check
  36614. * @param useInstances specifies that instances should be used
  36615. * @returns a boolean indicating that the submesh is ready or not
  36616. */
  36617. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  36618. return false;
  36619. };
  36620. /**
  36621. * Returns the material effect
  36622. * @returns the effect associated with the material
  36623. */
  36624. Material.prototype.getEffect = function () {
  36625. return this._effect;
  36626. };
  36627. /**
  36628. * Returns the current scene
  36629. * @returns a Scene
  36630. */
  36631. Material.prototype.getScene = function () {
  36632. return this._scene;
  36633. };
  36634. /**
  36635. * Specifies if the material will require alpha blending
  36636. * @returns a boolean specifying if alpha blending is needed
  36637. */
  36638. Material.prototype.needAlphaBlending = function () {
  36639. return (this.alpha < 1.0);
  36640. };
  36641. /**
  36642. * Specifies if the mesh will require alpha blending
  36643. * @param mesh defines the mesh to check
  36644. * @returns a boolean specifying if alpha blending is needed for the mesh
  36645. */
  36646. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  36647. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  36648. };
  36649. /**
  36650. * Specifies if this material should be rendered in alpha test mode
  36651. * @returns a boolean specifying if an alpha test is needed.
  36652. */
  36653. Material.prototype.needAlphaTesting = function () {
  36654. return false;
  36655. };
  36656. /**
  36657. * Gets the texture used for the alpha test
  36658. * @returns the texture to use for alpha testing
  36659. */
  36660. Material.prototype.getAlphaTestTexture = function () {
  36661. return null;
  36662. };
  36663. /**
  36664. * Marks the material to indicate that it needs to be re-calculated
  36665. */
  36666. Material.prototype.markDirty = function () {
  36667. this._wasPreviouslyReady = false;
  36668. };
  36669. /** @hidden */
  36670. Material.prototype._preBind = function (effect, overrideOrientation) {
  36671. if (overrideOrientation === void 0) { overrideOrientation = null; }
  36672. var engine = this._scene.getEngine();
  36673. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  36674. var reverse = orientation === Material.ClockWiseSideOrientation;
  36675. engine.enableEffect(effect ? effect : this._effect);
  36676. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  36677. return reverse;
  36678. };
  36679. /**
  36680. * Binds the material to the mesh
  36681. * @param world defines the world transformation matrix
  36682. * @param mesh defines the mesh to bind the material to
  36683. */
  36684. Material.prototype.bind = function (world, mesh) {
  36685. };
  36686. /**
  36687. * Binds the submesh to the material
  36688. * @param world defines the world transformation matrix
  36689. * @param mesh defines the mesh containing the submesh
  36690. * @param subMesh defines the submesh to bind the material to
  36691. */
  36692. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  36693. };
  36694. /**
  36695. * Binds the world matrix to the material
  36696. * @param world defines the world transformation matrix
  36697. */
  36698. Material.prototype.bindOnlyWorldMatrix = function (world) {
  36699. };
  36700. /**
  36701. * Binds the scene's uniform buffer to the effect.
  36702. * @param effect defines the effect to bind to the scene uniform buffer
  36703. * @param sceneUbo defines the uniform buffer storing scene data
  36704. */
  36705. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  36706. sceneUbo.bindToEffect(effect, "Scene");
  36707. };
  36708. /**
  36709. * Binds the view matrix to the effect
  36710. * @param effect defines the effect to bind the view matrix to
  36711. */
  36712. Material.prototype.bindView = function (effect) {
  36713. if (!this._useUBO) {
  36714. effect.setMatrix("view", this.getScene().getViewMatrix());
  36715. }
  36716. else {
  36717. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  36718. }
  36719. };
  36720. /**
  36721. * Binds the view projection matrix to the effect
  36722. * @param effect defines the effect to bind the view projection matrix to
  36723. */
  36724. Material.prototype.bindViewProjection = function (effect) {
  36725. if (!this._useUBO) {
  36726. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  36727. }
  36728. else {
  36729. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  36730. }
  36731. };
  36732. /**
  36733. * Specifies if material alpha testing should be turned on for the mesh
  36734. * @param mesh defines the mesh to check
  36735. */
  36736. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  36737. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  36738. };
  36739. /**
  36740. * Processes to execute after binding the material to a mesh
  36741. * @param mesh defines the rendered mesh
  36742. */
  36743. Material.prototype._afterBind = function (mesh) {
  36744. this._scene._cachedMaterial = this;
  36745. if (mesh) {
  36746. this._scene._cachedVisibility = mesh.visibility;
  36747. }
  36748. else {
  36749. this._scene._cachedVisibility = 1;
  36750. }
  36751. if (this._onBindObservable && mesh) {
  36752. this._onBindObservable.notifyObservers(mesh);
  36753. }
  36754. if (this.disableDepthWrite) {
  36755. var engine = this._scene.getEngine();
  36756. this._cachedDepthWriteState = engine.getDepthWrite();
  36757. engine.setDepthWrite(false);
  36758. }
  36759. };
  36760. /**
  36761. * Unbinds the material from the mesh
  36762. */
  36763. Material.prototype.unbind = function () {
  36764. if (this._onUnBindObservable) {
  36765. this._onUnBindObservable.notifyObservers(this);
  36766. }
  36767. if (this.disableDepthWrite) {
  36768. var engine = this._scene.getEngine();
  36769. engine.setDepthWrite(this._cachedDepthWriteState);
  36770. }
  36771. };
  36772. /**
  36773. * Gets the active textures from the material
  36774. * @returns an array of textures
  36775. */
  36776. Material.prototype.getActiveTextures = function () {
  36777. return [];
  36778. };
  36779. /**
  36780. * Specifies if the material uses a texture
  36781. * @param texture defines the texture to check against the material
  36782. * @returns a boolean specifying if the material uses the texture
  36783. */
  36784. Material.prototype.hasTexture = function (texture) {
  36785. return false;
  36786. };
  36787. /**
  36788. * Makes a duplicate of the material, and gives it a new name
  36789. * @param name defines the new name for the duplicated material
  36790. * @returns the cloned material
  36791. */
  36792. Material.prototype.clone = function (name) {
  36793. return null;
  36794. };
  36795. /**
  36796. * Gets the meshes bound to the material
  36797. * @returns an array of meshes bound to the material
  36798. */
  36799. Material.prototype.getBindedMeshes = function () {
  36800. var result = new Array();
  36801. for (var index = 0; index < this._scene.meshes.length; index++) {
  36802. var mesh = this._scene.meshes[index];
  36803. if (mesh.material === this) {
  36804. result.push(mesh);
  36805. }
  36806. }
  36807. return result;
  36808. };
  36809. /**
  36810. * Force shader compilation
  36811. * @param mesh defines the mesh associated with this material
  36812. * @param onCompiled defines a function to execute once the material is compiled
  36813. * @param options defines the options to configure the compilation
  36814. */
  36815. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  36816. var _this = this;
  36817. var localOptions = __assign({ clipPlane: false }, options);
  36818. var subMesh = new BABYLON.BaseSubMesh();
  36819. var scene = this.getScene();
  36820. var checkReady = function () {
  36821. if (!_this._scene || !_this._scene.getEngine()) {
  36822. return;
  36823. }
  36824. if (subMesh._materialDefines) {
  36825. subMesh._materialDefines._renderId = -1;
  36826. }
  36827. var clipPlaneState = scene.clipPlane;
  36828. if (localOptions.clipPlane) {
  36829. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  36830. }
  36831. if (_this.storeEffectOnSubMeshes) {
  36832. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  36833. if (onCompiled) {
  36834. onCompiled(_this);
  36835. }
  36836. }
  36837. else {
  36838. setTimeout(checkReady, 16);
  36839. }
  36840. }
  36841. else {
  36842. if (_this.isReady(mesh)) {
  36843. if (onCompiled) {
  36844. onCompiled(_this);
  36845. }
  36846. }
  36847. else {
  36848. setTimeout(checkReady, 16);
  36849. }
  36850. }
  36851. if (localOptions.clipPlane) {
  36852. scene.clipPlane = clipPlaneState;
  36853. }
  36854. };
  36855. checkReady();
  36856. };
  36857. /**
  36858. * Force shader compilation
  36859. * @param mesh defines the mesh that will use this material
  36860. * @param options defines additional options for compiling the shaders
  36861. * @returns a promise that resolves when the compilation completes
  36862. */
  36863. Material.prototype.forceCompilationAsync = function (mesh, options) {
  36864. var _this = this;
  36865. return new Promise(function (resolve) {
  36866. _this.forceCompilation(mesh, function () {
  36867. resolve();
  36868. }, options);
  36869. });
  36870. };
  36871. /**
  36872. * Marks a define in the material to indicate that it needs to be re-computed
  36873. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  36874. */
  36875. Material.prototype.markAsDirty = function (flag) {
  36876. if (flag & Material.TextureDirtyFlag) {
  36877. this._markAllSubMeshesAsTexturesDirty();
  36878. }
  36879. if (flag & Material.LightDirtyFlag) {
  36880. this._markAllSubMeshesAsLightsDirty();
  36881. }
  36882. if (flag & Material.FresnelDirtyFlag) {
  36883. this._markAllSubMeshesAsFresnelDirty();
  36884. }
  36885. if (flag & Material.AttributesDirtyFlag) {
  36886. this._markAllSubMeshesAsAttributesDirty();
  36887. }
  36888. if (flag & Material.MiscDirtyFlag) {
  36889. this._markAllSubMeshesAsMiscDirty();
  36890. }
  36891. this.getScene().resetCachedMaterial();
  36892. };
  36893. /**
  36894. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  36895. * @param func defines a function which checks material defines against the submeshes
  36896. */
  36897. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  36898. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  36899. var mesh = _a[_i];
  36900. if (!mesh.subMeshes) {
  36901. continue;
  36902. }
  36903. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  36904. var subMesh = _c[_b];
  36905. if (subMesh.getMaterial() !== this) {
  36906. continue;
  36907. }
  36908. if (!subMesh._materialDefines) {
  36909. continue;
  36910. }
  36911. func(subMesh._materialDefines);
  36912. }
  36913. }
  36914. };
  36915. /**
  36916. * Indicates that image processing needs to be re-calculated for all submeshes
  36917. */
  36918. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  36919. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  36920. };
  36921. /**
  36922. * Indicates that textures need to be re-calculated for all submeshes
  36923. */
  36924. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  36925. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  36926. };
  36927. /**
  36928. * Indicates that fresnel needs to be re-calculated for all submeshes
  36929. */
  36930. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  36931. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  36932. };
  36933. /**
  36934. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  36935. */
  36936. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  36937. this._markAllSubMeshesAsDirty(function (defines) {
  36938. defines.markAsFresnelDirty();
  36939. defines.markAsMiscDirty();
  36940. });
  36941. };
  36942. /**
  36943. * Indicates that lights need to be re-calculated for all submeshes
  36944. */
  36945. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  36946. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  36947. };
  36948. /**
  36949. * Indicates that attributes need to be re-calculated for all submeshes
  36950. */
  36951. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  36952. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  36953. };
  36954. /**
  36955. * Indicates that misc needs to be re-calculated for all submeshes
  36956. */
  36957. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  36958. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  36959. };
  36960. /**
  36961. * Indicates that textures and misc need to be re-calculated for all submeshes
  36962. */
  36963. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  36964. this._markAllSubMeshesAsDirty(function (defines) {
  36965. defines.markAsTexturesDirty();
  36966. defines.markAsMiscDirty();
  36967. });
  36968. };
  36969. /**
  36970. * Disposes the material
  36971. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  36972. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  36973. */
  36974. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  36975. // Animations
  36976. this.getScene().stopAnimation(this);
  36977. this.getScene().freeProcessedMaterials();
  36978. // Remove from scene
  36979. var index = this._scene.materials.indexOf(this);
  36980. if (index >= 0) {
  36981. this._scene.materials.splice(index, 1);
  36982. }
  36983. this._scene.onMaterialRemovedObservable.notifyObservers(this);
  36984. // Remove from meshes
  36985. for (index = 0; index < this._scene.meshes.length; index++) {
  36986. var mesh = this._scene.meshes[index];
  36987. if (mesh.material === this) {
  36988. mesh.material = null;
  36989. if (mesh.geometry) {
  36990. var geometry = (mesh.geometry);
  36991. if (this.storeEffectOnSubMeshes) {
  36992. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  36993. var subMesh = _a[_i];
  36994. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  36995. if (forceDisposeEffect && subMesh._materialEffect) {
  36996. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  36997. }
  36998. }
  36999. }
  37000. else {
  37001. geometry._releaseVertexArrayObject(this._effect);
  37002. }
  37003. }
  37004. }
  37005. }
  37006. this._uniformBuffer.dispose();
  37007. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  37008. if (forceDisposeEffect && this._effect) {
  37009. if (!this.storeEffectOnSubMeshes) {
  37010. this._scene.getEngine()._releaseEffect(this._effect);
  37011. }
  37012. this._effect = null;
  37013. }
  37014. // Callback
  37015. this.onDisposeObservable.notifyObservers(this);
  37016. this.onDisposeObservable.clear();
  37017. if (this._onBindObservable) {
  37018. this._onBindObservable.clear();
  37019. }
  37020. if (this._onUnBindObservable) {
  37021. this._onUnBindObservable.clear();
  37022. }
  37023. };
  37024. /**
  37025. * Serializes this material
  37026. * @returns the serialized material object
  37027. */
  37028. Material.prototype.serialize = function () {
  37029. return BABYLON.SerializationHelper.Serialize(this);
  37030. };
  37031. /**
  37032. * Creates a MultiMaterial from parsed MultiMaterial data.
  37033. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  37034. * @param scene defines the hosting scene
  37035. * @returns a new MultiMaterial
  37036. */
  37037. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  37038. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  37039. multiMaterial.id = parsedMultiMaterial.id;
  37040. if (BABYLON.Tags) {
  37041. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  37042. }
  37043. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  37044. var subMatId = parsedMultiMaterial.materials[matIndex];
  37045. if (subMatId) {
  37046. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  37047. }
  37048. else {
  37049. multiMaterial.subMaterials.push(null);
  37050. }
  37051. }
  37052. return multiMaterial;
  37053. };
  37054. /**
  37055. * Creates a material from parsed material data
  37056. * @param parsedMaterial defines parsed material data
  37057. * @param scene defines the hosting scene
  37058. * @param rootUrl defines the root URL to use to load textures
  37059. * @returns a new material
  37060. */
  37061. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  37062. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  37063. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  37064. }
  37065. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  37066. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  37067. if (!BABYLON.LegacyPBRMaterial) {
  37068. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  37069. return;
  37070. }
  37071. }
  37072. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  37073. return materialType.Parse(parsedMaterial, scene, rootUrl);
  37074. };
  37075. // Triangle views
  37076. Material._TriangleFillMode = 0;
  37077. Material._WireFrameFillMode = 1;
  37078. Material._PointFillMode = 2;
  37079. // Draw modes
  37080. Material._PointListDrawMode = 3;
  37081. Material._LineListDrawMode = 4;
  37082. Material._LineLoopDrawMode = 5;
  37083. Material._LineStripDrawMode = 6;
  37084. Material._TriangleStripDrawMode = 7;
  37085. Material._TriangleFanDrawMode = 8;
  37086. /**
  37087. * Stores the clock-wise side orientation
  37088. */
  37089. Material._ClockWiseSideOrientation = 0;
  37090. /**
  37091. * Stores the counter clock-wise side orientation
  37092. */
  37093. Material._CounterClockWiseSideOrientation = 1;
  37094. /**
  37095. * The dirty texture flag value
  37096. */
  37097. Material.TextureDirtyFlag = 1;
  37098. /**
  37099. * The dirty light flag value
  37100. */
  37101. Material.LightDirtyFlag = 2;
  37102. /**
  37103. * The dirty fresnel flag value
  37104. */
  37105. Material.FresnelDirtyFlag = 4;
  37106. /**
  37107. * The dirty attribute flag value
  37108. */
  37109. Material.AttributesDirtyFlag = 8;
  37110. /**
  37111. * The dirty misc flag value
  37112. */
  37113. Material.MiscDirtyFlag = 16;
  37114. /**
  37115. * The all dirty flag value
  37116. */
  37117. Material.AllDirtyFlag = 31;
  37118. __decorate([
  37119. BABYLON.serialize()
  37120. ], Material.prototype, "id", void 0);
  37121. __decorate([
  37122. BABYLON.serialize()
  37123. ], Material.prototype, "uniqueId", void 0);
  37124. __decorate([
  37125. BABYLON.serialize()
  37126. ], Material.prototype, "name", void 0);
  37127. __decorate([
  37128. BABYLON.serialize()
  37129. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  37130. __decorate([
  37131. BABYLON.serialize()
  37132. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  37133. __decorate([
  37134. BABYLON.serialize()
  37135. ], Material.prototype, "state", void 0);
  37136. __decorate([
  37137. BABYLON.serialize("alpha")
  37138. ], Material.prototype, "_alpha", void 0);
  37139. __decorate([
  37140. BABYLON.serialize("backFaceCulling")
  37141. ], Material.prototype, "_backFaceCulling", void 0);
  37142. __decorate([
  37143. BABYLON.serialize()
  37144. ], Material.prototype, "sideOrientation", void 0);
  37145. __decorate([
  37146. BABYLON.serialize("alphaMode")
  37147. ], Material.prototype, "_alphaMode", void 0);
  37148. __decorate([
  37149. BABYLON.serialize()
  37150. ], Material.prototype, "_needDepthPrePass", void 0);
  37151. __decorate([
  37152. BABYLON.serialize()
  37153. ], Material.prototype, "disableDepthWrite", void 0);
  37154. __decorate([
  37155. BABYLON.serialize()
  37156. ], Material.prototype, "forceDepthWrite", void 0);
  37157. __decorate([
  37158. BABYLON.serialize()
  37159. ], Material.prototype, "separateCullingPass", void 0);
  37160. __decorate([
  37161. BABYLON.serialize("fogEnabled")
  37162. ], Material.prototype, "_fogEnabled", void 0);
  37163. __decorate([
  37164. BABYLON.serialize()
  37165. ], Material.prototype, "pointSize", void 0);
  37166. __decorate([
  37167. BABYLON.serialize()
  37168. ], Material.prototype, "zOffset", void 0);
  37169. __decorate([
  37170. BABYLON.serialize()
  37171. ], Material.prototype, "wireframe", null);
  37172. __decorate([
  37173. BABYLON.serialize()
  37174. ], Material.prototype, "pointsCloud", null);
  37175. __decorate([
  37176. BABYLON.serialize()
  37177. ], Material.prototype, "fillMode", null);
  37178. return Material;
  37179. }());
  37180. BABYLON.Material = Material;
  37181. })(BABYLON || (BABYLON = {}));
  37182. //# sourceMappingURL=babylon.material.js.map
  37183. var BABYLON;
  37184. (function (BABYLON) {
  37185. /**
  37186. * Uniform buffer objects.
  37187. *
  37188. * Handles blocks of uniform on the GPU.
  37189. *
  37190. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  37191. *
  37192. * For more information, please refer to :
  37193. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  37194. */
  37195. var UniformBuffer = /** @class */ (function () {
  37196. /**
  37197. * Instantiates a new Uniform buffer objects.
  37198. *
  37199. * Handles blocks of uniform on the GPU.
  37200. *
  37201. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  37202. *
  37203. * For more information, please refer to :
  37204. * @see https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  37205. * @param engine Define the engine the buffer is associated with
  37206. * @param data Define the data contained in the buffer
  37207. * @param dynamic Define if the buffer is updatable
  37208. */
  37209. function UniformBuffer(engine, data, dynamic) {
  37210. this._engine = engine;
  37211. this._noUBO = !engine.supportsUniformBuffers;
  37212. this._dynamic = dynamic;
  37213. this._data = data || [];
  37214. this._uniformLocations = {};
  37215. this._uniformSizes = {};
  37216. this._uniformLocationPointer = 0;
  37217. this._needSync = false;
  37218. if (this._noUBO) {
  37219. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  37220. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  37221. this.updateFloat = this._updateFloatForEffect;
  37222. this.updateFloat2 = this._updateFloat2ForEffect;
  37223. this.updateFloat3 = this._updateFloat3ForEffect;
  37224. this.updateFloat4 = this._updateFloat4ForEffect;
  37225. this.updateMatrix = this._updateMatrixForEffect;
  37226. this.updateVector3 = this._updateVector3ForEffect;
  37227. this.updateVector4 = this._updateVector4ForEffect;
  37228. this.updateColor3 = this._updateColor3ForEffect;
  37229. this.updateColor4 = this._updateColor4ForEffect;
  37230. }
  37231. else {
  37232. this._engine._uniformBuffers.push(this);
  37233. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  37234. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  37235. this.updateFloat = this._updateFloatForUniform;
  37236. this.updateFloat2 = this._updateFloat2ForUniform;
  37237. this.updateFloat3 = this._updateFloat3ForUniform;
  37238. this.updateFloat4 = this._updateFloat4ForUniform;
  37239. this.updateMatrix = this._updateMatrixForUniform;
  37240. this.updateVector3 = this._updateVector3ForUniform;
  37241. this.updateVector4 = this._updateVector4ForUniform;
  37242. this.updateColor3 = this._updateColor3ForUniform;
  37243. this.updateColor4 = this._updateColor4ForUniform;
  37244. }
  37245. }
  37246. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  37247. /**
  37248. * Indicates if the buffer is using the WebGL2 UBO implementation,
  37249. * or just falling back on setUniformXXX calls.
  37250. */
  37251. get: function () {
  37252. return !this._noUBO;
  37253. },
  37254. enumerable: true,
  37255. configurable: true
  37256. });
  37257. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  37258. /**
  37259. * Indicates if the WebGL underlying uniform buffer is in sync
  37260. * with the javascript cache data.
  37261. */
  37262. get: function () {
  37263. return !this._needSync;
  37264. },
  37265. enumerable: true,
  37266. configurable: true
  37267. });
  37268. /**
  37269. * Indicates if the WebGL underlying uniform buffer is dynamic.
  37270. * Also, a dynamic UniformBuffer will disable cache verification and always
  37271. * update the underlying WebGL uniform buffer to the GPU.
  37272. * @returns if Dynamic, otherwise false
  37273. */
  37274. UniformBuffer.prototype.isDynamic = function () {
  37275. return this._dynamic !== undefined;
  37276. };
  37277. /**
  37278. * The data cache on JS side.
  37279. * @returns the underlying data as a float array
  37280. */
  37281. UniformBuffer.prototype.getData = function () {
  37282. return this._bufferData;
  37283. };
  37284. /**
  37285. * The underlying WebGL Uniform buffer.
  37286. * @returns the webgl buffer
  37287. */
  37288. UniformBuffer.prototype.getBuffer = function () {
  37289. return this._buffer;
  37290. };
  37291. /**
  37292. * std140 layout specifies how to align data within an UBO structure.
  37293. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  37294. * for specs.
  37295. */
  37296. UniformBuffer.prototype._fillAlignment = function (size) {
  37297. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  37298. // and 4x4 matrices
  37299. // TODO : change if other types are used
  37300. var alignment;
  37301. if (size <= 2) {
  37302. alignment = size;
  37303. }
  37304. else {
  37305. alignment = 4;
  37306. }
  37307. if ((this._uniformLocationPointer % alignment) !== 0) {
  37308. var oldPointer = this._uniformLocationPointer;
  37309. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  37310. var diff = this._uniformLocationPointer - oldPointer;
  37311. for (var i = 0; i < diff; i++) {
  37312. this._data.push(0);
  37313. }
  37314. }
  37315. };
  37316. /**
  37317. * Adds an uniform in the buffer.
  37318. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  37319. * for the layout to be correct !
  37320. * @param name Name of the uniform, as used in the uniform block in the shader.
  37321. * @param size Data size, or data directly.
  37322. */
  37323. UniformBuffer.prototype.addUniform = function (name, size) {
  37324. if (this._noUBO) {
  37325. return;
  37326. }
  37327. if (this._uniformLocations[name] !== undefined) {
  37328. // Already existing uniform
  37329. return;
  37330. }
  37331. // This function must be called in the order of the shader layout !
  37332. // size can be the size of the uniform, or data directly
  37333. var data;
  37334. if (size instanceof Array) {
  37335. data = size;
  37336. size = data.length;
  37337. }
  37338. else {
  37339. size = size;
  37340. data = [];
  37341. // Fill with zeros
  37342. for (var i = 0; i < size; i++) {
  37343. data.push(0);
  37344. }
  37345. }
  37346. this._fillAlignment(size);
  37347. this._uniformSizes[name] = size;
  37348. this._uniformLocations[name] = this._uniformLocationPointer;
  37349. this._uniformLocationPointer += size;
  37350. for (var i = 0; i < size; i++) {
  37351. this._data.push(data[i]);
  37352. }
  37353. this._needSync = true;
  37354. };
  37355. /**
  37356. * Adds a Matrix 4x4 to the uniform buffer.
  37357. * @param name Name of the uniform, as used in the uniform block in the shader.
  37358. * @param mat A 4x4 matrix.
  37359. */
  37360. UniformBuffer.prototype.addMatrix = function (name, mat) {
  37361. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  37362. };
  37363. /**
  37364. * Adds a vec2 to the uniform buffer.
  37365. * @param name Name of the uniform, as used in the uniform block in the shader.
  37366. * @param x Define the x component value of the vec2
  37367. * @param y Define the y component value of the vec2
  37368. */
  37369. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  37370. var temp = [x, y];
  37371. this.addUniform(name, temp);
  37372. };
  37373. /**
  37374. * Adds a vec3 to the uniform buffer.
  37375. * @param name Name of the uniform, as used in the uniform block in the shader.
  37376. * @param x Define the x component value of the vec3
  37377. * @param y Define the y component value of the vec3
  37378. * @param z Define the z component value of the vec3
  37379. */
  37380. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  37381. var temp = [x, y, z];
  37382. this.addUniform(name, temp);
  37383. };
  37384. /**
  37385. * Adds a vec3 to the uniform buffer.
  37386. * @param name Name of the uniform, as used in the uniform block in the shader.
  37387. * @param color Define the vec3 from a Color
  37388. */
  37389. UniformBuffer.prototype.addColor3 = function (name, color) {
  37390. var temp = new Array();
  37391. color.toArray(temp);
  37392. this.addUniform(name, temp);
  37393. };
  37394. /**
  37395. * Adds a vec4 to the uniform buffer.
  37396. * @param name Name of the uniform, as used in the uniform block in the shader.
  37397. * @param color Define the rgb components from a Color
  37398. * @param alpha Define the a component of the vec4
  37399. */
  37400. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  37401. var temp = new Array();
  37402. color.toArray(temp);
  37403. temp.push(alpha);
  37404. this.addUniform(name, temp);
  37405. };
  37406. /**
  37407. * Adds a vec3 to the uniform buffer.
  37408. * @param name Name of the uniform, as used in the uniform block in the shader.
  37409. * @param vector Define the vec3 components from a Vector
  37410. */
  37411. UniformBuffer.prototype.addVector3 = function (name, vector) {
  37412. var temp = new Array();
  37413. vector.toArray(temp);
  37414. this.addUniform(name, temp);
  37415. };
  37416. /**
  37417. * Adds a Matrix 3x3 to the uniform buffer.
  37418. * @param name Name of the uniform, as used in the uniform block in the shader.
  37419. */
  37420. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  37421. this.addUniform(name, 12);
  37422. };
  37423. /**
  37424. * Adds a Matrix 2x2 to the uniform buffer.
  37425. * @param name Name of the uniform, as used in the uniform block in the shader.
  37426. */
  37427. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  37428. this.addUniform(name, 8);
  37429. };
  37430. /**
  37431. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  37432. */
  37433. UniformBuffer.prototype.create = function () {
  37434. if (this._noUBO) {
  37435. return;
  37436. }
  37437. if (this._buffer) {
  37438. return; // nothing to do
  37439. }
  37440. // See spec, alignment must be filled as a vec4
  37441. this._fillAlignment(4);
  37442. this._bufferData = new Float32Array(this._data);
  37443. this._rebuild();
  37444. this._needSync = true;
  37445. };
  37446. /** @hidden */
  37447. UniformBuffer.prototype._rebuild = function () {
  37448. if (this._noUBO) {
  37449. return;
  37450. }
  37451. if (this._dynamic) {
  37452. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  37453. }
  37454. else {
  37455. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  37456. }
  37457. };
  37458. /**
  37459. * Updates the WebGL Uniform Buffer on the GPU.
  37460. * If the `dynamic` flag is set to true, no cache comparison is done.
  37461. * Otherwise, the buffer will be updated only if the cache differs.
  37462. */
  37463. UniformBuffer.prototype.update = function () {
  37464. if (!this._buffer) {
  37465. this.create();
  37466. return;
  37467. }
  37468. if (!this._dynamic && !this._needSync) {
  37469. return;
  37470. }
  37471. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  37472. this._needSync = false;
  37473. };
  37474. /**
  37475. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  37476. * @param uniformName Define the name of the uniform, as used in the uniform block in the shader.
  37477. * @param data Define the flattened data
  37478. * @param size Define the size of the data.
  37479. */
  37480. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  37481. var location = this._uniformLocations[uniformName];
  37482. if (location === undefined) {
  37483. if (this._buffer) {
  37484. // Cannot add an uniform if the buffer is already created
  37485. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  37486. return;
  37487. }
  37488. this.addUniform(uniformName, size);
  37489. location = this._uniformLocations[uniformName];
  37490. }
  37491. if (!this._buffer) {
  37492. this.create();
  37493. }
  37494. if (!this._dynamic) {
  37495. // Cache for static uniform buffers
  37496. var changed = false;
  37497. for (var i = 0; i < size; i++) {
  37498. if (this._bufferData[location + i] !== data[i]) {
  37499. changed = true;
  37500. this._bufferData[location + i] = data[i];
  37501. }
  37502. }
  37503. this._needSync = this._needSync || changed;
  37504. }
  37505. else {
  37506. // No cache for dynamic
  37507. for (var i = 0; i < size; i++) {
  37508. this._bufferData[location + i] = data[i];
  37509. }
  37510. }
  37511. };
  37512. // Update methods
  37513. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  37514. // To match std140, matrix must be realigned
  37515. for (var i = 0; i < 3; i++) {
  37516. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  37517. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  37518. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  37519. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  37520. }
  37521. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  37522. };
  37523. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  37524. this._currentEffect.setMatrix3x3(name, matrix);
  37525. };
  37526. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  37527. this._currentEffect.setMatrix2x2(name, matrix);
  37528. };
  37529. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  37530. // To match std140, matrix must be realigned
  37531. for (var i = 0; i < 2; i++) {
  37532. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  37533. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  37534. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  37535. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  37536. }
  37537. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  37538. };
  37539. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  37540. this._currentEffect.setFloat(name, x);
  37541. };
  37542. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  37543. UniformBuffer._tempBuffer[0] = x;
  37544. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  37545. };
  37546. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  37547. if (suffix === void 0) { suffix = ""; }
  37548. this._currentEffect.setFloat2(name + suffix, x, y);
  37549. };
  37550. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  37551. if (suffix === void 0) { suffix = ""; }
  37552. UniformBuffer._tempBuffer[0] = x;
  37553. UniformBuffer._tempBuffer[1] = y;
  37554. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  37555. };
  37556. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  37557. if (suffix === void 0) { suffix = ""; }
  37558. this._currentEffect.setFloat3(name + suffix, x, y, z);
  37559. };
  37560. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  37561. if (suffix === void 0) { suffix = ""; }
  37562. UniformBuffer._tempBuffer[0] = x;
  37563. UniformBuffer._tempBuffer[1] = y;
  37564. UniformBuffer._tempBuffer[2] = z;
  37565. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  37566. };
  37567. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  37568. if (suffix === void 0) { suffix = ""; }
  37569. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  37570. };
  37571. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  37572. if (suffix === void 0) { suffix = ""; }
  37573. UniformBuffer._tempBuffer[0] = x;
  37574. UniformBuffer._tempBuffer[1] = y;
  37575. UniformBuffer._tempBuffer[2] = z;
  37576. UniformBuffer._tempBuffer[3] = w;
  37577. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  37578. };
  37579. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  37580. this._currentEffect.setMatrix(name, mat);
  37581. };
  37582. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  37583. this.updateUniform(name, mat.toArray(), 16);
  37584. };
  37585. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  37586. this._currentEffect.setVector3(name, vector);
  37587. };
  37588. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  37589. vector.toArray(UniformBuffer._tempBuffer);
  37590. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  37591. };
  37592. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  37593. this._currentEffect.setVector4(name, vector);
  37594. };
  37595. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  37596. vector.toArray(UniformBuffer._tempBuffer);
  37597. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  37598. };
  37599. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  37600. if (suffix === void 0) { suffix = ""; }
  37601. this._currentEffect.setColor3(name + suffix, color);
  37602. };
  37603. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  37604. if (suffix === void 0) { suffix = ""; }
  37605. color.toArray(UniformBuffer._tempBuffer);
  37606. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  37607. };
  37608. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  37609. if (suffix === void 0) { suffix = ""; }
  37610. this._currentEffect.setColor4(name + suffix, color, alpha);
  37611. };
  37612. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  37613. if (suffix === void 0) { suffix = ""; }
  37614. color.toArray(UniformBuffer._tempBuffer);
  37615. UniformBuffer._tempBuffer[3] = alpha;
  37616. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  37617. };
  37618. /**
  37619. * Sets a sampler uniform on the effect.
  37620. * @param name Define the name of the sampler.
  37621. * @param texture Define the texture to set in the sampler
  37622. */
  37623. UniformBuffer.prototype.setTexture = function (name, texture) {
  37624. this._currentEffect.setTexture(name, texture);
  37625. };
  37626. /**
  37627. * Directly updates the value of the uniform in the cache AND on the GPU.
  37628. * @param uniformName Define the name of the uniform, as used in the uniform block in the shader.
  37629. * @param data Define the flattened data
  37630. */
  37631. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  37632. this.updateUniform(uniformName, data, data.length);
  37633. this.update();
  37634. };
  37635. /**
  37636. * Binds this uniform buffer to an effect.
  37637. * @param effect Define the effect to bind the buffer to
  37638. * @param name Name of the uniform block in the shader.
  37639. */
  37640. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  37641. this._currentEffect = effect;
  37642. if (this._noUBO || !this._buffer) {
  37643. return;
  37644. }
  37645. effect.bindUniformBuffer(this._buffer, name);
  37646. };
  37647. /**
  37648. * Disposes the uniform buffer.
  37649. */
  37650. UniformBuffer.prototype.dispose = function () {
  37651. if (this._noUBO) {
  37652. return;
  37653. }
  37654. var index = this._engine._uniformBuffers.indexOf(this);
  37655. if (index !== -1) {
  37656. this._engine._uniformBuffers.splice(index, 1);
  37657. }
  37658. if (!this._buffer) {
  37659. return;
  37660. }
  37661. if (this._engine._releaseBuffer(this._buffer)) {
  37662. this._buffer = null;
  37663. }
  37664. };
  37665. // Pool for avoiding memory leaks
  37666. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  37667. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  37668. return UniformBuffer;
  37669. }());
  37670. BABYLON.UniformBuffer = UniformBuffer;
  37671. })(BABYLON || (BABYLON = {}));
  37672. //# sourceMappingURL=babylon.uniformBuffer.js.map
  37673. var BABYLON;
  37674. (function (BABYLON) {
  37675. /**
  37676. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  37677. */
  37678. var VertexData = /** @class */ (function () {
  37679. function VertexData() {
  37680. }
  37681. /**
  37682. * Uses the passed data array to set the set the values for the specified kind of data
  37683. * @param data a linear array of floating numbers
  37684. * @param kind the type of data that is being set, eg positions, colors etc
  37685. */
  37686. VertexData.prototype.set = function (data, kind) {
  37687. switch (kind) {
  37688. case BABYLON.VertexBuffer.PositionKind:
  37689. this.positions = data;
  37690. break;
  37691. case BABYLON.VertexBuffer.NormalKind:
  37692. this.normals = data;
  37693. break;
  37694. case BABYLON.VertexBuffer.TangentKind:
  37695. this.tangents = data;
  37696. break;
  37697. case BABYLON.VertexBuffer.UVKind:
  37698. this.uvs = data;
  37699. break;
  37700. case BABYLON.VertexBuffer.UV2Kind:
  37701. this.uvs2 = data;
  37702. break;
  37703. case BABYLON.VertexBuffer.UV3Kind:
  37704. this.uvs3 = data;
  37705. break;
  37706. case BABYLON.VertexBuffer.UV4Kind:
  37707. this.uvs4 = data;
  37708. break;
  37709. case BABYLON.VertexBuffer.UV5Kind:
  37710. this.uvs5 = data;
  37711. break;
  37712. case BABYLON.VertexBuffer.UV6Kind:
  37713. this.uvs6 = data;
  37714. break;
  37715. case BABYLON.VertexBuffer.ColorKind:
  37716. this.colors = data;
  37717. break;
  37718. case BABYLON.VertexBuffer.MatricesIndicesKind:
  37719. this.matricesIndices = data;
  37720. break;
  37721. case BABYLON.VertexBuffer.MatricesWeightsKind:
  37722. this.matricesWeights = data;
  37723. break;
  37724. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  37725. this.matricesIndicesExtra = data;
  37726. break;
  37727. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  37728. this.matricesWeightsExtra = data;
  37729. break;
  37730. }
  37731. };
  37732. /**
  37733. * Associates the vertexData to the passed Mesh.
  37734. * Sets it as updatable or not (default `false`)
  37735. * @param mesh the mesh the vertexData is applied to
  37736. * @param updatable when used and having the value true allows new data to update the vertexData
  37737. * @returns the VertexData
  37738. */
  37739. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  37740. this._applyTo(mesh, updatable);
  37741. return this;
  37742. };
  37743. /**
  37744. * Associates the vertexData to the passed Geometry.
  37745. * Sets it as updatable or not (default `false`)
  37746. * @param geometry the geometry the vertexData is applied to
  37747. * @param updatable when used and having the value true allows new data to update the vertexData
  37748. * @returns VertexData
  37749. */
  37750. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  37751. this._applyTo(geometry, updatable);
  37752. return this;
  37753. };
  37754. /**
  37755. * Updates the associated mesh
  37756. * @param mesh the mesh to be updated
  37757. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  37758. * @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
  37759. * @returns VertexData
  37760. */
  37761. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  37762. this._update(mesh);
  37763. return this;
  37764. };
  37765. /**
  37766. * Updates the associated geometry
  37767. * @param geometry the geometry to be updated
  37768. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  37769. * @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
  37770. * @returns VertexData.
  37771. */
  37772. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  37773. this._update(geometry);
  37774. return this;
  37775. };
  37776. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  37777. if (updatable === void 0) { updatable = false; }
  37778. if (this.positions) {
  37779. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  37780. }
  37781. if (this.normals) {
  37782. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  37783. }
  37784. if (this.tangents) {
  37785. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  37786. }
  37787. if (this.uvs) {
  37788. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  37789. }
  37790. if (this.uvs2) {
  37791. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  37792. }
  37793. if (this.uvs3) {
  37794. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  37795. }
  37796. if (this.uvs4) {
  37797. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  37798. }
  37799. if (this.uvs5) {
  37800. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  37801. }
  37802. if (this.uvs6) {
  37803. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  37804. }
  37805. if (this.colors) {
  37806. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  37807. }
  37808. if (this.matricesIndices) {
  37809. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  37810. }
  37811. if (this.matricesWeights) {
  37812. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  37813. }
  37814. if (this.matricesIndicesExtra) {
  37815. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  37816. }
  37817. if (this.matricesWeightsExtra) {
  37818. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  37819. }
  37820. if (this.indices) {
  37821. meshOrGeometry.setIndices(this.indices, null, updatable);
  37822. }
  37823. else {
  37824. meshOrGeometry.setIndices([], null);
  37825. }
  37826. return this;
  37827. };
  37828. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  37829. if (this.positions) {
  37830. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  37831. }
  37832. if (this.normals) {
  37833. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  37834. }
  37835. if (this.tangents) {
  37836. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  37837. }
  37838. if (this.uvs) {
  37839. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  37840. }
  37841. if (this.uvs2) {
  37842. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  37843. }
  37844. if (this.uvs3) {
  37845. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  37846. }
  37847. if (this.uvs4) {
  37848. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  37849. }
  37850. if (this.uvs5) {
  37851. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  37852. }
  37853. if (this.uvs6) {
  37854. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  37855. }
  37856. if (this.colors) {
  37857. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  37858. }
  37859. if (this.matricesIndices) {
  37860. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  37861. }
  37862. if (this.matricesWeights) {
  37863. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  37864. }
  37865. if (this.matricesIndicesExtra) {
  37866. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  37867. }
  37868. if (this.matricesWeightsExtra) {
  37869. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  37870. }
  37871. if (this.indices) {
  37872. meshOrGeometry.setIndices(this.indices, null);
  37873. }
  37874. return this;
  37875. };
  37876. /**
  37877. * Transforms each position and each normal of the vertexData according to the passed Matrix
  37878. * @param matrix the transforming matrix
  37879. * @returns the VertexData
  37880. */
  37881. VertexData.prototype.transform = function (matrix) {
  37882. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  37883. var transformed = BABYLON.Vector3.Zero();
  37884. var index;
  37885. if (this.positions) {
  37886. var position = BABYLON.Vector3.Zero();
  37887. for (index = 0; index < this.positions.length; index += 3) {
  37888. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  37889. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  37890. this.positions[index] = transformed.x;
  37891. this.positions[index + 1] = transformed.y;
  37892. this.positions[index + 2] = transformed.z;
  37893. }
  37894. }
  37895. if (this.normals) {
  37896. var normal = BABYLON.Vector3.Zero();
  37897. for (index = 0; index < this.normals.length; index += 3) {
  37898. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  37899. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  37900. this.normals[index] = transformed.x;
  37901. this.normals[index + 1] = transformed.y;
  37902. this.normals[index + 2] = transformed.z;
  37903. }
  37904. }
  37905. if (this.tangents) {
  37906. var tangent = BABYLON.Vector4.Zero();
  37907. var tangentTransformed = BABYLON.Vector4.Zero();
  37908. for (index = 0; index < this.tangents.length; index += 4) {
  37909. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  37910. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  37911. this.tangents[index] = tangentTransformed.x;
  37912. this.tangents[index + 1] = tangentTransformed.y;
  37913. this.tangents[index + 2] = tangentTransformed.z;
  37914. this.tangents[index + 3] = tangentTransformed.w;
  37915. }
  37916. }
  37917. if (flip && this.indices) {
  37918. for (index = 0; index < this.indices.length; index += 3) {
  37919. var tmp = this.indices[index + 1];
  37920. this.indices[index + 1] = this.indices[index + 2];
  37921. this.indices[index + 2] = tmp;
  37922. }
  37923. }
  37924. return this;
  37925. };
  37926. /**
  37927. * Merges the passed VertexData into the current one
  37928. * @param other the VertexData to be merged into the current one
  37929. * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array
  37930. * @returns the modified VertexData
  37931. */
  37932. VertexData.prototype.merge = function (other, use32BitsIndices) {
  37933. if (use32BitsIndices === void 0) { use32BitsIndices = false; }
  37934. this._validate();
  37935. other._validate();
  37936. if (!this.normals !== !other.normals ||
  37937. !this.tangents !== !other.tangents ||
  37938. !this.uvs !== !other.uvs ||
  37939. !this.uvs2 !== !other.uvs2 ||
  37940. !this.uvs3 !== !other.uvs3 ||
  37941. !this.uvs4 !== !other.uvs4 ||
  37942. !this.uvs5 !== !other.uvs5 ||
  37943. !this.uvs6 !== !other.uvs6 ||
  37944. !this.colors !== !other.colors ||
  37945. !this.matricesIndices !== !other.matricesIndices ||
  37946. !this.matricesWeights !== !other.matricesWeights ||
  37947. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  37948. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  37949. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  37950. }
  37951. if (other.indices) {
  37952. if (!this.indices) {
  37953. this.indices = [];
  37954. }
  37955. var offset = this.positions ? this.positions.length / 3 : 0;
  37956. var isSrcTypedArray = this.indices.BYTES_PER_ELEMENT !== undefined;
  37957. if (isSrcTypedArray) {
  37958. var len = this.indices.length + other.indices.length;
  37959. var temp = use32BitsIndices || this.indices instanceof Uint32Array ? new Uint32Array(len) : new Uint16Array(len);
  37960. temp.set(this.indices);
  37961. var decal = this.indices.length;
  37962. for (var index = 0; index < other.indices.length; index++) {
  37963. temp[decal + index] = other.indices[index] + offset;
  37964. }
  37965. this.indices = temp;
  37966. }
  37967. else {
  37968. for (var index = 0; index < other.indices.length; index++) {
  37969. this.indices.push(other.indices[index] + offset);
  37970. }
  37971. }
  37972. }
  37973. this.positions = this._mergeElement(this.positions, other.positions);
  37974. this.normals = this._mergeElement(this.normals, other.normals);
  37975. this.tangents = this._mergeElement(this.tangents, other.tangents);
  37976. this.uvs = this._mergeElement(this.uvs, other.uvs);
  37977. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  37978. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  37979. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  37980. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  37981. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  37982. this.colors = this._mergeElement(this.colors, other.colors);
  37983. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  37984. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  37985. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  37986. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  37987. return this;
  37988. };
  37989. VertexData.prototype._mergeElement = function (source, other) {
  37990. if (!source) {
  37991. return other;
  37992. }
  37993. if (!other) {
  37994. return source;
  37995. }
  37996. var len = other.length + source.length;
  37997. var isSrcTypedArray = source instanceof Float32Array;
  37998. var isOthTypedArray = other instanceof Float32Array;
  37999. // use non-loop method when the source is Float32Array
  38000. if (isSrcTypedArray) {
  38001. var ret32 = new Float32Array(len);
  38002. ret32.set(source);
  38003. ret32.set(other, source.length);
  38004. return ret32;
  38005. // source is number[], when other is also use concat
  38006. }
  38007. else if (!isOthTypedArray) {
  38008. return source.concat(other);
  38009. // source is a number[], but other is a Float32Array, loop required
  38010. }
  38011. else {
  38012. var ret = source.slice(0); // copy source to a separate array
  38013. for (var i = 0, len = other.length; i < len; i++) {
  38014. ret.push(other[i]);
  38015. }
  38016. return ret;
  38017. }
  38018. };
  38019. VertexData.prototype._validate = function () {
  38020. if (!this.positions) {
  38021. throw new Error("Positions are required");
  38022. }
  38023. var getElementCount = function (kind, values) {
  38024. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  38025. if ((values.length % stride) !== 0) {
  38026. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  38027. }
  38028. return values.length / stride;
  38029. };
  38030. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  38031. var validateElementCount = function (kind, values) {
  38032. var elementCount = getElementCount(kind, values);
  38033. if (elementCount !== positionsElementCount) {
  38034. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  38035. }
  38036. };
  38037. if (this.normals) {
  38038. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  38039. }
  38040. if (this.tangents) {
  38041. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  38042. }
  38043. if (this.uvs) {
  38044. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  38045. }
  38046. if (this.uvs2) {
  38047. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  38048. }
  38049. if (this.uvs3) {
  38050. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  38051. }
  38052. if (this.uvs4) {
  38053. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  38054. }
  38055. if (this.uvs5) {
  38056. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  38057. }
  38058. if (this.uvs6) {
  38059. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  38060. }
  38061. if (this.colors) {
  38062. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  38063. }
  38064. if (this.matricesIndices) {
  38065. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  38066. }
  38067. if (this.matricesWeights) {
  38068. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  38069. }
  38070. if (this.matricesIndicesExtra) {
  38071. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  38072. }
  38073. if (this.matricesWeightsExtra) {
  38074. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  38075. }
  38076. };
  38077. /**
  38078. * Serializes the VertexData
  38079. * @returns a serialized object
  38080. */
  38081. VertexData.prototype.serialize = function () {
  38082. var serializationObject = this.serialize();
  38083. if (this.positions) {
  38084. serializationObject.positions = this.positions;
  38085. }
  38086. if (this.normals) {
  38087. serializationObject.normals = this.normals;
  38088. }
  38089. if (this.tangents) {
  38090. serializationObject.tangents = this.tangents;
  38091. }
  38092. if (this.uvs) {
  38093. serializationObject.uvs = this.uvs;
  38094. }
  38095. if (this.uvs2) {
  38096. serializationObject.uvs2 = this.uvs2;
  38097. }
  38098. if (this.uvs3) {
  38099. serializationObject.uvs3 = this.uvs3;
  38100. }
  38101. if (this.uvs4) {
  38102. serializationObject.uvs4 = this.uvs4;
  38103. }
  38104. if (this.uvs5) {
  38105. serializationObject.uvs5 = this.uvs5;
  38106. }
  38107. if (this.uvs6) {
  38108. serializationObject.uvs6 = this.uvs6;
  38109. }
  38110. if (this.colors) {
  38111. serializationObject.colors = this.colors;
  38112. }
  38113. if (this.matricesIndices) {
  38114. serializationObject.matricesIndices = this.matricesIndices;
  38115. serializationObject.matricesIndices._isExpanded = true;
  38116. }
  38117. if (this.matricesWeights) {
  38118. serializationObject.matricesWeights = this.matricesWeights;
  38119. }
  38120. if (this.matricesIndicesExtra) {
  38121. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  38122. serializationObject.matricesIndicesExtra._isExpanded = true;
  38123. }
  38124. if (this.matricesWeightsExtra) {
  38125. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  38126. }
  38127. serializationObject.indices = this.indices;
  38128. return serializationObject;
  38129. };
  38130. // Statics
  38131. /**
  38132. * Extracts the vertexData from a mesh
  38133. * @param mesh the mesh from which to extract the VertexData
  38134. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  38135. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  38136. * @returns the object VertexData associated to the passed mesh
  38137. */
  38138. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  38139. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  38140. };
  38141. /**
  38142. * Extracts the vertexData from the geometry
  38143. * @param geometry the geometry from which to extract the VertexData
  38144. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  38145. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  38146. * @returns the object VertexData associated to the passed mesh
  38147. */
  38148. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  38149. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  38150. };
  38151. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  38152. var result = new VertexData();
  38153. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  38154. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  38155. }
  38156. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  38157. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  38158. }
  38159. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38160. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  38161. }
  38162. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38163. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  38164. }
  38165. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  38166. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  38167. }
  38168. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  38169. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  38170. }
  38171. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  38172. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  38173. }
  38174. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  38175. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  38176. }
  38177. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  38178. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  38179. }
  38180. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  38181. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  38182. }
  38183. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  38184. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  38185. }
  38186. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  38187. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  38188. }
  38189. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  38190. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  38191. }
  38192. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  38193. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  38194. }
  38195. result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
  38196. return result;
  38197. };
  38198. /**
  38199. * Creates the VertexData for a Ribbon
  38200. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  38201. * * pathArray array of paths, each of which an array of successive Vector3
  38202. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  38203. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  38204. * * 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
  38205. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38206. * * 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)
  38207. * * 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)
  38208. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  38209. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  38210. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  38211. * @returns the VertexData of the ribbon
  38212. */
  38213. VertexData.CreateRibbon = function (options) {
  38214. var pathArray = options.pathArray;
  38215. var closeArray = options.closeArray || false;
  38216. var closePath = options.closePath || false;
  38217. var invertUV = options.invertUV || false;
  38218. var defaultOffset = Math.floor(pathArray[0].length / 2);
  38219. var offset = options.offset || defaultOffset;
  38220. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  38221. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38222. var customUV = options.uvs;
  38223. var customColors = options.colors;
  38224. var positions = [];
  38225. var indices = [];
  38226. var normals = [];
  38227. var uvs = [];
  38228. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  38229. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  38230. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  38231. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  38232. var minlg; // minimal length among all paths from pathArray
  38233. var lg = []; // array of path lengths : nb of vertex per path
  38234. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  38235. var p; // path iterator
  38236. var i; // point iterator
  38237. var j; // point iterator
  38238. // if single path in pathArray
  38239. if (pathArray.length < 2) {
  38240. var ar1 = [];
  38241. var ar2 = [];
  38242. for (i = 0; i < pathArray[0].length - offset; i++) {
  38243. ar1.push(pathArray[0][i]);
  38244. ar2.push(pathArray[0][i + offset]);
  38245. }
  38246. pathArray = [ar1, ar2];
  38247. }
  38248. // positions and horizontal distances (u)
  38249. var idc = 0;
  38250. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  38251. var path;
  38252. var l;
  38253. minlg = pathArray[0].length;
  38254. var vectlg;
  38255. var dist;
  38256. for (p = 0; p < pathArray.length; p++) {
  38257. uTotalDistance[p] = 0;
  38258. us[p] = [0];
  38259. path = pathArray[p];
  38260. l = path.length;
  38261. minlg = (minlg < l) ? minlg : l;
  38262. j = 0;
  38263. while (j < l) {
  38264. positions.push(path[j].x, path[j].y, path[j].z);
  38265. if (j > 0) {
  38266. vectlg = path[j].subtract(path[j - 1]).length();
  38267. dist = vectlg + uTotalDistance[p];
  38268. us[p].push(dist);
  38269. uTotalDistance[p] = dist;
  38270. }
  38271. j++;
  38272. }
  38273. if (closePath) { // an extra hidden vertex is added in the "positions" array
  38274. j--;
  38275. positions.push(path[0].x, path[0].y, path[0].z);
  38276. vectlg = path[j].subtract(path[0]).length();
  38277. dist = vectlg + uTotalDistance[p];
  38278. us[p].push(dist);
  38279. uTotalDistance[p] = dist;
  38280. }
  38281. lg[p] = l + closePathCorr;
  38282. idx[p] = idc;
  38283. idc += (l + closePathCorr);
  38284. }
  38285. // vertical distances (v)
  38286. var path1;
  38287. var path2;
  38288. var vertex1 = null;
  38289. var vertex2 = null;
  38290. for (i = 0; i < minlg + closePathCorr; i++) {
  38291. vTotalDistance[i] = 0;
  38292. vs[i] = [0];
  38293. for (p = 0; p < pathArray.length - 1; p++) {
  38294. path1 = pathArray[p];
  38295. path2 = pathArray[p + 1];
  38296. if (i === minlg) { // closePath
  38297. vertex1 = path1[0];
  38298. vertex2 = path2[0];
  38299. }
  38300. else {
  38301. vertex1 = path1[i];
  38302. vertex2 = path2[i];
  38303. }
  38304. vectlg = vertex2.subtract(vertex1).length();
  38305. dist = vectlg + vTotalDistance[i];
  38306. vs[i].push(dist);
  38307. vTotalDistance[i] = dist;
  38308. }
  38309. if (closeArray && vertex2 && vertex1) {
  38310. path1 = pathArray[p];
  38311. path2 = pathArray[0];
  38312. if (i === minlg) { // closePath
  38313. vertex2 = path2[0];
  38314. }
  38315. vectlg = vertex2.subtract(vertex1).length();
  38316. dist = vectlg + vTotalDistance[i];
  38317. vTotalDistance[i] = dist;
  38318. }
  38319. }
  38320. // uvs
  38321. var u;
  38322. var v;
  38323. if (customUV) {
  38324. for (p = 0; p < customUV.length; p++) {
  38325. uvs.push(customUV[p].x, customUV[p].y);
  38326. }
  38327. }
  38328. else {
  38329. for (p = 0; p < pathArray.length; p++) {
  38330. for (i = 0; i < minlg + closePathCorr; i++) {
  38331. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  38332. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  38333. if (invertUV) {
  38334. uvs.push(v, u);
  38335. }
  38336. else {
  38337. uvs.push(u, v);
  38338. }
  38339. }
  38340. }
  38341. }
  38342. // indices
  38343. p = 0; // path index
  38344. var pi = 0; // positions array index
  38345. var l1 = lg[p] - 1; // path1 length
  38346. var l2 = lg[p + 1] - 1; // path2 length
  38347. var min = (l1 < l2) ? l1 : l2; // current path stop index
  38348. var shft = idx[1] - idx[0]; // shift
  38349. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  38350. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  38351. // 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
  38352. indices.push(pi, pi + shft, pi + 1);
  38353. indices.push(pi + shft + 1, pi + 1, pi + shft);
  38354. pi += 1;
  38355. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  38356. p++;
  38357. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  38358. shft = idx[0] - idx[p];
  38359. l1 = lg[p] - 1;
  38360. l2 = lg[0] - 1;
  38361. }
  38362. else {
  38363. shft = idx[p + 1] - idx[p];
  38364. l1 = lg[p] - 1;
  38365. l2 = lg[p + 1] - 1;
  38366. }
  38367. pi = idx[p];
  38368. min = (l1 < l2) ? l1 + pi : l2 + pi;
  38369. }
  38370. }
  38371. // normals
  38372. VertexData.ComputeNormals(positions, indices, normals);
  38373. if (closePath) { // update both the first and last vertex normals to their average value
  38374. var indexFirst = 0;
  38375. var indexLast = 0;
  38376. for (p = 0; p < pathArray.length; p++) {
  38377. indexFirst = idx[p] * 3;
  38378. if (p + 1 < pathArray.length) {
  38379. indexLast = (idx[p + 1] - 1) * 3;
  38380. }
  38381. else {
  38382. indexLast = normals.length - 3;
  38383. }
  38384. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  38385. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  38386. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  38387. normals[indexLast] = normals[indexFirst];
  38388. normals[indexLast + 1] = normals[indexFirst + 1];
  38389. normals[indexLast + 2] = normals[indexFirst + 2];
  38390. }
  38391. }
  38392. // sides
  38393. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38394. // Colors
  38395. var colors = null;
  38396. if (customColors) {
  38397. colors = new Float32Array(customColors.length * 4);
  38398. for (var c = 0; c < customColors.length; c++) {
  38399. colors[c * 4] = customColors[c].r;
  38400. colors[c * 4 + 1] = customColors[c].g;
  38401. colors[c * 4 + 2] = customColors[c].b;
  38402. colors[c * 4 + 3] = customColors[c].a;
  38403. }
  38404. }
  38405. // Result
  38406. var vertexData = new VertexData();
  38407. var positions32 = new Float32Array(positions);
  38408. var normals32 = new Float32Array(normals);
  38409. var uvs32 = new Float32Array(uvs);
  38410. vertexData.indices = indices;
  38411. vertexData.positions = positions32;
  38412. vertexData.normals = normals32;
  38413. vertexData.uvs = uvs32;
  38414. if (colors) {
  38415. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  38416. }
  38417. if (closePath) {
  38418. vertexData._idx = idx;
  38419. }
  38420. return vertexData;
  38421. };
  38422. /**
  38423. * Creates the VertexData for a box
  38424. * @param options an object used to set the following optional parameters for the box, required but can be empty
  38425. * * size sets the width, height and depth of the box to the value of size, optional default 1
  38426. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  38427. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  38428. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  38429. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  38430. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  38431. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38432. * * 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)
  38433. * * 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)
  38434. * @returns the VertexData of the box
  38435. */
  38436. VertexData.CreateBox = function (options) {
  38437. var normalsSource = [
  38438. new BABYLON.Vector3(0, 0, 1),
  38439. new BABYLON.Vector3(0, 0, -1),
  38440. new BABYLON.Vector3(1, 0, 0),
  38441. new BABYLON.Vector3(-1, 0, 0),
  38442. new BABYLON.Vector3(0, 1, 0),
  38443. new BABYLON.Vector3(0, -1, 0)
  38444. ];
  38445. var indices = [];
  38446. var positions = [];
  38447. var normals = [];
  38448. var uvs = [];
  38449. var width = options.width || options.size || 1;
  38450. var height = options.height || options.size || 1;
  38451. var depth = options.depth || options.size || 1;
  38452. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38453. var faceUV = options.faceUV || new Array(6);
  38454. var faceColors = options.faceColors;
  38455. var colors = [];
  38456. // default face colors and UV if undefined
  38457. for (var f = 0; f < 6; f++) {
  38458. if (faceUV[f] === undefined) {
  38459. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38460. }
  38461. if (faceColors && faceColors[f] === undefined) {
  38462. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38463. }
  38464. }
  38465. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  38466. // Create each face in turn.
  38467. for (var index = 0; index < normalsSource.length; index++) {
  38468. var normal = normalsSource[index];
  38469. // Get two vectors perpendicular to the face normal and to each other.
  38470. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  38471. var side2 = BABYLON.Vector3.Cross(normal, side1);
  38472. // Six indices (two triangles) per face.
  38473. var verticesLength = positions.length / 3;
  38474. indices.push(verticesLength);
  38475. indices.push(verticesLength + 1);
  38476. indices.push(verticesLength + 2);
  38477. indices.push(verticesLength);
  38478. indices.push(verticesLength + 2);
  38479. indices.push(verticesLength + 3);
  38480. // Four vertices per face.
  38481. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  38482. positions.push(vertex.x, vertex.y, vertex.z);
  38483. normals.push(normal.x, normal.y, normal.z);
  38484. uvs.push(faceUV[index].z, faceUV[index].w);
  38485. if (faceColors) {
  38486. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38487. }
  38488. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  38489. positions.push(vertex.x, vertex.y, vertex.z);
  38490. normals.push(normal.x, normal.y, normal.z);
  38491. uvs.push(faceUV[index].x, faceUV[index].w);
  38492. if (faceColors) {
  38493. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38494. }
  38495. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  38496. positions.push(vertex.x, vertex.y, vertex.z);
  38497. normals.push(normal.x, normal.y, normal.z);
  38498. uvs.push(faceUV[index].x, faceUV[index].y);
  38499. if (faceColors) {
  38500. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38501. }
  38502. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  38503. positions.push(vertex.x, vertex.y, vertex.z);
  38504. normals.push(normal.x, normal.y, normal.z);
  38505. uvs.push(faceUV[index].z, faceUV[index].y);
  38506. if (faceColors) {
  38507. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38508. }
  38509. }
  38510. // sides
  38511. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38512. // Result
  38513. var vertexData = new VertexData();
  38514. vertexData.indices = indices;
  38515. vertexData.positions = positions;
  38516. vertexData.normals = normals;
  38517. vertexData.uvs = uvs;
  38518. if (faceColors) {
  38519. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38520. vertexData.colors = totalColors;
  38521. }
  38522. return vertexData;
  38523. };
  38524. /**
  38525. * Creates the VertexData for an ellipsoid, defaults to a sphere
  38526. * @param options an object used to set the following optional parameters for the box, required but can be empty
  38527. * * segments sets the number of horizontal strips optional, default 32
  38528. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  38529. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  38530. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  38531. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  38532. * * 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
  38533. * * 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
  38534. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38535. * * 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)
  38536. * * 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)
  38537. * @returns the VertexData of the ellipsoid
  38538. */
  38539. VertexData.CreateSphere = function (options) {
  38540. var segments = options.segments || 32;
  38541. var diameterX = options.diameterX || options.diameter || 1;
  38542. var diameterY = options.diameterY || options.diameter || 1;
  38543. var diameterZ = options.diameterZ || options.diameter || 1;
  38544. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38545. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  38546. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38547. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  38548. var totalZRotationSteps = 2 + segments;
  38549. var totalYRotationSteps = 2 * totalZRotationSteps;
  38550. var indices = [];
  38551. var positions = [];
  38552. var normals = [];
  38553. var uvs = [];
  38554. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  38555. var normalizedZ = zRotationStep / totalZRotationSteps;
  38556. var angleZ = normalizedZ * Math.PI * slice;
  38557. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  38558. var normalizedY = yRotationStep / totalYRotationSteps;
  38559. var angleY = normalizedY * Math.PI * 2 * arc;
  38560. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  38561. var rotationY = BABYLON.Matrix.RotationY(angleY);
  38562. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  38563. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  38564. var vertex = complete.multiply(radius);
  38565. var normal = complete.divide(radius).normalize();
  38566. positions.push(vertex.x, vertex.y, vertex.z);
  38567. normals.push(normal.x, normal.y, normal.z);
  38568. uvs.push(normalizedY, normalizedZ);
  38569. }
  38570. if (zRotationStep > 0) {
  38571. var verticesCount = positions.length / 3;
  38572. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  38573. indices.push((firstIndex));
  38574. indices.push((firstIndex + 1));
  38575. indices.push(firstIndex + totalYRotationSteps + 1);
  38576. indices.push((firstIndex + totalYRotationSteps + 1));
  38577. indices.push((firstIndex + 1));
  38578. indices.push((firstIndex + totalYRotationSteps + 2));
  38579. }
  38580. }
  38581. }
  38582. // Sides
  38583. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38584. // Result
  38585. var vertexData = new VertexData();
  38586. vertexData.indices = indices;
  38587. vertexData.positions = positions;
  38588. vertexData.normals = normals;
  38589. vertexData.uvs = uvs;
  38590. return vertexData;
  38591. };
  38592. /**
  38593. * Creates the VertexData for a cylinder, cone or prism
  38594. * @param options an object used to set the following optional parameters for the box, required but can be empty
  38595. * * height sets the height (y direction) of the cylinder, optional, default 2
  38596. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  38597. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  38598. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  38599. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  38600. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  38601. * * 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
  38602. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38603. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38604. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  38605. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  38606. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38607. * * 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)
  38608. * * 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)
  38609. * @returns the VertexData of the cylinder, cone or prism
  38610. */
  38611. VertexData.CreateCylinder = function (options) {
  38612. var height = options.height || 2;
  38613. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  38614. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  38615. var tessellation = options.tessellation || 24;
  38616. var subdivisions = options.subdivisions || 1;
  38617. var hasRings = options.hasRings ? true : false;
  38618. var enclose = options.enclose ? true : false;
  38619. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38620. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38621. var faceUV = options.faceUV || new Array(3);
  38622. var faceColors = options.faceColors;
  38623. // default face colors and UV if undefined
  38624. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  38625. var ringNb = (hasRings) ? subdivisions : 1;
  38626. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  38627. var f;
  38628. for (f = 0; f < surfaceNb; f++) {
  38629. if (faceColors && faceColors[f] === undefined) {
  38630. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38631. }
  38632. }
  38633. for (f = 0; f < surfaceNb; f++) {
  38634. if (faceUV && faceUV[f] === undefined) {
  38635. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38636. }
  38637. }
  38638. var indices = new Array();
  38639. var positions = new Array();
  38640. var normals = new Array();
  38641. var uvs = new Array();
  38642. var colors = new Array();
  38643. var angle_step = Math.PI * 2 * arc / tessellation;
  38644. var angle;
  38645. var h;
  38646. var radius;
  38647. var tan = (diameterBottom - diameterTop) / 2 / height;
  38648. var ringVertex = BABYLON.Vector3.Zero();
  38649. var ringNormal = BABYLON.Vector3.Zero();
  38650. var ringFirstVertex = BABYLON.Vector3.Zero();
  38651. var ringFirstNormal = BABYLON.Vector3.Zero();
  38652. var quadNormal = BABYLON.Vector3.Zero();
  38653. var Y = BABYLON.Axis.Y;
  38654. // positions, normals, uvs
  38655. var i;
  38656. var j;
  38657. var r;
  38658. var ringIdx = 1;
  38659. var s = 1; // surface index
  38660. var cs = 0;
  38661. var v = 0;
  38662. for (i = 0; i <= subdivisions; i++) {
  38663. h = i / subdivisions;
  38664. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  38665. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  38666. for (r = 0; r < ringIdx; r++) {
  38667. if (hasRings) {
  38668. s += r;
  38669. }
  38670. if (enclose) {
  38671. s += 2 * r;
  38672. }
  38673. for (j = 0; j <= tessellation; j++) {
  38674. angle = j * angle_step;
  38675. // position
  38676. ringVertex.x = Math.cos(-angle) * radius;
  38677. ringVertex.y = -height / 2 + h * height;
  38678. ringVertex.z = Math.sin(-angle) * radius;
  38679. // normal
  38680. if (diameterTop === 0 && i === subdivisions) {
  38681. // if no top cap, reuse former normals
  38682. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  38683. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  38684. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  38685. }
  38686. else {
  38687. ringNormal.x = ringVertex.x;
  38688. ringNormal.z = ringVertex.z;
  38689. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  38690. ringNormal.normalize();
  38691. }
  38692. // keep first ring vertex values for enclose
  38693. if (j === 0) {
  38694. ringFirstVertex.copyFrom(ringVertex);
  38695. ringFirstNormal.copyFrom(ringNormal);
  38696. }
  38697. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  38698. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  38699. if (hasRings) {
  38700. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  38701. }
  38702. else {
  38703. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  38704. }
  38705. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  38706. if (faceColors) {
  38707. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  38708. }
  38709. }
  38710. // if enclose, add four vertices and their dedicated normals
  38711. if (arc !== 1 && enclose) {
  38712. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  38713. positions.push(0, ringVertex.y, 0);
  38714. positions.push(0, ringVertex.y, 0);
  38715. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  38716. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  38717. quadNormal.normalize();
  38718. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  38719. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  38720. quadNormal.normalize();
  38721. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  38722. if (hasRings) {
  38723. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  38724. }
  38725. else {
  38726. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  38727. }
  38728. uvs.push(faceUV[s + 1].x, v);
  38729. uvs.push(faceUV[s + 1].z, v);
  38730. if (hasRings) {
  38731. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  38732. }
  38733. else {
  38734. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  38735. }
  38736. uvs.push(faceUV[s + 2].x, v);
  38737. uvs.push(faceUV[s + 2].z, v);
  38738. if (faceColors) {
  38739. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  38740. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  38741. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  38742. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  38743. }
  38744. }
  38745. if (cs !== s) {
  38746. cs = s;
  38747. }
  38748. }
  38749. }
  38750. // indices
  38751. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  38752. var s;
  38753. i = 0;
  38754. for (s = 0; s < subdivisions; s++) {
  38755. var i0 = 0;
  38756. var i1 = 0;
  38757. var i2 = 0;
  38758. var i3 = 0;
  38759. for (j = 0; j < tessellation; j++) {
  38760. i0 = i * (e + 1) + j;
  38761. i1 = (i + 1) * (e + 1) + j;
  38762. i2 = i * (e + 1) + (j + 1);
  38763. i3 = (i + 1) * (e + 1) + (j + 1);
  38764. indices.push(i0, i1, i2);
  38765. indices.push(i3, i2, i1);
  38766. }
  38767. if (arc !== 1 && enclose) { // if enclose, add two quads
  38768. indices.push(i0 + 2, i1 + 2, i2 + 2);
  38769. indices.push(i3 + 2, i2 + 2, i1 + 2);
  38770. indices.push(i0 + 4, i1 + 4, i2 + 4);
  38771. indices.push(i3 + 4, i2 + 4, i1 + 4);
  38772. }
  38773. i = (hasRings) ? (i + 2) : (i + 1);
  38774. }
  38775. // Caps
  38776. var createCylinderCap = function (isTop) {
  38777. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  38778. if (radius === 0) {
  38779. return;
  38780. }
  38781. // Cap positions, normals & uvs
  38782. var angle;
  38783. var circleVector;
  38784. var i;
  38785. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  38786. var c = null;
  38787. if (faceColors) {
  38788. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  38789. }
  38790. // cap center
  38791. var vbase = positions.length / 3;
  38792. var offset = isTop ? height / 2 : -height / 2;
  38793. var center = new BABYLON.Vector3(0, offset, 0);
  38794. positions.push(center.x, center.y, center.z);
  38795. normals.push(0, isTop ? 1 : -1, 0);
  38796. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  38797. if (c) {
  38798. colors.push(c.r, c.g, c.b, c.a);
  38799. }
  38800. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  38801. for (i = 0; i <= tessellation; i++) {
  38802. angle = Math.PI * 2 * i * arc / tessellation;
  38803. var cos = Math.cos(-angle);
  38804. var sin = Math.sin(-angle);
  38805. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  38806. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  38807. positions.push(circleVector.x, circleVector.y, circleVector.z);
  38808. normals.push(0, isTop ? 1 : -1, 0);
  38809. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  38810. if (c) {
  38811. colors.push(c.r, c.g, c.b, c.a);
  38812. }
  38813. }
  38814. // Cap indices
  38815. for (i = 0; i < tessellation; i++) {
  38816. if (!isTop) {
  38817. indices.push(vbase);
  38818. indices.push(vbase + (i + 1));
  38819. indices.push(vbase + (i + 2));
  38820. }
  38821. else {
  38822. indices.push(vbase);
  38823. indices.push(vbase + (i + 2));
  38824. indices.push(vbase + (i + 1));
  38825. }
  38826. }
  38827. };
  38828. // add caps to geometry
  38829. createCylinderCap(false);
  38830. createCylinderCap(true);
  38831. // Sides
  38832. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38833. var vertexData = new VertexData();
  38834. vertexData.indices = indices;
  38835. vertexData.positions = positions;
  38836. vertexData.normals = normals;
  38837. vertexData.uvs = uvs;
  38838. if (faceColors) {
  38839. vertexData.colors = colors;
  38840. }
  38841. return vertexData;
  38842. };
  38843. /**
  38844. * Creates the VertexData for a torus
  38845. * @param options an object used to set the following optional parameters for the box, required but can be empty
  38846. * * diameter the diameter of the torus, optional default 1
  38847. * * thickness the diameter of the tube forming the torus, optional default 0.5
  38848. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  38849. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38850. * * 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)
  38851. * * 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)
  38852. * @returns the VertexData of the torus
  38853. */
  38854. VertexData.CreateTorus = function (options) {
  38855. var indices = [];
  38856. var positions = [];
  38857. var normals = [];
  38858. var uvs = [];
  38859. var diameter = options.diameter || 1;
  38860. var thickness = options.thickness || 0.5;
  38861. var tessellation = options.tessellation || 16;
  38862. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38863. var stride = tessellation + 1;
  38864. for (var i = 0; i <= tessellation; i++) {
  38865. var u = i / tessellation;
  38866. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  38867. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  38868. for (var j = 0; j <= tessellation; j++) {
  38869. var v = 1 - j / tessellation;
  38870. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  38871. var dx = Math.cos(innerAngle);
  38872. var dy = Math.sin(innerAngle);
  38873. // Create a vertex.
  38874. var normal = new BABYLON.Vector3(dx, dy, 0);
  38875. var position = normal.scale(thickness / 2);
  38876. var textureCoordinate = new BABYLON.Vector2(u, v);
  38877. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  38878. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  38879. positions.push(position.x, position.y, position.z);
  38880. normals.push(normal.x, normal.y, normal.z);
  38881. uvs.push(textureCoordinate.x, textureCoordinate.y);
  38882. // And create indices for two triangles.
  38883. var nextI = (i + 1) % stride;
  38884. var nextJ = (j + 1) % stride;
  38885. indices.push(i * stride + j);
  38886. indices.push(i * stride + nextJ);
  38887. indices.push(nextI * stride + j);
  38888. indices.push(i * stride + nextJ);
  38889. indices.push(nextI * stride + nextJ);
  38890. indices.push(nextI * stride + j);
  38891. }
  38892. }
  38893. // Sides
  38894. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38895. // Result
  38896. var vertexData = new VertexData();
  38897. vertexData.indices = indices;
  38898. vertexData.positions = positions;
  38899. vertexData.normals = normals;
  38900. vertexData.uvs = uvs;
  38901. return vertexData;
  38902. };
  38903. /**
  38904. * Creates the VertexData of the LineSystem
  38905. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  38906. * - lines an array of lines, each line being an array of successive Vector3
  38907. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  38908. * @returns the VertexData of the LineSystem
  38909. */
  38910. VertexData.CreateLineSystem = function (options) {
  38911. var indices = [];
  38912. var positions = [];
  38913. var lines = options.lines;
  38914. var colors = options.colors;
  38915. var vertexColors = [];
  38916. var idx = 0;
  38917. for (var l = 0; l < lines.length; l++) {
  38918. var points = lines[l];
  38919. for (var index = 0; index < points.length; index++) {
  38920. positions.push(points[index].x, points[index].y, points[index].z);
  38921. if (colors) {
  38922. var color = colors[l];
  38923. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  38924. }
  38925. if (index > 0) {
  38926. indices.push(idx - 1);
  38927. indices.push(idx);
  38928. }
  38929. idx++;
  38930. }
  38931. }
  38932. var vertexData = new VertexData();
  38933. vertexData.indices = indices;
  38934. vertexData.positions = positions;
  38935. if (colors) {
  38936. vertexData.colors = vertexColors;
  38937. }
  38938. return vertexData;
  38939. };
  38940. /**
  38941. * Create the VertexData for a DashedLines
  38942. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  38943. * - points an array successive Vector3
  38944. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  38945. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  38946. * - dashNb the intended total number of dashes, optional, default 200
  38947. * @returns the VertexData for the DashedLines
  38948. */
  38949. VertexData.CreateDashedLines = function (options) {
  38950. var dashSize = options.dashSize || 3;
  38951. var gapSize = options.gapSize || 1;
  38952. var dashNb = options.dashNb || 200;
  38953. var points = options.points;
  38954. var positions = new Array();
  38955. var indices = new Array();
  38956. var curvect = BABYLON.Vector3.Zero();
  38957. var lg = 0;
  38958. var nb = 0;
  38959. var shft = 0;
  38960. var dashshft = 0;
  38961. var curshft = 0;
  38962. var idx = 0;
  38963. var i = 0;
  38964. for (i = 0; i < points.length - 1; i++) {
  38965. points[i + 1].subtractToRef(points[i], curvect);
  38966. lg += curvect.length();
  38967. }
  38968. shft = lg / dashNb;
  38969. dashshft = dashSize * shft / (dashSize + gapSize);
  38970. for (i = 0; i < points.length - 1; i++) {
  38971. points[i + 1].subtractToRef(points[i], curvect);
  38972. nb = Math.floor(curvect.length() / shft);
  38973. curvect.normalize();
  38974. for (var j = 0; j < nb; j++) {
  38975. curshft = shft * j;
  38976. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  38977. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  38978. indices.push(idx, idx + 1);
  38979. idx += 2;
  38980. }
  38981. }
  38982. // Result
  38983. var vertexData = new VertexData();
  38984. vertexData.positions = positions;
  38985. vertexData.indices = indices;
  38986. return vertexData;
  38987. };
  38988. /**
  38989. * Creates the VertexData for a Ground
  38990. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  38991. * - width the width (x direction) of the ground, optional, default 1
  38992. * - height the height (z direction) of the ground, optional, default 1
  38993. * - subdivisions the number of subdivisions per side, optional, default 1
  38994. * @returns the VertexData of the Ground
  38995. */
  38996. VertexData.CreateGround = function (options) {
  38997. var indices = [];
  38998. var positions = [];
  38999. var normals = [];
  39000. var uvs = [];
  39001. var row, col;
  39002. var width = options.width || 1;
  39003. var height = options.height || 1;
  39004. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  39005. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  39006. for (row = 0; row <= subdivisionsY; row++) {
  39007. for (col = 0; col <= subdivisionsX; col++) {
  39008. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  39009. var normal = new BABYLON.Vector3(0, 1.0, 0);
  39010. positions.push(position.x, position.y, position.z);
  39011. normals.push(normal.x, normal.y, normal.z);
  39012. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  39013. }
  39014. }
  39015. for (row = 0; row < subdivisionsY; row++) {
  39016. for (col = 0; col < subdivisionsX; col++) {
  39017. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  39018. indices.push(col + 1 + row * (subdivisionsX + 1));
  39019. indices.push(col + row * (subdivisionsX + 1));
  39020. indices.push(col + (row + 1) * (subdivisionsX + 1));
  39021. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  39022. indices.push(col + row * (subdivisionsX + 1));
  39023. }
  39024. }
  39025. // Result
  39026. var vertexData = new VertexData();
  39027. vertexData.indices = indices;
  39028. vertexData.positions = positions;
  39029. vertexData.normals = normals;
  39030. vertexData.uvs = uvs;
  39031. return vertexData;
  39032. };
  39033. /**
  39034. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  39035. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  39036. * * xmin the ground minimum X coordinate, optional, default -1
  39037. * * zmin the ground minimum Z coordinate, optional, default -1
  39038. * * xmax the ground maximum X coordinate, optional, default 1
  39039. * * zmax the ground maximum Z coordinate, optional, default 1
  39040. * * 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}
  39041. * * 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}
  39042. * @returns the VertexData of the TiledGround
  39043. */
  39044. VertexData.CreateTiledGround = function (options) {
  39045. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  39046. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  39047. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  39048. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  39049. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  39050. var precision = options.precision || { w: 1, h: 1 };
  39051. var indices = new Array();
  39052. var positions = new Array();
  39053. var normals = new Array();
  39054. var uvs = new Array();
  39055. var row, col, tileRow, tileCol;
  39056. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  39057. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  39058. precision.w = (precision.w < 1) ? 1 : precision.w;
  39059. precision.h = (precision.h < 1) ? 1 : precision.h;
  39060. var tileSize = {
  39061. 'w': (xmax - xmin) / subdivisions.w,
  39062. 'h': (zmax - zmin) / subdivisions.h
  39063. };
  39064. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  39065. // Indices
  39066. var base = positions.length / 3;
  39067. var rowLength = precision.w + 1;
  39068. for (row = 0; row < precision.h; row++) {
  39069. for (col = 0; col < precision.w; col++) {
  39070. var square = [
  39071. base + col + row * rowLength,
  39072. base + (col + 1) + row * rowLength,
  39073. base + (col + 1) + (row + 1) * rowLength,
  39074. base + col + (row + 1) * rowLength
  39075. ];
  39076. indices.push(square[1]);
  39077. indices.push(square[2]);
  39078. indices.push(square[3]);
  39079. indices.push(square[0]);
  39080. indices.push(square[1]);
  39081. indices.push(square[3]);
  39082. }
  39083. }
  39084. // Position, normals and uvs
  39085. var position = BABYLON.Vector3.Zero();
  39086. var normal = new BABYLON.Vector3(0, 1.0, 0);
  39087. for (row = 0; row <= precision.h; row++) {
  39088. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  39089. for (col = 0; col <= precision.w; col++) {
  39090. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  39091. position.y = 0;
  39092. positions.push(position.x, position.y, position.z);
  39093. normals.push(normal.x, normal.y, normal.z);
  39094. uvs.push(col / precision.w, row / precision.h);
  39095. }
  39096. }
  39097. }
  39098. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  39099. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  39100. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  39101. }
  39102. }
  39103. // Result
  39104. var vertexData = new VertexData();
  39105. vertexData.indices = indices;
  39106. vertexData.positions = positions;
  39107. vertexData.normals = normals;
  39108. vertexData.uvs = uvs;
  39109. return vertexData;
  39110. };
  39111. /**
  39112. * Creates the VertexData of the Ground designed from a heightmap
  39113. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  39114. * * width the width (x direction) of the ground
  39115. * * height the height (z direction) of the ground
  39116. * * subdivisions the number of subdivisions per side
  39117. * * minHeight the minimum altitude on the ground, optional, default 0
  39118. * * maxHeight the maximum altitude on the ground, optional default 1
  39119. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  39120. * * buffer the array holding the image color data
  39121. * * bufferWidth the width of image
  39122. * * bufferHeight the height of image
  39123. * * alphaFilter Remove any data where the alpha channel is below this value, defaults 0 (all data visible)
  39124. * @returns the VertexData of the Ground designed from a heightmap
  39125. */
  39126. VertexData.CreateGroundFromHeightMap = function (options) {
  39127. var indices = [];
  39128. var positions = [];
  39129. var normals = [];
  39130. var uvs = [];
  39131. var row, col;
  39132. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  39133. var alphaFilter = options.alphaFilter || 0.0;
  39134. // Vertices
  39135. for (row = 0; row <= options.subdivisions; row++) {
  39136. for (col = 0; col <= options.subdivisions; col++) {
  39137. 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));
  39138. // Compute height
  39139. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  39140. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  39141. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  39142. var r = options.buffer[pos] / 255.0;
  39143. var g = options.buffer[pos + 1] / 255.0;
  39144. var b = options.buffer[pos + 2] / 255.0;
  39145. var a = options.buffer[pos + 3] / 255.0;
  39146. var gradient = r * filter.r + g * filter.g + b * filter.b;
  39147. // If our alpha channel is not within our filter then we will assign a 'special' height
  39148. // Then when building the indices, we will ignore any vertex that is using the special height
  39149. if (a >= alphaFilter) {
  39150. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  39151. }
  39152. else {
  39153. position.y = options.minHeight - BABYLON.Epsilon; // We can't have a height below minHeight, normally.
  39154. }
  39155. // Add vertex
  39156. positions.push(position.x, position.y, position.z);
  39157. normals.push(0, 0, 0);
  39158. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  39159. }
  39160. }
  39161. // Indices
  39162. for (row = 0; row < options.subdivisions; row++) {
  39163. for (col = 0; col < options.subdivisions; col++) {
  39164. // Calculate Indices
  39165. var idx1 = (col + 1 + (row + 1) * (options.subdivisions + 1));
  39166. var idx2 = (col + 1 + row * (options.subdivisions + 1));
  39167. var idx3 = (col + row * (options.subdivisions + 1));
  39168. var idx4 = (col + (row + 1) * (options.subdivisions + 1));
  39169. // Check that all indices are visible (based on our special height)
  39170. // Only display the vertex if all Indices are visible
  39171. // Positions are stored x,y,z for each vertex, hence the * 3 and + 1 for height
  39172. var isVisibleIdx1 = positions[idx1 * 3 + 1] >= options.minHeight;
  39173. var isVisibleIdx2 = positions[idx2 * 3 + 1] >= options.minHeight;
  39174. var isVisibleIdx3 = positions[idx3 * 3 + 1] >= options.minHeight;
  39175. if (isVisibleIdx1 && isVisibleIdx2 && isVisibleIdx3) {
  39176. indices.push(idx1);
  39177. indices.push(idx2);
  39178. indices.push(idx3);
  39179. }
  39180. var isVisibleIdx4 = positions[idx4 * 3 + 1] >= options.minHeight;
  39181. if (isVisibleIdx4 && isVisibleIdx1 && isVisibleIdx3) {
  39182. indices.push(idx4);
  39183. indices.push(idx1);
  39184. indices.push(idx3);
  39185. }
  39186. }
  39187. }
  39188. // Normals
  39189. VertexData.ComputeNormals(positions, indices, normals);
  39190. // Result
  39191. var vertexData = new VertexData();
  39192. vertexData.indices = indices;
  39193. vertexData.positions = positions;
  39194. vertexData.normals = normals;
  39195. vertexData.uvs = uvs;
  39196. return vertexData;
  39197. };
  39198. /**
  39199. * Creates the VertexData for a Plane
  39200. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  39201. * * size sets the width and height of the plane to the value of size, optional default 1
  39202. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  39203. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  39204. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39205. * * 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)
  39206. * * 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)
  39207. * @returns the VertexData of the box
  39208. */
  39209. VertexData.CreatePlane = function (options) {
  39210. var indices = [];
  39211. var positions = [];
  39212. var normals = [];
  39213. var uvs = [];
  39214. var width = options.width || options.size || 1;
  39215. var height = options.height || options.size || 1;
  39216. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39217. // Vertices
  39218. var halfWidth = width / 2.0;
  39219. var halfHeight = height / 2.0;
  39220. positions.push(-halfWidth, -halfHeight, 0);
  39221. normals.push(0, 0, -1.0);
  39222. uvs.push(0.0, 0.0);
  39223. positions.push(halfWidth, -halfHeight, 0);
  39224. normals.push(0, 0, -1.0);
  39225. uvs.push(1.0, 0.0);
  39226. positions.push(halfWidth, halfHeight, 0);
  39227. normals.push(0, 0, -1.0);
  39228. uvs.push(1.0, 1.0);
  39229. positions.push(-halfWidth, halfHeight, 0);
  39230. normals.push(0, 0, -1.0);
  39231. uvs.push(0.0, 1.0);
  39232. // Indices
  39233. indices.push(0);
  39234. indices.push(1);
  39235. indices.push(2);
  39236. indices.push(0);
  39237. indices.push(2);
  39238. indices.push(3);
  39239. // Sides
  39240. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39241. // Result
  39242. var vertexData = new VertexData();
  39243. vertexData.indices = indices;
  39244. vertexData.positions = positions;
  39245. vertexData.normals = normals;
  39246. vertexData.uvs = uvs;
  39247. return vertexData;
  39248. };
  39249. /**
  39250. * Creates the VertexData of the Disc or regular Polygon
  39251. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  39252. * * radius the radius of the disc, optional default 0.5
  39253. * * tessellation the number of polygon sides, optional, default 64
  39254. * * 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
  39255. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39256. * * 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)
  39257. * * 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)
  39258. * @returns the VertexData of the box
  39259. */
  39260. VertexData.CreateDisc = function (options) {
  39261. var positions = new Array();
  39262. var indices = new Array();
  39263. var normals = new Array();
  39264. var uvs = new Array();
  39265. var radius = options.radius || 0.5;
  39266. var tessellation = options.tessellation || 64;
  39267. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  39268. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39269. // positions and uvs
  39270. positions.push(0, 0, 0); // disc center first
  39271. uvs.push(0.5, 0.5);
  39272. var theta = Math.PI * 2 * arc;
  39273. var step = theta / tessellation;
  39274. for (var a = 0; a < theta; a += step) {
  39275. var x = Math.cos(a);
  39276. var y = Math.sin(a);
  39277. var u = (x + 1) / 2;
  39278. var v = (1 - y) / 2;
  39279. positions.push(radius * x, radius * y, 0);
  39280. uvs.push(u, v);
  39281. }
  39282. if (arc === 1) {
  39283. positions.push(positions[3], positions[4], positions[5]); // close the circle
  39284. uvs.push(uvs[2], uvs[3]);
  39285. }
  39286. //indices
  39287. var vertexNb = positions.length / 3;
  39288. for (var i = 1; i < vertexNb - 1; i++) {
  39289. indices.push(i + 1, 0, i);
  39290. }
  39291. // result
  39292. VertexData.ComputeNormals(positions, indices, normals);
  39293. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39294. var vertexData = new VertexData();
  39295. vertexData.indices = indices;
  39296. vertexData.positions = positions;
  39297. vertexData.normals = normals;
  39298. vertexData.uvs = uvs;
  39299. return vertexData;
  39300. };
  39301. /**
  39302. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  39303. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  39304. * @param polygon a mesh built from polygonTriangulation.build()
  39305. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39306. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  39307. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  39308. * @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)
  39309. * @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)
  39310. * @returns the VertexData of the Polygon
  39311. */
  39312. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  39313. var faceUV = fUV || new Array(3);
  39314. var faceColors = fColors;
  39315. var colors = [];
  39316. // default face colors and UV if undefined
  39317. for (var f = 0; f < 3; f++) {
  39318. if (faceUV[f] === undefined) {
  39319. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  39320. }
  39321. if (faceColors && faceColors[f] === undefined) {
  39322. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  39323. }
  39324. }
  39325. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39326. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  39327. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  39328. var indices = polygon.getIndices();
  39329. // set face colours and textures
  39330. var idx = 0;
  39331. var face = 0;
  39332. for (var index = 0; index < normals.length; index += 3) {
  39333. //Edge Face no. 1
  39334. if (Math.abs(normals[index + 1]) < 0.001) {
  39335. face = 1;
  39336. }
  39337. //Top Face no. 0
  39338. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  39339. face = 0;
  39340. }
  39341. //Bottom Face no. 2
  39342. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  39343. face = 2;
  39344. }
  39345. idx = index / 3;
  39346. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  39347. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  39348. if (faceColors) {
  39349. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  39350. }
  39351. }
  39352. // sides
  39353. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  39354. // Result
  39355. var vertexData = new VertexData();
  39356. vertexData.indices = indices;
  39357. vertexData.positions = positions;
  39358. vertexData.normals = normals;
  39359. vertexData.uvs = uvs;
  39360. if (faceColors) {
  39361. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  39362. vertexData.colors = totalColors;
  39363. }
  39364. return vertexData;
  39365. };
  39366. /**
  39367. * Creates the VertexData of the IcoSphere
  39368. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  39369. * * radius the radius of the IcoSphere, optional default 1
  39370. * * radiusX allows stretching in the x direction, optional, default radius
  39371. * * radiusY allows stretching in the y direction, optional, default radius
  39372. * * radiusZ allows stretching in the z direction, optional, default radius
  39373. * * flat when true creates a flat shaded mesh, optional, default true
  39374. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  39375. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39376. * * 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)
  39377. * * 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)
  39378. * @returns the VertexData of the IcoSphere
  39379. */
  39380. VertexData.CreateIcoSphere = function (options) {
  39381. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39382. var radius = options.radius || 1;
  39383. var flat = (options.flat === undefined) ? true : options.flat;
  39384. var subdivisions = options.subdivisions || 4;
  39385. var radiusX = options.radiusX || radius;
  39386. var radiusY = options.radiusY || radius;
  39387. var radiusZ = options.radiusZ || radius;
  39388. var t = (1 + Math.sqrt(5)) / 2;
  39389. // 12 vertex x,y,z
  39390. var ico_vertices = [
  39391. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  39392. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  39393. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  39394. ];
  39395. // index of 3 vertex makes a face of icopshere
  39396. var ico_indices = [
  39397. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  39398. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  39399. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  39400. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  39401. ];
  39402. // vertex for uv have aliased position, not for UV
  39403. var vertices_unalias_id = [
  39404. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  39405. // vertex alias
  39406. 0,
  39407. 2,
  39408. 3,
  39409. 3,
  39410. 3,
  39411. 4,
  39412. 7,
  39413. 8,
  39414. 9,
  39415. 9,
  39416. 10,
  39417. 11 // 23: B + 12
  39418. ];
  39419. // uv as integer step (not pixels !)
  39420. var ico_vertexuv = [
  39421. 5, 1, 3, 1, 6, 4, 0, 0,
  39422. 5, 3, 4, 2, 2, 2, 4, 0,
  39423. 2, 0, 1, 1, 6, 0, 6, 2,
  39424. // vertex alias (for same vertex on different faces)
  39425. 0, 4,
  39426. 3, 3,
  39427. 4, 4,
  39428. 3, 1,
  39429. 4, 2,
  39430. 4, 4,
  39431. 0, 2,
  39432. 1, 1,
  39433. 2, 2,
  39434. 3, 3,
  39435. 1, 3,
  39436. 2, 4 // 23: B + 12
  39437. ];
  39438. // Vertices[0, 1, ...9, A, B] : position on UV plane
  39439. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  39440. // First island of uv mapping
  39441. // v = 4h 3+ 2
  39442. // v = 3h 9+ 4
  39443. // v = 2h 9+ 5 B
  39444. // v = 1h 9 1 0
  39445. // v = 0h 3 8 7 A
  39446. // u = 0 1 2 3 4 5 6 *a
  39447. // Second island of uv mapping
  39448. // v = 4h 0+ B+ 4+
  39449. // v = 3h A+ 2+
  39450. // v = 2h 7+ 6 3+
  39451. // v = 1h 8+ 3+
  39452. // v = 0h
  39453. // u = 0 1 2 3 4 5 6 *a
  39454. // Face layout on texture UV mapping
  39455. // ============
  39456. // \ 4 /\ 16 / ======
  39457. // \ / \ / /\ 11 /
  39458. // \/ 7 \/ / \ /
  39459. // ======= / 10 \/
  39460. // /\ 17 /\ =======
  39461. // / \ / \ \ 15 /\
  39462. // / 8 \/ 12 \ \ / \
  39463. // ============ \/ 6 \
  39464. // \ 18 /\ ============
  39465. // \ / \ \ 5 /\ 0 /
  39466. // \/ 13 \ \ / \ /
  39467. // ======= \/ 1 \/
  39468. // =============
  39469. // /\ 19 /\ 2 /\
  39470. // / \ / \ / \
  39471. // / 14 \/ 9 \/ 3 \
  39472. // ===================
  39473. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  39474. var ustep = 138 / 1024;
  39475. var vstep = 239 / 1024;
  39476. var uoffset = 60 / 1024;
  39477. var voffset = 26 / 1024;
  39478. // Second island should have margin, not to touch the first island
  39479. // avoid any borderline artefact in pixel rounding
  39480. var island_u_offset = -40 / 1024;
  39481. var island_v_offset = +20 / 1024;
  39482. // face is either island 0 or 1 :
  39483. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  39484. var island = [
  39485. 0, 0, 0, 0, 1,
  39486. 0, 0, 1, 1, 0,
  39487. 0, 0, 1, 1, 0,
  39488. 0, 1, 1, 1, 0 // 15 - 19
  39489. ];
  39490. var indices = new Array();
  39491. var positions = new Array();
  39492. var normals = new Array();
  39493. var uvs = new Array();
  39494. var current_indice = 0;
  39495. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  39496. var face_vertex_pos = new Array(3);
  39497. var face_vertex_uv = new Array(3);
  39498. var v012;
  39499. for (v012 = 0; v012 < 3; v012++) {
  39500. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  39501. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  39502. }
  39503. // create all with normals
  39504. for (var face = 0; face < 20; face++) {
  39505. // 3 vertex per face
  39506. for (v012 = 0; v012 < 3; v012++) {
  39507. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  39508. var v_id = ico_indices[3 * face + v012];
  39509. // vertex have 3D position (x,y,z)
  39510. 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]);
  39511. // Normalize to get normal, then scale to radius
  39512. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  39513. // uv Coordinates from vertex ID
  39514. 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);
  39515. }
  39516. // Subdivide the face (interpolate pos, norm, uv)
  39517. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  39518. // - norm is linear interpolation of vertex corner normal
  39519. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  39520. // - uv is linear interpolation
  39521. //
  39522. // Topology is as below for sub-divide by 2
  39523. // vertex shown as v0,v1,v2
  39524. // interp index is i1 to progress in range [v0,v1[
  39525. // interp index is i2 to progress in range [v0,v2[
  39526. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  39527. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  39528. //
  39529. //
  39530. // i2 v2
  39531. // ^ ^
  39532. // / / \
  39533. // / / \
  39534. // / / \
  39535. // / / (0,1) \
  39536. // / #---------\
  39537. // / / \ (0,0)'/ \
  39538. // / / \ / \
  39539. // / / \ / \
  39540. // / / (0,0) \ / (1,0) \
  39541. // / #---------#---------\
  39542. // v0 v1
  39543. //
  39544. // --------------------> i1
  39545. //
  39546. // interp of (i1,i2):
  39547. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  39548. // along i1 : lerp(x0,x1, i1/(S-i2))
  39549. //
  39550. // centroid of triangle is needed to get help normal computation
  39551. // (c1,c2) are used for centroid location
  39552. var interp_vertex = function (i1, i2, c1, c2) {
  39553. // vertex is interpolated from
  39554. // - face_vertex_pos[0..2]
  39555. // - face_vertex_uv[0..2]
  39556. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  39557. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  39558. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  39559. pos_interp.normalize();
  39560. var vertex_normal;
  39561. if (flat) {
  39562. // in flat mode, recalculate normal as face centroid normal
  39563. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  39564. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  39565. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  39566. }
  39567. else {
  39568. // in smooth mode, recalculate normal from each single vertex position
  39569. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  39570. }
  39571. // Vertex normal need correction due to X,Y,Z radius scaling
  39572. vertex_normal.x /= radiusX;
  39573. vertex_normal.y /= radiusY;
  39574. vertex_normal.z /= radiusZ;
  39575. vertex_normal.normalize();
  39576. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  39577. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  39578. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  39579. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  39580. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  39581. uvs.push(uv_interp.x, uv_interp.y);
  39582. // push each vertex has member of a face
  39583. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  39584. indices.push(current_indice);
  39585. current_indice++;
  39586. };
  39587. for (var i2 = 0; i2 < subdivisions; i2++) {
  39588. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  39589. // face : (i1,i2) for /\ :
  39590. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  39591. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  39592. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  39593. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  39594. if (i1 + i2 + 1 < subdivisions) {
  39595. // face : (i1,i2)' for \/ :
  39596. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  39597. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  39598. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  39599. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  39600. }
  39601. }
  39602. }
  39603. }
  39604. // Sides
  39605. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39606. // Result
  39607. var vertexData = new VertexData();
  39608. vertexData.indices = indices;
  39609. vertexData.positions = positions;
  39610. vertexData.normals = normals;
  39611. vertexData.uvs = uvs;
  39612. return vertexData;
  39613. };
  39614. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  39615. /**
  39616. * Creates the VertexData for a Polyhedron
  39617. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  39618. * * type provided types are:
  39619. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  39620. * * 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)
  39621. * * size the size of the IcoSphere, optional default 1
  39622. * * sizeX allows stretching in the x direction, optional, default size
  39623. * * sizeY allows stretching in the y direction, optional, default size
  39624. * * sizeZ allows stretching in the z direction, optional, default size
  39625. * * 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
  39626. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  39627. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  39628. * * flat when true creates a flat shaded mesh, optional, default true
  39629. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  39630. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39631. * * 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)
  39632. * * 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)
  39633. * @returns the VertexData of the Polyhedron
  39634. */
  39635. VertexData.CreatePolyhedron = function (options) {
  39636. // provided polyhedron types :
  39637. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  39638. // 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)
  39639. var polyhedra = [];
  39640. 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]] };
  39641. 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]] };
  39642. polyhedra[2] = {
  39643. 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]],
  39644. 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]]
  39645. };
  39646. polyhedra[3] = {
  39647. 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]],
  39648. 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]]
  39649. };
  39650. polyhedra[4] = {
  39651. 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]],
  39652. 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]]
  39653. };
  39654. 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]] };
  39655. 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]] };
  39656. 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]] };
  39657. 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]] };
  39658. 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]] };
  39659. 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]] };
  39660. 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]] };
  39661. 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]] };
  39662. 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]] };
  39663. polyhedra[14] = {
  39664. 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]],
  39665. 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]]
  39666. };
  39667. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  39668. var size = options.size;
  39669. var sizeX = options.sizeX || size || 1;
  39670. var sizeY = options.sizeY || size || 1;
  39671. var sizeZ = options.sizeZ || size || 1;
  39672. var data = options.custom || polyhedra[type];
  39673. var nbfaces = data.face.length;
  39674. var faceUV = options.faceUV || new Array(nbfaces);
  39675. var faceColors = options.faceColors;
  39676. var flat = (options.flat === undefined) ? true : options.flat;
  39677. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39678. var positions = new Array();
  39679. var indices = new Array();
  39680. var normals = new Array();
  39681. var uvs = new Array();
  39682. var colors = new Array();
  39683. var index = 0;
  39684. var faceIdx = 0; // face cursor in the array "indexes"
  39685. var indexes = new Array();
  39686. var i = 0;
  39687. var f = 0;
  39688. var u, v, ang, x, y, tmp;
  39689. // default face colors and UV if undefined
  39690. if (flat) {
  39691. for (f = 0; f < nbfaces; f++) {
  39692. if (faceColors && faceColors[f] === undefined) {
  39693. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  39694. }
  39695. if (faceUV && faceUV[f] === undefined) {
  39696. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  39697. }
  39698. }
  39699. }
  39700. if (!flat) {
  39701. for (i = 0; i < data.vertex.length; i++) {
  39702. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  39703. uvs.push(0, 0);
  39704. }
  39705. for (f = 0; f < nbfaces; f++) {
  39706. for (i = 0; i < data.face[f].length - 2; i++) {
  39707. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  39708. }
  39709. }
  39710. }
  39711. else {
  39712. for (f = 0; f < nbfaces; f++) {
  39713. var fl = data.face[f].length; // number of vertices of the current face
  39714. ang = 2 * Math.PI / fl;
  39715. x = 0.5 * Math.tan(ang / 2);
  39716. y = 0.5;
  39717. // positions, uvs, colors
  39718. for (i = 0; i < fl; i++) {
  39719. // positions
  39720. 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);
  39721. indexes.push(index);
  39722. index++;
  39723. // uvs
  39724. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  39725. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  39726. uvs.push(u, v);
  39727. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  39728. y = x * Math.sin(ang) + y * Math.cos(ang);
  39729. x = tmp;
  39730. // colors
  39731. if (faceColors) {
  39732. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  39733. }
  39734. }
  39735. // indices from indexes
  39736. for (i = 0; i < fl - 2; i++) {
  39737. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  39738. }
  39739. faceIdx += fl;
  39740. }
  39741. }
  39742. VertexData.ComputeNormals(positions, indices, normals);
  39743. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39744. var vertexData = new VertexData();
  39745. vertexData.positions = positions;
  39746. vertexData.indices = indices;
  39747. vertexData.normals = normals;
  39748. vertexData.uvs = uvs;
  39749. if (faceColors && flat) {
  39750. vertexData.colors = colors;
  39751. }
  39752. return vertexData;
  39753. };
  39754. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  39755. /**
  39756. * Creates the VertexData for a TorusKnot
  39757. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  39758. * * radius the radius of the torus knot, optional, default 2
  39759. * * tube the thickness of the tube, optional, default 0.5
  39760. * * radialSegments the number of sides on each tube segments, optional, default 32
  39761. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  39762. * * p the number of windings around the z axis, optional, default 2
  39763. * * q the number of windings around the x axis, optional, default 3
  39764. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39765. * * 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)
  39766. * * 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)
  39767. * @returns the VertexData of the Torus Knot
  39768. */
  39769. VertexData.CreateTorusKnot = function (options) {
  39770. var indices = new Array();
  39771. var positions = new Array();
  39772. var normals = new Array();
  39773. var uvs = new Array();
  39774. var radius = options.radius || 2;
  39775. var tube = options.tube || 0.5;
  39776. var radialSegments = options.radialSegments || 32;
  39777. var tubularSegments = options.tubularSegments || 32;
  39778. var p = options.p || 2;
  39779. var q = options.q || 3;
  39780. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39781. // Helper
  39782. var getPos = function (angle) {
  39783. var cu = Math.cos(angle);
  39784. var su = Math.sin(angle);
  39785. var quOverP = q / p * angle;
  39786. var cs = Math.cos(quOverP);
  39787. var tx = radius * (2 + cs) * 0.5 * cu;
  39788. var ty = radius * (2 + cs) * su * 0.5;
  39789. var tz = radius * Math.sin(quOverP) * 0.5;
  39790. return new BABYLON.Vector3(tx, ty, tz);
  39791. };
  39792. // Vertices
  39793. var i;
  39794. var j;
  39795. for (i = 0; i <= radialSegments; i++) {
  39796. var modI = i % radialSegments;
  39797. var u = modI / radialSegments * 2 * p * Math.PI;
  39798. var p1 = getPos(u);
  39799. var p2 = getPos(u + 0.01);
  39800. var tang = p2.subtract(p1);
  39801. var n = p2.add(p1);
  39802. var bitan = BABYLON.Vector3.Cross(tang, n);
  39803. n = BABYLON.Vector3.Cross(bitan, tang);
  39804. bitan.normalize();
  39805. n.normalize();
  39806. for (j = 0; j < tubularSegments; j++) {
  39807. var modJ = j % tubularSegments;
  39808. var v = modJ / tubularSegments * 2 * Math.PI;
  39809. var cx = -tube * Math.cos(v);
  39810. var cy = tube * Math.sin(v);
  39811. positions.push(p1.x + cx * n.x + cy * bitan.x);
  39812. positions.push(p1.y + cx * n.y + cy * bitan.y);
  39813. positions.push(p1.z + cx * n.z + cy * bitan.z);
  39814. uvs.push(i / radialSegments);
  39815. uvs.push(j / tubularSegments);
  39816. }
  39817. }
  39818. for (i = 0; i < radialSegments; i++) {
  39819. for (j = 0; j < tubularSegments; j++) {
  39820. var jNext = (j + 1) % tubularSegments;
  39821. var a = i * tubularSegments + j;
  39822. var b = (i + 1) * tubularSegments + j;
  39823. var c = (i + 1) * tubularSegments + jNext;
  39824. var d = i * tubularSegments + jNext;
  39825. indices.push(d);
  39826. indices.push(b);
  39827. indices.push(a);
  39828. indices.push(d);
  39829. indices.push(c);
  39830. indices.push(b);
  39831. }
  39832. }
  39833. // Normals
  39834. VertexData.ComputeNormals(positions, indices, normals);
  39835. // Sides
  39836. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39837. // Result
  39838. var vertexData = new VertexData();
  39839. vertexData.indices = indices;
  39840. vertexData.positions = positions;
  39841. vertexData.normals = normals;
  39842. vertexData.uvs = uvs;
  39843. return vertexData;
  39844. };
  39845. // Tools
  39846. /**
  39847. * Compute normals for given positions and indices
  39848. * @param positions an array of vertex positions, [...., x, y, z, ......]
  39849. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  39850. * @param normals an array of vertex normals, [...., x, y, z, ......]
  39851. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  39852. * * facetNormals : optional array of facet normals (vector3)
  39853. * * facetPositions : optional array of facet positions (vector3)
  39854. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  39855. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  39856. * * bInfo : optional bounding info, required for facetPartitioning computation
  39857. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  39858. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  39859. * * useRightHandedSystem: optional boolean to for right handed system computation
  39860. * * depthSort : optional boolean to enable the facet depth sort computation
  39861. * * distanceTo : optional Vector3 to compute the facet depth from this location
  39862. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  39863. */
  39864. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  39865. // temporary scalar variables
  39866. var index = 0; // facet index
  39867. var p1p2x = 0.0; // p1p2 vector x coordinate
  39868. var p1p2y = 0.0; // p1p2 vector y coordinate
  39869. var p1p2z = 0.0; // p1p2 vector z coordinate
  39870. var p3p2x = 0.0; // p3p2 vector x coordinate
  39871. var p3p2y = 0.0; // p3p2 vector y coordinate
  39872. var p3p2z = 0.0; // p3p2 vector z coordinate
  39873. var faceNormalx = 0.0; // facet normal x coordinate
  39874. var faceNormaly = 0.0; // facet normal y coordinate
  39875. var faceNormalz = 0.0; // facet normal z coordinate
  39876. var length = 0.0; // facet normal length before normalization
  39877. var v1x = 0; // vector1 x index in the positions array
  39878. var v1y = 0; // vector1 y index in the positions array
  39879. var v1z = 0; // vector1 z index in the positions array
  39880. var v2x = 0; // vector2 x index in the positions array
  39881. var v2y = 0; // vector2 y index in the positions array
  39882. var v2z = 0; // vector2 z index in the positions array
  39883. var v3x = 0; // vector3 x index in the positions array
  39884. var v3y = 0; // vector3 y index in the positions array
  39885. var v3z = 0; // vector3 z index in the positions array
  39886. var computeFacetNormals = false;
  39887. var computeFacetPositions = false;
  39888. var computeFacetPartitioning = false;
  39889. var computeDepthSort = false;
  39890. var faceNormalSign = 1;
  39891. var ratio = 0;
  39892. var distanceTo = null;
  39893. if (options) {
  39894. computeFacetNormals = (options.facetNormals) ? true : false;
  39895. computeFacetPositions = (options.facetPositions) ? true : false;
  39896. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  39897. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  39898. ratio = options.ratio || 0;
  39899. computeDepthSort = (options.depthSort) ? true : false;
  39900. distanceTo = (options.distanceTo);
  39901. if (computeDepthSort) {
  39902. if (distanceTo === undefined) {
  39903. distanceTo = BABYLON.Vector3.Zero();
  39904. }
  39905. var depthSortedFacets = options.depthSortedFacets;
  39906. }
  39907. }
  39908. // facetPartitioning reinit if needed
  39909. var xSubRatio = 0;
  39910. var ySubRatio = 0;
  39911. var zSubRatio = 0;
  39912. var subSq = 0;
  39913. if (computeFacetPartitioning && options && options.bbSize) {
  39914. var ox = 0; // X partitioning index for facet position
  39915. var oy = 0; // Y partinioning index for facet position
  39916. var oz = 0; // Z partinioning index for facet position
  39917. var b1x = 0; // X partitioning index for facet v1 vertex
  39918. var b1y = 0; // Y partitioning index for facet v1 vertex
  39919. var b1z = 0; // z partitioning index for facet v1 vertex
  39920. var b2x = 0; // X partitioning index for facet v2 vertex
  39921. var b2y = 0; // Y partitioning index for facet v2 vertex
  39922. var b2z = 0; // Z partitioning index for facet v2 vertex
  39923. var b3x = 0; // X partitioning index for facet v3 vertex
  39924. var b3y = 0; // Y partitioning index for facet v3 vertex
  39925. var b3z = 0; // Z partitioning index for facet v3 vertex
  39926. var block_idx_o = 0; // facet barycenter block index
  39927. var block_idx_v1 = 0; // v1 vertex block index
  39928. var block_idx_v2 = 0; // v2 vertex block index
  39929. var block_idx_v3 = 0; // v3 vertex block index
  39930. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  39931. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  39932. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  39933. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  39934. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  39935. subSq = options.subDiv.max * options.subDiv.max;
  39936. options.facetPartitioning.length = 0;
  39937. }
  39938. // reset the normals
  39939. for (index = 0; index < positions.length; index++) {
  39940. normals[index] = 0.0;
  39941. }
  39942. // Loop : 1 indice triplet = 1 facet
  39943. var nbFaces = (indices.length / 3) | 0;
  39944. for (index = 0; index < nbFaces; index++) {
  39945. // get the indexes of the coordinates of each vertex of the facet
  39946. v1x = indices[index * 3] * 3;
  39947. v1y = v1x + 1;
  39948. v1z = v1x + 2;
  39949. v2x = indices[index * 3 + 1] * 3;
  39950. v2y = v2x + 1;
  39951. v2z = v2x + 2;
  39952. v3x = indices[index * 3 + 2] * 3;
  39953. v3y = v3x + 1;
  39954. v3z = v3x + 2;
  39955. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  39956. p1p2y = positions[v1y] - positions[v2y];
  39957. p1p2z = positions[v1z] - positions[v2z];
  39958. p3p2x = positions[v3x] - positions[v2x];
  39959. p3p2y = positions[v3y] - positions[v2y];
  39960. p3p2z = positions[v3z] - positions[v2z];
  39961. // compute the face normal with the cross product
  39962. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  39963. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  39964. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  39965. // normalize this normal and store it in the array facetData
  39966. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  39967. length = (length === 0) ? 1.0 : length;
  39968. faceNormalx /= length;
  39969. faceNormaly /= length;
  39970. faceNormalz /= length;
  39971. if (computeFacetNormals && options) {
  39972. options.facetNormals[index].x = faceNormalx;
  39973. options.facetNormals[index].y = faceNormaly;
  39974. options.facetNormals[index].z = faceNormalz;
  39975. }
  39976. if (computeFacetPositions && options) {
  39977. // compute and the facet barycenter coordinates in the array facetPositions
  39978. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  39979. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  39980. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  39981. }
  39982. if (computeFacetPartitioning && options) {
  39983. // store the facet indexes in arrays in the main facetPartitioning array :
  39984. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  39985. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  39986. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  39987. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  39988. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  39989. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  39990. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  39991. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  39992. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  39993. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  39994. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  39995. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  39996. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  39997. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  39998. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  39999. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  40000. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  40001. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  40002. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  40003. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  40004. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  40005. // push each facet index in each block containing the vertex
  40006. options.facetPartitioning[block_idx_v1].push(index);
  40007. if (block_idx_v2 != block_idx_v1) {
  40008. options.facetPartitioning[block_idx_v2].push(index);
  40009. }
  40010. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  40011. options.facetPartitioning[block_idx_v3].push(index);
  40012. }
  40013. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  40014. options.facetPartitioning[block_idx_o].push(index);
  40015. }
  40016. }
  40017. if (computeDepthSort && options && options.facetPositions) {
  40018. var dsf = depthSortedFacets[index];
  40019. dsf.ind = index * 3;
  40020. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  40021. }
  40022. // compute the normals anyway
  40023. normals[v1x] += faceNormalx; // accumulate all the normals per face
  40024. normals[v1y] += faceNormaly;
  40025. normals[v1z] += faceNormalz;
  40026. normals[v2x] += faceNormalx;
  40027. normals[v2y] += faceNormaly;
  40028. normals[v2z] += faceNormalz;
  40029. normals[v3x] += faceNormalx;
  40030. normals[v3y] += faceNormaly;
  40031. normals[v3z] += faceNormalz;
  40032. }
  40033. // last normalization of each normal
  40034. for (index = 0; index < normals.length / 3; index++) {
  40035. faceNormalx = normals[index * 3];
  40036. faceNormaly = normals[index * 3 + 1];
  40037. faceNormalz = normals[index * 3 + 2];
  40038. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  40039. length = (length === 0) ? 1.0 : length;
  40040. faceNormalx /= length;
  40041. faceNormaly /= length;
  40042. faceNormalz /= length;
  40043. normals[index * 3] = faceNormalx;
  40044. normals[index * 3 + 1] = faceNormaly;
  40045. normals[index * 3 + 2] = faceNormalz;
  40046. }
  40047. };
  40048. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  40049. var li = indices.length;
  40050. var ln = normals.length;
  40051. var i;
  40052. var n;
  40053. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  40054. switch (sideOrientation) {
  40055. case BABYLON.Mesh.FRONTSIDE:
  40056. // nothing changed
  40057. break;
  40058. case BABYLON.Mesh.BACKSIDE:
  40059. var tmp;
  40060. // indices
  40061. for (i = 0; i < li; i += 3) {
  40062. tmp = indices[i];
  40063. indices[i] = indices[i + 2];
  40064. indices[i + 2] = tmp;
  40065. }
  40066. // normals
  40067. for (n = 0; n < ln; n++) {
  40068. normals[n] = -normals[n];
  40069. }
  40070. break;
  40071. case BABYLON.Mesh.DOUBLESIDE:
  40072. // positions
  40073. var lp = positions.length;
  40074. var l = lp / 3;
  40075. for (var p = 0; p < lp; p++) {
  40076. positions[lp + p] = positions[p];
  40077. }
  40078. // indices
  40079. for (i = 0; i < li; i += 3) {
  40080. indices[i + li] = indices[i + 2] + l;
  40081. indices[i + 1 + li] = indices[i + 1] + l;
  40082. indices[i + 2 + li] = indices[i] + l;
  40083. }
  40084. // normals
  40085. for (n = 0; n < ln; n++) {
  40086. normals[ln + n] = -normals[n];
  40087. }
  40088. // uvs
  40089. var lu = uvs.length;
  40090. var u = 0;
  40091. for (u = 0; u < lu; u++) {
  40092. uvs[u + lu] = uvs[u];
  40093. }
  40094. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  40095. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  40096. u = 0;
  40097. for (i = 0; i < lu / 2; i++) {
  40098. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  40099. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  40100. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  40101. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  40102. u += 2;
  40103. }
  40104. break;
  40105. }
  40106. };
  40107. /**
  40108. * Applies VertexData created from the imported parameters to the geometry
  40109. * @param parsedVertexData the parsed data from an imported file
  40110. * @param geometry the geometry to apply the VertexData to
  40111. */
  40112. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  40113. var vertexData = new VertexData();
  40114. // positions
  40115. var positions = parsedVertexData.positions;
  40116. if (positions) {
  40117. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  40118. }
  40119. // normals
  40120. var normals = parsedVertexData.normals;
  40121. if (normals) {
  40122. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  40123. }
  40124. // tangents
  40125. var tangents = parsedVertexData.tangents;
  40126. if (tangents) {
  40127. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  40128. }
  40129. // uvs
  40130. var uvs = parsedVertexData.uvs;
  40131. if (uvs) {
  40132. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  40133. }
  40134. // uv2s
  40135. var uv2s = parsedVertexData.uv2s;
  40136. if (uv2s) {
  40137. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  40138. }
  40139. // uv3s
  40140. var uv3s = parsedVertexData.uv3s;
  40141. if (uv3s) {
  40142. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  40143. }
  40144. // uv4s
  40145. var uv4s = parsedVertexData.uv4s;
  40146. if (uv4s) {
  40147. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  40148. }
  40149. // uv5s
  40150. var uv5s = parsedVertexData.uv5s;
  40151. if (uv5s) {
  40152. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  40153. }
  40154. // uv6s
  40155. var uv6s = parsedVertexData.uv6s;
  40156. if (uv6s) {
  40157. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  40158. }
  40159. // colors
  40160. var colors = parsedVertexData.colors;
  40161. if (colors) {
  40162. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  40163. }
  40164. // matricesIndices
  40165. var matricesIndices = parsedVertexData.matricesIndices;
  40166. if (matricesIndices) {
  40167. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  40168. }
  40169. // matricesWeights
  40170. var matricesWeights = parsedVertexData.matricesWeights;
  40171. if (matricesWeights) {
  40172. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  40173. }
  40174. // indices
  40175. var indices = parsedVertexData.indices;
  40176. if (indices) {
  40177. vertexData.indices = indices;
  40178. }
  40179. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  40180. };
  40181. return VertexData;
  40182. }());
  40183. BABYLON.VertexData = VertexData;
  40184. })(BABYLON || (BABYLON = {}));
  40185. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  40186. var BABYLON;
  40187. (function (BABYLON) {
  40188. /**
  40189. * Class used to store geometry data (vertex buffers + index buffer)
  40190. */
  40191. var Geometry = /** @class */ (function () {
  40192. /**
  40193. * Creates a new geometry
  40194. * @param id defines the unique ID
  40195. * @param scene defines the hosting scene
  40196. * @param vertexData defines the VertexData used to get geometry data
  40197. * @param updatable defines if geometry must be updatable (false by default)
  40198. * @param mesh defines the mesh that will be associated with the geometry
  40199. */
  40200. function Geometry(id, scene, vertexData, updatable, mesh) {
  40201. if (updatable === void 0) { updatable = false; }
  40202. if (mesh === void 0) { mesh = null; }
  40203. /**
  40204. * Gets the delay loading state of the geometry (none by default which means not delayed)
  40205. */
  40206. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  40207. this._totalVertices = 0;
  40208. this._isDisposed = false;
  40209. this._indexBufferIsUpdatable = false;
  40210. this.id = id;
  40211. this._engine = scene.getEngine();
  40212. this._meshes = [];
  40213. this._scene = scene;
  40214. //Init vertex buffer cache
  40215. this._vertexBuffers = {};
  40216. this._indices = [];
  40217. this._updatable = updatable;
  40218. // vertexData
  40219. if (vertexData) {
  40220. this.setAllVerticesData(vertexData, updatable);
  40221. }
  40222. else {
  40223. this._totalVertices = 0;
  40224. this._indices = [];
  40225. }
  40226. if (this._engine.getCaps().vertexArrayObject) {
  40227. this._vertexArrayObjects = {};
  40228. }
  40229. // applyToMesh
  40230. if (mesh) {
  40231. if (mesh.getClassName() === "LinesMesh") {
  40232. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  40233. this._updateExtend();
  40234. }
  40235. this.applyToMesh(mesh);
  40236. mesh.computeWorldMatrix(true);
  40237. }
  40238. }
  40239. Object.defineProperty(Geometry.prototype, "boundingBias", {
  40240. /**
  40241. * 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
  40242. */
  40243. get: function () {
  40244. return this._boundingBias;
  40245. },
  40246. /**
  40247. * 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
  40248. */
  40249. set: function (value) {
  40250. if (this._boundingBias) {
  40251. if (this._boundingBias.equals(value)) {
  40252. return;
  40253. }
  40254. this._boundingBias.copyFrom(value);
  40255. }
  40256. else {
  40257. this._boundingBias = value.clone();
  40258. }
  40259. this._updateBoundingInfo(true, null);
  40260. },
  40261. enumerable: true,
  40262. configurable: true
  40263. });
  40264. /**
  40265. * Static function used to attach a new empty geometry to a mesh
  40266. * @param mesh defines the mesh to attach the geometry to
  40267. * @returns the new Geometry
  40268. */
  40269. Geometry.CreateGeometryForMesh = function (mesh) {
  40270. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  40271. geometry.applyToMesh(mesh);
  40272. return geometry;
  40273. };
  40274. Object.defineProperty(Geometry.prototype, "extend", {
  40275. /**
  40276. * Gets the current extend of the geometry
  40277. */
  40278. get: function () {
  40279. return this._extend;
  40280. },
  40281. enumerable: true,
  40282. configurable: true
  40283. });
  40284. /**
  40285. * Gets the hosting scene
  40286. * @returns the hosting Scene
  40287. */
  40288. Geometry.prototype.getScene = function () {
  40289. return this._scene;
  40290. };
  40291. /**
  40292. * Gets the hosting engine
  40293. * @returns the hosting Engine
  40294. */
  40295. Geometry.prototype.getEngine = function () {
  40296. return this._engine;
  40297. };
  40298. /**
  40299. * Defines if the geometry is ready to use
  40300. * @returns true if the geometry is ready to be used
  40301. */
  40302. Geometry.prototype.isReady = function () {
  40303. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  40304. };
  40305. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  40306. /**
  40307. * Gets a value indicating that the geometry should not be serialized
  40308. */
  40309. get: function () {
  40310. for (var index = 0; index < this._meshes.length; index++) {
  40311. if (!this._meshes[index].doNotSerialize) {
  40312. return false;
  40313. }
  40314. }
  40315. return true;
  40316. },
  40317. enumerable: true,
  40318. configurable: true
  40319. });
  40320. /** @hidden */
  40321. Geometry.prototype._rebuild = function () {
  40322. if (this._vertexArrayObjects) {
  40323. this._vertexArrayObjects = {};
  40324. }
  40325. // Index buffer
  40326. if (this._meshes.length !== 0 && this._indices) {
  40327. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  40328. }
  40329. // Vertex buffers
  40330. for (var key in this._vertexBuffers) {
  40331. var vertexBuffer = this._vertexBuffers[key];
  40332. vertexBuffer._rebuild();
  40333. }
  40334. };
  40335. /**
  40336. * Affects all geometry data in one call
  40337. * @param vertexData defines the geometry data
  40338. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  40339. */
  40340. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40341. vertexData.applyToGeometry(this, updatable);
  40342. this.notifyUpdate();
  40343. };
  40344. /**
  40345. * Set specific vertex data
  40346. * @param kind defines the data kind (Position, normal, etc...)
  40347. * @param data defines the vertex data to use
  40348. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  40349. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  40350. */
  40351. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  40352. if (updatable === void 0) { updatable = false; }
  40353. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  40354. this.setVerticesBuffer(buffer);
  40355. };
  40356. /**
  40357. * Removes a specific vertex data
  40358. * @param kind defines the data kind (Position, normal, etc...)
  40359. */
  40360. Geometry.prototype.removeVerticesData = function (kind) {
  40361. if (this._vertexBuffers[kind]) {
  40362. this._vertexBuffers[kind].dispose();
  40363. delete this._vertexBuffers[kind];
  40364. }
  40365. };
  40366. /**
  40367. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  40368. * @param buffer defines the vertex buffer to use
  40369. * @param totalVertices defines the total number of vertices for position kind (could be null)
  40370. */
  40371. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  40372. if (totalVertices === void 0) { totalVertices = null; }
  40373. var kind = buffer.getKind();
  40374. if (this._vertexBuffers[kind]) {
  40375. this._vertexBuffers[kind].dispose();
  40376. }
  40377. this._vertexBuffers[kind] = buffer;
  40378. if (kind === BABYLON.VertexBuffer.PositionKind) {
  40379. var data = buffer.getData();
  40380. if (totalVertices != null) {
  40381. this._totalVertices = totalVertices;
  40382. }
  40383. else {
  40384. if (data != null) {
  40385. this._totalVertices = data.length / (buffer.byteStride / 4);
  40386. }
  40387. }
  40388. this._updateExtend(data);
  40389. this._resetPointsArrayCache();
  40390. var meshes = this._meshes;
  40391. var numOfMeshes = meshes.length;
  40392. for (var index = 0; index < numOfMeshes; index++) {
  40393. var mesh = meshes[index];
  40394. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40395. mesh._createGlobalSubMesh(false);
  40396. mesh.computeWorldMatrix(true);
  40397. }
  40398. }
  40399. this.notifyUpdate(kind);
  40400. if (this._vertexArrayObjects) {
  40401. this._disposeVertexArrayObjects();
  40402. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  40403. }
  40404. };
  40405. /**
  40406. * Update a specific vertex buffer
  40407. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  40408. * It will do nothing if the buffer is not updatable
  40409. * @param kind defines the data kind (Position, normal, etc...)
  40410. * @param data defines the data to use
  40411. * @param offset defines the offset in the target buffer where to store the data
  40412. * @param useBytes set to true if the offset is in bytes
  40413. */
  40414. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  40415. if (useBytes === void 0) { useBytes = false; }
  40416. var vertexBuffer = this.getVertexBuffer(kind);
  40417. if (!vertexBuffer) {
  40418. return;
  40419. }
  40420. vertexBuffer.updateDirectly(data, offset, useBytes);
  40421. this.notifyUpdate(kind);
  40422. };
  40423. /**
  40424. * Update a specific vertex buffer
  40425. * This function will create a new buffer if the current one is not updatable
  40426. * @param kind defines the data kind (Position, normal, etc...)
  40427. * @param data defines the data to use
  40428. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  40429. */
  40430. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  40431. if (updateExtends === void 0) { updateExtends = false; }
  40432. var vertexBuffer = this.getVertexBuffer(kind);
  40433. if (!vertexBuffer) {
  40434. return;
  40435. }
  40436. vertexBuffer.update(data);
  40437. if (kind === BABYLON.VertexBuffer.PositionKind) {
  40438. this._updateBoundingInfo(updateExtends, data);
  40439. }
  40440. this.notifyUpdate(kind);
  40441. };
  40442. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  40443. if (updateExtends) {
  40444. this._updateExtend(data);
  40445. }
  40446. var meshes = this._meshes;
  40447. var numOfMeshes = meshes.length;
  40448. this._resetPointsArrayCache();
  40449. for (var index = 0; index < numOfMeshes; index++) {
  40450. var mesh = meshes[index];
  40451. if (updateExtends) {
  40452. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40453. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  40454. var subMesh = mesh.subMeshes[subIndex];
  40455. subMesh.refreshBoundingInfo();
  40456. }
  40457. }
  40458. }
  40459. };
  40460. /** @hidden */
  40461. Geometry.prototype._bind = function (effect, indexToBind) {
  40462. if (!effect) {
  40463. return;
  40464. }
  40465. if (indexToBind === undefined) {
  40466. indexToBind = this._indexBuffer;
  40467. }
  40468. var vbs = this.getVertexBuffers();
  40469. if (!vbs) {
  40470. return;
  40471. }
  40472. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  40473. this._engine.bindBuffers(vbs, indexToBind, effect);
  40474. return;
  40475. }
  40476. // Using VAO
  40477. if (!this._vertexArrayObjects[effect.key]) {
  40478. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  40479. }
  40480. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  40481. };
  40482. /**
  40483. * Gets total number of vertices
  40484. * @returns the total number of vertices
  40485. */
  40486. Geometry.prototype.getTotalVertices = function () {
  40487. if (!this.isReady()) {
  40488. return 0;
  40489. }
  40490. return this._totalVertices;
  40491. };
  40492. /**
  40493. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  40494. * @param kind defines the data kind (Position, normal, etc...)
  40495. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  40496. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  40497. * @returns a float array containing vertex data
  40498. */
  40499. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  40500. var vertexBuffer = this.getVertexBuffer(kind);
  40501. if (!vertexBuffer) {
  40502. return null;
  40503. }
  40504. var data = vertexBuffer.getData();
  40505. if (!data) {
  40506. return null;
  40507. }
  40508. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  40509. var count = this._totalVertices * vertexBuffer.getSize();
  40510. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  40511. var copy_1 = new Array(count);
  40512. vertexBuffer.forEach(count, function (value, index) {
  40513. copy_1[index] = value;
  40514. });
  40515. return copy_1;
  40516. }
  40517. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  40518. if (data instanceof Array) {
  40519. var offset = vertexBuffer.byteOffset / 4;
  40520. return BABYLON.Tools.Slice(data, offset, offset + count);
  40521. }
  40522. else if (data instanceof ArrayBuffer) {
  40523. return new Float32Array(data, vertexBuffer.byteOffset, count);
  40524. }
  40525. else {
  40526. var offset = data.byteOffset + vertexBuffer.byteOffset;
  40527. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  40528. var result = new Float32Array(count);
  40529. var source = new Float32Array(data.buffer, offset, count);
  40530. result.set(source);
  40531. return result;
  40532. }
  40533. return new Float32Array(data.buffer, offset, count);
  40534. }
  40535. }
  40536. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  40537. return BABYLON.Tools.Slice(data);
  40538. }
  40539. return data;
  40540. };
  40541. /**
  40542. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  40543. * @param kind defines the data kind (Position, normal, etc...)
  40544. * @returns true if the vertex buffer with the specified kind is updatable
  40545. */
  40546. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  40547. var vb = this._vertexBuffers[kind];
  40548. if (!vb) {
  40549. return false;
  40550. }
  40551. return vb.isUpdatable();
  40552. };
  40553. /**
  40554. * Gets a specific vertex buffer
  40555. * @param kind defines the data kind (Position, normal, etc...)
  40556. * @returns a VertexBuffer
  40557. */
  40558. Geometry.prototype.getVertexBuffer = function (kind) {
  40559. if (!this.isReady()) {
  40560. return null;
  40561. }
  40562. return this._vertexBuffers[kind];
  40563. };
  40564. /**
  40565. * Returns all vertex buffers
  40566. * @return an object holding all vertex buffers indexed by kind
  40567. */
  40568. Geometry.prototype.getVertexBuffers = function () {
  40569. if (!this.isReady()) {
  40570. return null;
  40571. }
  40572. return this._vertexBuffers;
  40573. };
  40574. /**
  40575. * Gets a boolean indicating if specific vertex buffer is present
  40576. * @param kind defines the data kind (Position, normal, etc...)
  40577. * @returns true if data is present
  40578. */
  40579. Geometry.prototype.isVerticesDataPresent = function (kind) {
  40580. if (!this._vertexBuffers) {
  40581. if (this._delayInfo) {
  40582. return this._delayInfo.indexOf(kind) !== -1;
  40583. }
  40584. return false;
  40585. }
  40586. return this._vertexBuffers[kind] !== undefined;
  40587. };
  40588. /**
  40589. * Gets a list of all attached data kinds (Position, normal, etc...)
  40590. * @returns a list of string containing all kinds
  40591. */
  40592. Geometry.prototype.getVerticesDataKinds = function () {
  40593. var result = [];
  40594. var kind;
  40595. if (!this._vertexBuffers && this._delayInfo) {
  40596. for (kind in this._delayInfo) {
  40597. result.push(kind);
  40598. }
  40599. }
  40600. else {
  40601. for (kind in this._vertexBuffers) {
  40602. result.push(kind);
  40603. }
  40604. }
  40605. return result;
  40606. };
  40607. /**
  40608. * Update index buffer
  40609. * @param indices defines the indices to store in the index buffer
  40610. * @param offset defines the offset in the target buffer where to store the data
  40611. */
  40612. Geometry.prototype.updateIndices = function (indices, offset) {
  40613. if (!this._indexBuffer) {
  40614. return;
  40615. }
  40616. if (!this._indexBufferIsUpdatable) {
  40617. this.setIndices(indices, null, true);
  40618. }
  40619. else {
  40620. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  40621. }
  40622. };
  40623. /**
  40624. * Creates a new index buffer
  40625. * @param indices defines the indices to store in the index buffer
  40626. * @param totalVertices defines the total number of vertices (could be null)
  40627. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  40628. */
  40629. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  40630. if (totalVertices === void 0) { totalVertices = null; }
  40631. if (updatable === void 0) { updatable = false; }
  40632. if (this._indexBuffer) {
  40633. this._engine._releaseBuffer(this._indexBuffer);
  40634. }
  40635. this._disposeVertexArrayObjects();
  40636. this._indices = indices;
  40637. this._indexBufferIsUpdatable = updatable;
  40638. if (this._meshes.length !== 0 && this._indices) {
  40639. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  40640. }
  40641. if (totalVertices != undefined) { // including null and undefined
  40642. this._totalVertices = totalVertices;
  40643. }
  40644. var meshes = this._meshes;
  40645. var numOfMeshes = meshes.length;
  40646. for (var index = 0; index < numOfMeshes; index++) {
  40647. meshes[index]._createGlobalSubMesh(true);
  40648. }
  40649. this.notifyUpdate();
  40650. };
  40651. /**
  40652. * Return the total number of indices
  40653. * @returns the total number of indices
  40654. */
  40655. Geometry.prototype.getTotalIndices = function () {
  40656. if (!this.isReady()) {
  40657. return 0;
  40658. }
  40659. return this._indices.length;
  40660. };
  40661. /**
  40662. * Gets the index buffer array
  40663. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  40664. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  40665. * @returns the index buffer array
  40666. */
  40667. Geometry.prototype.getIndices = function (copyWhenShared, forceCopy) {
  40668. if (!this.isReady()) {
  40669. return null;
  40670. }
  40671. var orig = this._indices;
  40672. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  40673. return orig;
  40674. }
  40675. else {
  40676. var len = orig.length;
  40677. var copy = [];
  40678. for (var i = 0; i < len; i++) {
  40679. copy.push(orig[i]);
  40680. }
  40681. return copy;
  40682. }
  40683. };
  40684. /**
  40685. * Gets the index buffer
  40686. * @return the index buffer
  40687. */
  40688. Geometry.prototype.getIndexBuffer = function () {
  40689. if (!this.isReady()) {
  40690. return null;
  40691. }
  40692. return this._indexBuffer;
  40693. };
  40694. /** @hidden */
  40695. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  40696. if (effect === void 0) { effect = null; }
  40697. if (!effect || !this._vertexArrayObjects) {
  40698. return;
  40699. }
  40700. if (this._vertexArrayObjects[effect.key]) {
  40701. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  40702. delete this._vertexArrayObjects[effect.key];
  40703. }
  40704. };
  40705. /**
  40706. * Release the associated resources for a specific mesh
  40707. * @param mesh defines the source mesh
  40708. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  40709. */
  40710. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  40711. var meshes = this._meshes;
  40712. var index = meshes.indexOf(mesh);
  40713. if (index === -1) {
  40714. return;
  40715. }
  40716. meshes.splice(index, 1);
  40717. mesh._geometry = null;
  40718. if (meshes.length === 0 && shouldDispose) {
  40719. this.dispose();
  40720. }
  40721. };
  40722. /**
  40723. * Apply current geometry to a given mesh
  40724. * @param mesh defines the mesh to apply geometry to
  40725. */
  40726. Geometry.prototype.applyToMesh = function (mesh) {
  40727. if (mesh._geometry === this) {
  40728. return;
  40729. }
  40730. var previousGeometry = mesh._geometry;
  40731. if (previousGeometry) {
  40732. previousGeometry.releaseForMesh(mesh);
  40733. }
  40734. var meshes = this._meshes;
  40735. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  40736. mesh._geometry = this;
  40737. this._scene.pushGeometry(this);
  40738. meshes.push(mesh);
  40739. if (this.isReady()) {
  40740. this._applyToMesh(mesh);
  40741. }
  40742. else {
  40743. mesh._boundingInfo = this._boundingInfo;
  40744. }
  40745. };
  40746. Geometry.prototype._updateExtend = function (data) {
  40747. if (data === void 0) { data = null; }
  40748. if (!data) {
  40749. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40750. }
  40751. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  40752. };
  40753. Geometry.prototype._applyToMesh = function (mesh) {
  40754. var numOfMeshes = this._meshes.length;
  40755. // vertexBuffers
  40756. for (var kind in this._vertexBuffers) {
  40757. if (numOfMeshes === 1) {
  40758. this._vertexBuffers[kind].create();
  40759. }
  40760. var buffer = this._vertexBuffers[kind].getBuffer();
  40761. if (buffer) {
  40762. buffer.references = numOfMeshes;
  40763. }
  40764. if (kind === BABYLON.VertexBuffer.PositionKind) {
  40765. if (!this._extend) {
  40766. this._updateExtend();
  40767. }
  40768. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40769. mesh._createGlobalSubMesh(false);
  40770. //bounding info was just created again, world matrix should be applied again.
  40771. mesh._updateBoundingInfo();
  40772. }
  40773. }
  40774. // indexBuffer
  40775. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  40776. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  40777. }
  40778. if (this._indexBuffer) {
  40779. this._indexBuffer.references = numOfMeshes;
  40780. }
  40781. // morphTargets
  40782. mesh._syncGeometryWithMorphTargetManager();
  40783. };
  40784. Geometry.prototype.notifyUpdate = function (kind) {
  40785. if (this.onGeometryUpdated) {
  40786. this.onGeometryUpdated(this, kind);
  40787. }
  40788. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  40789. var mesh = _a[_i];
  40790. mesh._markSubMeshesAsAttributesDirty();
  40791. }
  40792. };
  40793. /**
  40794. * Load the geometry if it was flagged as delay loaded
  40795. * @param scene defines the hosting scene
  40796. * @param onLoaded defines a callback called when the geometry is loaded
  40797. */
  40798. Geometry.prototype.load = function (scene, onLoaded) {
  40799. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  40800. return;
  40801. }
  40802. if (this.isReady()) {
  40803. if (onLoaded) {
  40804. onLoaded();
  40805. }
  40806. return;
  40807. }
  40808. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  40809. this._queueLoad(scene, onLoaded);
  40810. };
  40811. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  40812. var _this = this;
  40813. if (!this.delayLoadingFile) {
  40814. return;
  40815. }
  40816. scene._addPendingData(this);
  40817. scene._loadFile(this.delayLoadingFile, function (data) {
  40818. if (!_this._delayLoadingFunction) {
  40819. return;
  40820. }
  40821. _this._delayLoadingFunction(JSON.parse(data), _this);
  40822. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  40823. _this._delayInfo = [];
  40824. scene._removePendingData(_this);
  40825. var meshes = _this._meshes;
  40826. var numOfMeshes = meshes.length;
  40827. for (var index = 0; index < numOfMeshes; index++) {
  40828. _this._applyToMesh(meshes[index]);
  40829. }
  40830. if (onLoaded) {
  40831. onLoaded();
  40832. }
  40833. }, undefined, true);
  40834. };
  40835. /**
  40836. * Invert the geometry to move from a right handed system to a left handed one.
  40837. */
  40838. Geometry.prototype.toLeftHanded = function () {
  40839. // Flip faces
  40840. var tIndices = this.getIndices(false);
  40841. if (tIndices != null && tIndices.length > 0) {
  40842. for (var i = 0; i < tIndices.length; i += 3) {
  40843. var tTemp = tIndices[i + 0];
  40844. tIndices[i + 0] = tIndices[i + 2];
  40845. tIndices[i + 2] = tTemp;
  40846. }
  40847. this.setIndices(tIndices);
  40848. }
  40849. // Negate position.z
  40850. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  40851. if (tPositions != null && tPositions.length > 0) {
  40852. for (var i = 0; i < tPositions.length; i += 3) {
  40853. tPositions[i + 2] = -tPositions[i + 2];
  40854. }
  40855. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  40856. }
  40857. // Negate normal.z
  40858. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  40859. if (tNormals != null && tNormals.length > 0) {
  40860. for (var i = 0; i < tNormals.length; i += 3) {
  40861. tNormals[i + 2] = -tNormals[i + 2];
  40862. }
  40863. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  40864. }
  40865. };
  40866. // Cache
  40867. /** @hidden */
  40868. Geometry.prototype._resetPointsArrayCache = function () {
  40869. this._positions = null;
  40870. };
  40871. /** @hidden */
  40872. Geometry.prototype._generatePointsArray = function () {
  40873. if (this._positions) {
  40874. return true;
  40875. }
  40876. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40877. if (!data || data.length === 0) {
  40878. return false;
  40879. }
  40880. this._positions = [];
  40881. for (var index = 0; index < data.length; index += 3) {
  40882. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  40883. }
  40884. return true;
  40885. };
  40886. /**
  40887. * Gets a value indicating if the geometry is disposed
  40888. * @returns true if the geometry was disposed
  40889. */
  40890. Geometry.prototype.isDisposed = function () {
  40891. return this._isDisposed;
  40892. };
  40893. Geometry.prototype._disposeVertexArrayObjects = function () {
  40894. if (this._vertexArrayObjects) {
  40895. for (var kind in this._vertexArrayObjects) {
  40896. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  40897. }
  40898. this._vertexArrayObjects = {};
  40899. }
  40900. };
  40901. /**
  40902. * Free all associated resources
  40903. */
  40904. Geometry.prototype.dispose = function () {
  40905. var meshes = this._meshes;
  40906. var numOfMeshes = meshes.length;
  40907. var index;
  40908. for (index = 0; index < numOfMeshes; index++) {
  40909. this.releaseForMesh(meshes[index]);
  40910. }
  40911. this._meshes = [];
  40912. this._disposeVertexArrayObjects();
  40913. for (var kind in this._vertexBuffers) {
  40914. this._vertexBuffers[kind].dispose();
  40915. }
  40916. this._vertexBuffers = {};
  40917. this._totalVertices = 0;
  40918. if (this._indexBuffer) {
  40919. this._engine._releaseBuffer(this._indexBuffer);
  40920. }
  40921. this._indexBuffer = null;
  40922. this._indices = [];
  40923. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  40924. this.delayLoadingFile = null;
  40925. this._delayLoadingFunction = null;
  40926. this._delayInfo = [];
  40927. this._boundingInfo = null;
  40928. this._scene.removeGeometry(this);
  40929. this._isDisposed = true;
  40930. };
  40931. /**
  40932. * Clone the current geometry into a new geometry
  40933. * @param id defines the unique ID of the new geometry
  40934. * @returns a new geometry object
  40935. */
  40936. Geometry.prototype.copy = function (id) {
  40937. var vertexData = new BABYLON.VertexData();
  40938. vertexData.indices = [];
  40939. var indices = this.getIndices();
  40940. if (indices) {
  40941. for (var index = 0; index < indices.length; index++) {
  40942. vertexData.indices.push(indices[index]);
  40943. }
  40944. }
  40945. var updatable = false;
  40946. var stopChecking = false;
  40947. var kind;
  40948. for (kind in this._vertexBuffers) {
  40949. // using slice() to make a copy of the array and not just reference it
  40950. var data = this.getVerticesData(kind);
  40951. if (data instanceof Float32Array) {
  40952. vertexData.set(new Float32Array(data), kind);
  40953. }
  40954. else {
  40955. vertexData.set(data.slice(0), kind);
  40956. }
  40957. if (!stopChecking) {
  40958. var vb = this.getVertexBuffer(kind);
  40959. if (vb) {
  40960. updatable = vb.isUpdatable();
  40961. stopChecking = !updatable;
  40962. }
  40963. }
  40964. }
  40965. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  40966. geometry.delayLoadState = this.delayLoadState;
  40967. geometry.delayLoadingFile = this.delayLoadingFile;
  40968. geometry._delayLoadingFunction = this._delayLoadingFunction;
  40969. for (kind in this._delayInfo) {
  40970. geometry._delayInfo = geometry._delayInfo || [];
  40971. geometry._delayInfo.push(kind);
  40972. }
  40973. // Bounding info
  40974. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40975. return geometry;
  40976. };
  40977. /**
  40978. * Serialize the current geometry info (and not the vertices data) into a JSON object
  40979. * @return a JSON representation of the current geometry data (without the vertices data)
  40980. */
  40981. Geometry.prototype.serialize = function () {
  40982. var serializationObject = {};
  40983. serializationObject.id = this.id;
  40984. serializationObject.updatable = this._updatable;
  40985. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  40986. serializationObject.tags = BABYLON.Tags.GetTags(this);
  40987. }
  40988. return serializationObject;
  40989. };
  40990. Geometry.prototype.toNumberArray = function (origin) {
  40991. if (Array.isArray(origin)) {
  40992. return origin;
  40993. }
  40994. else {
  40995. return Array.prototype.slice.call(origin);
  40996. }
  40997. };
  40998. /**
  40999. * Serialize all vertices data into a JSON oject
  41000. * @returns a JSON representation of the current geometry data
  41001. */
  41002. Geometry.prototype.serializeVerticeData = function () {
  41003. var serializationObject = this.serialize();
  41004. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  41005. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  41006. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  41007. serializationObject.positions._updatable = true;
  41008. }
  41009. }
  41010. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  41011. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  41012. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  41013. serializationObject.normals._updatable = true;
  41014. }
  41015. }
  41016. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41017. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  41018. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  41019. serializationObject.tangets._updatable = true;
  41020. }
  41021. }
  41022. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  41023. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  41024. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  41025. serializationObject.uvs._updatable = true;
  41026. }
  41027. }
  41028. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  41029. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  41030. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  41031. serializationObject.uv2s._updatable = true;
  41032. }
  41033. }
  41034. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  41035. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  41036. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  41037. serializationObject.uv3s._updatable = true;
  41038. }
  41039. }
  41040. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  41041. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  41042. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  41043. serializationObject.uv4s._updatable = true;
  41044. }
  41045. }
  41046. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  41047. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  41048. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  41049. serializationObject.uv5s._updatable = true;
  41050. }
  41051. }
  41052. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  41053. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  41054. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  41055. serializationObject.uv6s._updatable = true;
  41056. }
  41057. }
  41058. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  41059. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  41060. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  41061. serializationObject.colors._updatable = true;
  41062. }
  41063. }
  41064. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  41065. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  41066. serializationObject.matricesIndices._isExpanded = true;
  41067. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  41068. serializationObject.matricesIndices._updatable = true;
  41069. }
  41070. }
  41071. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  41072. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  41073. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  41074. serializationObject.matricesWeights._updatable = true;
  41075. }
  41076. }
  41077. serializationObject.indices = this.toNumberArray(this.getIndices());
  41078. return serializationObject;
  41079. };
  41080. // Statics
  41081. /**
  41082. * Extracts a clone of a mesh geometry
  41083. * @param mesh defines the source mesh
  41084. * @param id defines the unique ID of the new geometry object
  41085. * @returns the new geometry object
  41086. */
  41087. Geometry.ExtractFromMesh = function (mesh, id) {
  41088. var geometry = mesh._geometry;
  41089. if (!geometry) {
  41090. return null;
  41091. }
  41092. return geometry.copy(id);
  41093. };
  41094. /**
  41095. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  41096. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  41097. * Be aware Math.random() could cause collisions, but:
  41098. * "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"
  41099. * @returns a string containing a new GUID
  41100. */
  41101. Geometry.RandomId = function () {
  41102. return BABYLON.Tools.RandomId();
  41103. };
  41104. /** @hidden */
  41105. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  41106. var scene = mesh.getScene();
  41107. // Geometry
  41108. var geometryId = parsedGeometry.geometryId;
  41109. if (geometryId) {
  41110. var geometry = scene.getGeometryByID(geometryId);
  41111. if (geometry) {
  41112. geometry.applyToMesh(mesh);
  41113. }
  41114. }
  41115. else if (parsedGeometry instanceof ArrayBuffer) {
  41116. var binaryInfo = mesh._binaryInfo;
  41117. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  41118. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  41119. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  41120. }
  41121. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  41122. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  41123. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  41124. }
  41125. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  41126. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  41127. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  41128. }
  41129. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  41130. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  41131. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  41132. }
  41133. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  41134. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  41135. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  41136. }
  41137. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  41138. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  41139. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  41140. }
  41141. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  41142. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  41143. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  41144. }
  41145. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  41146. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  41147. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  41148. }
  41149. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  41150. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  41151. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  41152. }
  41153. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  41154. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  41155. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  41156. }
  41157. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  41158. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  41159. var floatIndices = [];
  41160. for (var i = 0; i < matricesIndicesData.length; i++) {
  41161. var index = matricesIndicesData[i];
  41162. floatIndices.push(index & 0x000000FF);
  41163. floatIndices.push((index & 0x0000FF00) >> 8);
  41164. floatIndices.push((index & 0x00FF0000) >> 16);
  41165. floatIndices.push(index >> 24);
  41166. }
  41167. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  41168. }
  41169. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  41170. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  41171. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  41172. }
  41173. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  41174. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  41175. mesh.setIndices(indicesData, null);
  41176. }
  41177. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  41178. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  41179. mesh.subMeshes = [];
  41180. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  41181. var materialIndex = subMeshesData[(i * 5) + 0];
  41182. var verticesStart = subMeshesData[(i * 5) + 1];
  41183. var verticesCount = subMeshesData[(i * 5) + 2];
  41184. var indexStart = subMeshesData[(i * 5) + 3];
  41185. var indexCount = subMeshesData[(i * 5) + 4];
  41186. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  41187. }
  41188. }
  41189. }
  41190. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  41191. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  41192. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  41193. if (parsedGeometry.tangents) {
  41194. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  41195. }
  41196. if (parsedGeometry.uvs) {
  41197. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  41198. }
  41199. if (parsedGeometry.uvs2) {
  41200. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  41201. }
  41202. if (parsedGeometry.uvs3) {
  41203. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  41204. }
  41205. if (parsedGeometry.uvs4) {
  41206. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  41207. }
  41208. if (parsedGeometry.uvs5) {
  41209. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  41210. }
  41211. if (parsedGeometry.uvs6) {
  41212. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  41213. }
  41214. if (parsedGeometry.colors) {
  41215. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  41216. }
  41217. if (parsedGeometry.matricesIndices) {
  41218. if (!parsedGeometry.matricesIndices._isExpanded) {
  41219. var floatIndices = [];
  41220. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  41221. var matricesIndex = parsedGeometry.matricesIndices[i];
  41222. floatIndices.push(matricesIndex & 0x000000FF);
  41223. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  41224. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  41225. floatIndices.push(matricesIndex >> 24);
  41226. }
  41227. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  41228. }
  41229. else {
  41230. delete parsedGeometry.matricesIndices._isExpanded;
  41231. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  41232. }
  41233. }
  41234. if (parsedGeometry.matricesIndicesExtra) {
  41235. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  41236. var floatIndices = [];
  41237. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  41238. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  41239. floatIndices.push(matricesIndex & 0x000000FF);
  41240. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  41241. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  41242. floatIndices.push(matricesIndex >> 24);
  41243. }
  41244. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  41245. }
  41246. else {
  41247. delete parsedGeometry.matricesIndices._isExpanded;
  41248. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  41249. }
  41250. }
  41251. if (parsedGeometry.matricesWeights) {
  41252. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  41253. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  41254. }
  41255. if (parsedGeometry.matricesWeightsExtra) {
  41256. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  41257. }
  41258. mesh.setIndices(parsedGeometry.indices, null);
  41259. }
  41260. // SubMeshes
  41261. if (parsedGeometry.subMeshes) {
  41262. mesh.subMeshes = [];
  41263. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  41264. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  41265. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  41266. }
  41267. }
  41268. // Flat shading
  41269. if (mesh._shouldGenerateFlatShading) {
  41270. mesh.convertToFlatShadedMesh();
  41271. delete mesh._shouldGenerateFlatShading;
  41272. }
  41273. // Update
  41274. mesh.computeWorldMatrix(true);
  41275. scene.onMeshImportedObservable.notifyObservers(mesh);
  41276. };
  41277. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  41278. var epsilon = 1e-3;
  41279. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  41280. return;
  41281. }
  41282. var noInfluenceBoneIndex = 0.0;
  41283. if (parsedGeometry.skeletonId > -1) {
  41284. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  41285. if (!skeleton) {
  41286. return;
  41287. }
  41288. noInfluenceBoneIndex = skeleton.bones.length;
  41289. }
  41290. else {
  41291. return;
  41292. }
  41293. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  41294. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41295. var matricesWeights = parsedGeometry.matricesWeights;
  41296. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  41297. var influencers = parsedGeometry.numBoneInfluencer;
  41298. var size = matricesWeights.length;
  41299. for (var i = 0; i < size; i += 4) {
  41300. var weight = 0.0;
  41301. var firstZeroWeight = -1;
  41302. for (var j = 0; j < 4; j++) {
  41303. var w = matricesWeights[i + j];
  41304. weight += w;
  41305. if (w < epsilon && firstZeroWeight < 0) {
  41306. firstZeroWeight = j;
  41307. }
  41308. }
  41309. if (matricesWeightsExtra) {
  41310. for (var j = 0; j < 4; j++) {
  41311. var w = matricesWeightsExtra[i + j];
  41312. weight += w;
  41313. if (w < epsilon && firstZeroWeight < 0) {
  41314. firstZeroWeight = j + 4;
  41315. }
  41316. }
  41317. }
  41318. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  41319. firstZeroWeight = influencers - 1;
  41320. }
  41321. if (weight > epsilon) {
  41322. var mweight = 1.0 / weight;
  41323. for (var j = 0; j < 4; j++) {
  41324. matricesWeights[i + j] *= mweight;
  41325. }
  41326. if (matricesWeightsExtra) {
  41327. for (var j = 0; j < 4; j++) {
  41328. matricesWeightsExtra[i + j] *= mweight;
  41329. }
  41330. }
  41331. }
  41332. else {
  41333. if (firstZeroWeight >= 4) {
  41334. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  41335. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  41336. }
  41337. else {
  41338. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  41339. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  41340. }
  41341. }
  41342. }
  41343. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  41344. if (parsedGeometry.matricesWeightsExtra) {
  41345. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  41346. }
  41347. };
  41348. /**
  41349. * Create a new geometry from persisted data (Using .babylon file format)
  41350. * @param parsedVertexData defines the persisted data
  41351. * @param scene defines the hosting scene
  41352. * @param rootUrl defines the root url to use to load assets (like delayed data)
  41353. * @returns the new geometry object
  41354. */
  41355. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  41356. if (scene.getGeometryByID(parsedVertexData.id)) {
  41357. return null; // null since geometry could be something else than a box...
  41358. }
  41359. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  41360. if (BABYLON.Tags) {
  41361. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  41362. }
  41363. if (parsedVertexData.delayLoadingFile) {
  41364. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41365. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  41366. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  41367. geometry._delayInfo = [];
  41368. if (parsedVertexData.hasUVs) {
  41369. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  41370. }
  41371. if (parsedVertexData.hasUVs2) {
  41372. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  41373. }
  41374. if (parsedVertexData.hasUVs3) {
  41375. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  41376. }
  41377. if (parsedVertexData.hasUVs4) {
  41378. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  41379. }
  41380. if (parsedVertexData.hasUVs5) {
  41381. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  41382. }
  41383. if (parsedVertexData.hasUVs6) {
  41384. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  41385. }
  41386. if (parsedVertexData.hasColors) {
  41387. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  41388. }
  41389. if (parsedVertexData.hasMatricesIndices) {
  41390. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41391. }
  41392. if (parsedVertexData.hasMatricesWeights) {
  41393. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41394. }
  41395. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  41396. }
  41397. else {
  41398. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  41399. }
  41400. scene.pushGeometry(geometry, true);
  41401. return geometry;
  41402. };
  41403. return Geometry;
  41404. }());
  41405. BABYLON.Geometry = Geometry;
  41406. // Primitives
  41407. /// Abstract class
  41408. /**
  41409. * Abstract class used to provide common services for all typed geometries
  41410. * @hidden
  41411. */
  41412. var _PrimitiveGeometry = /** @class */ (function (_super) {
  41413. __extends(_PrimitiveGeometry, _super);
  41414. /**
  41415. * Creates a new typed geometry
  41416. * @param id defines the unique ID of the geometry
  41417. * @param scene defines the hosting scene
  41418. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41419. * @param mesh defines the hosting mesh (can be null)
  41420. */
  41421. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  41422. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  41423. if (mesh === void 0) { mesh = null; }
  41424. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  41425. _this._canBeRegenerated = _canBeRegenerated;
  41426. _this._beingRegenerated = true;
  41427. _this.regenerate();
  41428. _this._beingRegenerated = false;
  41429. return _this;
  41430. }
  41431. /**
  41432. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  41433. * @returns true if the geometry can be regenerated
  41434. */
  41435. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  41436. return this._canBeRegenerated;
  41437. };
  41438. /**
  41439. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  41440. */
  41441. _PrimitiveGeometry.prototype.regenerate = function () {
  41442. if (!this._canBeRegenerated) {
  41443. return;
  41444. }
  41445. this._beingRegenerated = true;
  41446. this.setAllVerticesData(this._regenerateVertexData(), false);
  41447. this._beingRegenerated = false;
  41448. };
  41449. /**
  41450. * Clone the geometry
  41451. * @param id defines the unique ID of the new geometry
  41452. * @returns the new geometry
  41453. */
  41454. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  41455. return _super.prototype.copy.call(this, id);
  41456. };
  41457. // overrides
  41458. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  41459. if (!this._beingRegenerated) {
  41460. return;
  41461. }
  41462. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  41463. };
  41464. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  41465. if (!this._beingRegenerated) {
  41466. return;
  41467. }
  41468. _super.prototype.setVerticesData.call(this, kind, data, false);
  41469. };
  41470. // to override
  41471. /** @hidden */
  41472. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  41473. throw new Error("Abstract method");
  41474. };
  41475. _PrimitiveGeometry.prototype.copy = function (id) {
  41476. throw new Error("Must be overriden in sub-classes.");
  41477. };
  41478. _PrimitiveGeometry.prototype.serialize = function () {
  41479. var serializationObject = _super.prototype.serialize.call(this);
  41480. serializationObject.canBeRegenerated = this.canBeRegenerated();
  41481. return serializationObject;
  41482. };
  41483. return _PrimitiveGeometry;
  41484. }(Geometry));
  41485. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  41486. /**
  41487. * Creates a ribbon geometry
  41488. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  41489. */
  41490. var RibbonGeometry = /** @class */ (function (_super) {
  41491. __extends(RibbonGeometry, _super);
  41492. /**
  41493. * Creates a ribbon geometry
  41494. * @param id defines the unique ID of the geometry
  41495. * @param scene defines the hosting scene
  41496. * @param pathArray defines the array of paths to use
  41497. * @param closeArray defines if the last path and the first path must be joined
  41498. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  41499. * @param offset defines the offset between points
  41500. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41501. * @param mesh defines the hosting mesh (can be null)
  41502. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41503. */
  41504. function RibbonGeometry(id, scene,
  41505. /**
  41506. * Defines the array of paths to use
  41507. */
  41508. pathArray,
  41509. /**
  41510. * Defines if the last and first points of each path in your pathArray must be joined
  41511. */
  41512. closeArray,
  41513. /**
  41514. * Defines if the last and first points of each path in your pathArray must be joined
  41515. */
  41516. closePath,
  41517. /**
  41518. * Defines the offset between points
  41519. */
  41520. offset, canBeRegenerated, mesh,
  41521. /**
  41522. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41523. */
  41524. side) {
  41525. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41526. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41527. _this.pathArray = pathArray;
  41528. _this.closeArray = closeArray;
  41529. _this.closePath = closePath;
  41530. _this.offset = offset;
  41531. _this.side = side;
  41532. return _this;
  41533. }
  41534. /** @hidden */
  41535. RibbonGeometry.prototype._regenerateVertexData = function () {
  41536. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  41537. };
  41538. RibbonGeometry.prototype.copy = function (id) {
  41539. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  41540. };
  41541. return RibbonGeometry;
  41542. }(_PrimitiveGeometry));
  41543. BABYLON.RibbonGeometry = RibbonGeometry;
  41544. /**
  41545. * Creates a box geometry
  41546. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  41547. */
  41548. var BoxGeometry = /** @class */ (function (_super) {
  41549. __extends(BoxGeometry, _super);
  41550. /**
  41551. * Creates a box geometry
  41552. * @param id defines the unique ID of the geometry
  41553. * @param scene defines the hosting scene
  41554. * @param size defines the zise of the box (width, height and depth are the same)
  41555. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41556. * @param mesh defines the hosting mesh (can be null)
  41557. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41558. */
  41559. function BoxGeometry(id, scene,
  41560. /**
  41561. * Defines the zise of the box (width, height and depth are the same)
  41562. */
  41563. size, canBeRegenerated, mesh,
  41564. /**
  41565. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41566. */
  41567. side) {
  41568. if (mesh === void 0) { mesh = null; }
  41569. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41570. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41571. _this.size = size;
  41572. _this.side = side;
  41573. return _this;
  41574. }
  41575. /** @hidden */
  41576. BoxGeometry.prototype._regenerateVertexData = function () {
  41577. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  41578. };
  41579. BoxGeometry.prototype.copy = function (id) {
  41580. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  41581. };
  41582. BoxGeometry.prototype.serialize = function () {
  41583. var serializationObject = _super.prototype.serialize.call(this);
  41584. serializationObject.size = this.size;
  41585. return serializationObject;
  41586. };
  41587. BoxGeometry.Parse = function (parsedBox, scene) {
  41588. if (scene.getGeometryByID(parsedBox.id)) {
  41589. return null; // null since geometry could be something else than a box...
  41590. }
  41591. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  41592. if (BABYLON.Tags) {
  41593. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  41594. }
  41595. scene.pushGeometry(box, true);
  41596. return box;
  41597. };
  41598. return BoxGeometry;
  41599. }(_PrimitiveGeometry));
  41600. BABYLON.BoxGeometry = BoxGeometry;
  41601. /**
  41602. * Creates a sphere geometry
  41603. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  41604. */
  41605. var SphereGeometry = /** @class */ (function (_super) {
  41606. __extends(SphereGeometry, _super);
  41607. /**
  41608. * Create a new sphere geometry
  41609. * @param id defines the unique ID of the geometry
  41610. * @param scene defines the hosting scene
  41611. * @param segments defines the number of segments to use to create the sphere
  41612. * @param diameter defines the diameter of the sphere
  41613. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41614. * @param mesh defines the hosting mesh (can be null)
  41615. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41616. */
  41617. function SphereGeometry(id, scene,
  41618. /**
  41619. * Defines the number of segments to use to create the sphere
  41620. */
  41621. segments,
  41622. /**
  41623. * Defines the diameter of the sphere
  41624. */
  41625. diameter, canBeRegenerated, mesh,
  41626. /**
  41627. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41628. */
  41629. side) {
  41630. if (mesh === void 0) { mesh = null; }
  41631. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41632. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41633. _this.segments = segments;
  41634. _this.diameter = diameter;
  41635. _this.side = side;
  41636. return _this;
  41637. }
  41638. /** @hidden */
  41639. SphereGeometry.prototype._regenerateVertexData = function () {
  41640. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  41641. };
  41642. SphereGeometry.prototype.copy = function (id) {
  41643. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  41644. };
  41645. SphereGeometry.prototype.serialize = function () {
  41646. var serializationObject = _super.prototype.serialize.call(this);
  41647. serializationObject.segments = this.segments;
  41648. serializationObject.diameter = this.diameter;
  41649. return serializationObject;
  41650. };
  41651. SphereGeometry.Parse = function (parsedSphere, scene) {
  41652. if (scene.getGeometryByID(parsedSphere.id)) {
  41653. return null; // null since geometry could be something else than a sphere...
  41654. }
  41655. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  41656. if (BABYLON.Tags) {
  41657. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  41658. }
  41659. scene.pushGeometry(sphere, true);
  41660. return sphere;
  41661. };
  41662. return SphereGeometry;
  41663. }(_PrimitiveGeometry));
  41664. BABYLON.SphereGeometry = SphereGeometry;
  41665. /**
  41666. * Creates a disc geometry
  41667. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  41668. */
  41669. var DiscGeometry = /** @class */ (function (_super) {
  41670. __extends(DiscGeometry, _super);
  41671. /**
  41672. * Creates a new disc geometry
  41673. * @param id defines the unique ID of the geometry
  41674. * @param scene defines the hosting scene
  41675. * @param radius defines the radius of the disc
  41676. * @param tessellation defines the tesselation factor to apply to the disc
  41677. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41678. * @param mesh defines the hosting mesh (can be null)
  41679. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41680. */
  41681. function DiscGeometry(id, scene,
  41682. /**
  41683. * Defines the radius of the disc
  41684. */
  41685. radius,
  41686. /**
  41687. * Defines the tesselation factor to apply to the disc
  41688. */
  41689. tessellation, canBeRegenerated, mesh,
  41690. /**
  41691. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41692. */
  41693. side) {
  41694. if (mesh === void 0) { mesh = null; }
  41695. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41696. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41697. _this.radius = radius;
  41698. _this.tessellation = tessellation;
  41699. _this.side = side;
  41700. return _this;
  41701. }
  41702. /** @hidden */
  41703. DiscGeometry.prototype._regenerateVertexData = function () {
  41704. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  41705. };
  41706. DiscGeometry.prototype.copy = function (id) {
  41707. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  41708. };
  41709. return DiscGeometry;
  41710. }(_PrimitiveGeometry));
  41711. BABYLON.DiscGeometry = DiscGeometry;
  41712. /**
  41713. * Creates a new cylinder geometry
  41714. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  41715. */
  41716. var CylinderGeometry = /** @class */ (function (_super) {
  41717. __extends(CylinderGeometry, _super);
  41718. /**
  41719. * Creates a new cylinder geometry
  41720. * @param id defines the unique ID of the geometry
  41721. * @param scene defines the hosting scene
  41722. * @param height defines the height of the cylinder
  41723. * @param diameterTop defines the diameter of the cylinder's top cap
  41724. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  41725. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  41726. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  41727. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41728. * @param mesh defines the hosting mesh (can be null)
  41729. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41730. */
  41731. function CylinderGeometry(id, scene,
  41732. /**
  41733. * Defines the height of the cylinder
  41734. */
  41735. height,
  41736. /**
  41737. * Defines the diameter of the cylinder's top cap
  41738. */
  41739. diameterTop,
  41740. /**
  41741. * Defines the diameter of the cylinder's bottom cap
  41742. */
  41743. diameterBottom,
  41744. /**
  41745. * Defines the tessellation factor to apply to the cylinder
  41746. */
  41747. tessellation,
  41748. /**
  41749. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  41750. */
  41751. subdivisions, canBeRegenerated, mesh,
  41752. /**
  41753. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41754. */
  41755. side) {
  41756. if (subdivisions === void 0) { subdivisions = 1; }
  41757. if (mesh === void 0) { mesh = null; }
  41758. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41759. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41760. _this.height = height;
  41761. _this.diameterTop = diameterTop;
  41762. _this.diameterBottom = diameterBottom;
  41763. _this.tessellation = tessellation;
  41764. _this.subdivisions = subdivisions;
  41765. _this.side = side;
  41766. return _this;
  41767. }
  41768. /** @hidden */
  41769. CylinderGeometry.prototype._regenerateVertexData = function () {
  41770. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  41771. };
  41772. CylinderGeometry.prototype.copy = function (id) {
  41773. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  41774. };
  41775. CylinderGeometry.prototype.serialize = function () {
  41776. var serializationObject = _super.prototype.serialize.call(this);
  41777. serializationObject.height = this.height;
  41778. serializationObject.diameterTop = this.diameterTop;
  41779. serializationObject.diameterBottom = this.diameterBottom;
  41780. serializationObject.tessellation = this.tessellation;
  41781. return serializationObject;
  41782. };
  41783. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  41784. if (scene.getGeometryByID(parsedCylinder.id)) {
  41785. return null; // null since geometry could be something else than a cylinder...
  41786. }
  41787. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  41788. if (BABYLON.Tags) {
  41789. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  41790. }
  41791. scene.pushGeometry(cylinder, true);
  41792. return cylinder;
  41793. };
  41794. return CylinderGeometry;
  41795. }(_PrimitiveGeometry));
  41796. BABYLON.CylinderGeometry = CylinderGeometry;
  41797. /**
  41798. * Creates a new torus geometry
  41799. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  41800. */
  41801. var TorusGeometry = /** @class */ (function (_super) {
  41802. __extends(TorusGeometry, _super);
  41803. /**
  41804. * Creates a new torus geometry
  41805. * @param id defines the unique ID of the geometry
  41806. * @param scene defines the hosting scene
  41807. * @param diameter defines the diameter of the torus
  41808. * @param thickness defines the thickness of the torus (ie. internal diameter)
  41809. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  41810. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41811. * @param mesh defines the hosting mesh (can be null)
  41812. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41813. */
  41814. function TorusGeometry(id, scene,
  41815. /**
  41816. * Defines the diameter of the torus
  41817. */
  41818. diameter,
  41819. /**
  41820. * Defines the thickness of the torus (ie. internal diameter)
  41821. */
  41822. thickness,
  41823. /**
  41824. * Defines the tesselation factor to apply to the torus
  41825. */
  41826. tessellation, canBeRegenerated, mesh,
  41827. /**
  41828. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41829. */
  41830. side) {
  41831. if (mesh === void 0) { mesh = null; }
  41832. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41833. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41834. _this.diameter = diameter;
  41835. _this.thickness = thickness;
  41836. _this.tessellation = tessellation;
  41837. _this.side = side;
  41838. return _this;
  41839. }
  41840. /** @hidden */
  41841. TorusGeometry.prototype._regenerateVertexData = function () {
  41842. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  41843. };
  41844. TorusGeometry.prototype.copy = function (id) {
  41845. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  41846. };
  41847. TorusGeometry.prototype.serialize = function () {
  41848. var serializationObject = _super.prototype.serialize.call(this);
  41849. serializationObject.diameter = this.diameter;
  41850. serializationObject.thickness = this.thickness;
  41851. serializationObject.tessellation = this.tessellation;
  41852. return serializationObject;
  41853. };
  41854. TorusGeometry.Parse = function (parsedTorus, scene) {
  41855. if (scene.getGeometryByID(parsedTorus.id)) {
  41856. return null; // null since geometry could be something else than a torus...
  41857. }
  41858. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  41859. if (BABYLON.Tags) {
  41860. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  41861. }
  41862. scene.pushGeometry(torus, true);
  41863. return torus;
  41864. };
  41865. return TorusGeometry;
  41866. }(_PrimitiveGeometry));
  41867. BABYLON.TorusGeometry = TorusGeometry;
  41868. /**
  41869. * Creates a new ground geometry
  41870. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  41871. */
  41872. var GroundGeometry = /** @class */ (function (_super) {
  41873. __extends(GroundGeometry, _super);
  41874. /**
  41875. * Creates a new ground geometry
  41876. * @param id defines the unique ID of the geometry
  41877. * @param scene defines the hosting scene
  41878. * @param width defines the width of the ground
  41879. * @param height defines the height of the ground
  41880. * @param subdivisions defines the subdivisions to apply to the ground
  41881. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41882. * @param mesh defines the hosting mesh (can be null)
  41883. */
  41884. function GroundGeometry(id, scene,
  41885. /**
  41886. * Defines the width of the ground
  41887. */
  41888. width,
  41889. /**
  41890. * Defines the height of the ground
  41891. */
  41892. height,
  41893. /**
  41894. * Defines the subdivisions to apply to the ground
  41895. */
  41896. subdivisions, canBeRegenerated, mesh) {
  41897. if (mesh === void 0) { mesh = null; }
  41898. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41899. _this.width = width;
  41900. _this.height = height;
  41901. _this.subdivisions = subdivisions;
  41902. return _this;
  41903. }
  41904. /** @hidden */
  41905. GroundGeometry.prototype._regenerateVertexData = function () {
  41906. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  41907. };
  41908. GroundGeometry.prototype.copy = function (id) {
  41909. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  41910. };
  41911. GroundGeometry.prototype.serialize = function () {
  41912. var serializationObject = _super.prototype.serialize.call(this);
  41913. serializationObject.width = this.width;
  41914. serializationObject.height = this.height;
  41915. serializationObject.subdivisions = this.subdivisions;
  41916. return serializationObject;
  41917. };
  41918. GroundGeometry.Parse = function (parsedGround, scene) {
  41919. if (scene.getGeometryByID(parsedGround.id)) {
  41920. return null; // null since geometry could be something else than a ground...
  41921. }
  41922. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  41923. if (BABYLON.Tags) {
  41924. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  41925. }
  41926. scene.pushGeometry(ground, true);
  41927. return ground;
  41928. };
  41929. return GroundGeometry;
  41930. }(_PrimitiveGeometry));
  41931. BABYLON.GroundGeometry = GroundGeometry;
  41932. /**
  41933. * Creates a tiled ground geometry
  41934. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  41935. */
  41936. var TiledGroundGeometry = /** @class */ (function (_super) {
  41937. __extends(TiledGroundGeometry, _super);
  41938. /**
  41939. * Creates a tiled ground geometry
  41940. * @param id defines the unique ID of the geometry
  41941. * @param scene defines the hosting scene
  41942. * @param xmin defines the minimum value on X axis
  41943. * @param zmin defines the minimum value on Z axis
  41944. * @param xmax defines the maximum value on X axis
  41945. * @param zmax defines the maximum value on Z axis
  41946. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  41947. * @param precision defines the precision to use when computing the tiles
  41948. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41949. * @param mesh defines the hosting mesh (can be null)
  41950. */
  41951. function TiledGroundGeometry(id, scene,
  41952. /**
  41953. * Defines the minimum value on X axis
  41954. */
  41955. xmin,
  41956. /**
  41957. * Defines the minimum value on Z axis
  41958. */
  41959. zmin,
  41960. /**
  41961. * Defines the maximum value on X axis
  41962. */
  41963. xmax,
  41964. /**
  41965. * Defines the maximum value on Z axis
  41966. */
  41967. zmax,
  41968. /**
  41969. * Defines the subdivisions to apply to the ground
  41970. */
  41971. subdivisions,
  41972. /**
  41973. * Defines the precision to use when computing the tiles
  41974. */
  41975. precision, canBeRegenerated, mesh) {
  41976. if (mesh === void 0) { mesh = null; }
  41977. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41978. _this.xmin = xmin;
  41979. _this.zmin = zmin;
  41980. _this.xmax = xmax;
  41981. _this.zmax = zmax;
  41982. _this.subdivisions = subdivisions;
  41983. _this.precision = precision;
  41984. return _this;
  41985. }
  41986. /** @hidden */
  41987. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  41988. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  41989. };
  41990. TiledGroundGeometry.prototype.copy = function (id) {
  41991. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  41992. };
  41993. return TiledGroundGeometry;
  41994. }(_PrimitiveGeometry));
  41995. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  41996. /**
  41997. * Creates a plane geometry
  41998. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  41999. */
  42000. var PlaneGeometry = /** @class */ (function (_super) {
  42001. __extends(PlaneGeometry, _super);
  42002. /**
  42003. * Creates a plane geometry
  42004. * @param id defines the unique ID of the geometry
  42005. * @param scene defines the hosting scene
  42006. * @param size defines the size of the plane (width === height)
  42007. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42008. * @param mesh defines the hosting mesh (can be null)
  42009. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42010. */
  42011. function PlaneGeometry(id, scene,
  42012. /**
  42013. * Defines the size of the plane (width === height)
  42014. */
  42015. size, canBeRegenerated, mesh,
  42016. /**
  42017. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42018. */
  42019. side) {
  42020. if (mesh === void 0) { mesh = null; }
  42021. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42022. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42023. _this.size = size;
  42024. _this.side = side;
  42025. return _this;
  42026. }
  42027. /** @hidden */
  42028. PlaneGeometry.prototype._regenerateVertexData = function () {
  42029. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  42030. };
  42031. PlaneGeometry.prototype.copy = function (id) {
  42032. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  42033. };
  42034. PlaneGeometry.prototype.serialize = function () {
  42035. var serializationObject = _super.prototype.serialize.call(this);
  42036. serializationObject.size = this.size;
  42037. return serializationObject;
  42038. };
  42039. PlaneGeometry.Parse = function (parsedPlane, scene) {
  42040. if (scene.getGeometryByID(parsedPlane.id)) {
  42041. return null; // null since geometry could be something else than a ground...
  42042. }
  42043. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  42044. if (BABYLON.Tags) {
  42045. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  42046. }
  42047. scene.pushGeometry(plane, true);
  42048. return plane;
  42049. };
  42050. return PlaneGeometry;
  42051. }(_PrimitiveGeometry));
  42052. BABYLON.PlaneGeometry = PlaneGeometry;
  42053. /**
  42054. * Creates a torus knot geometry
  42055. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  42056. */
  42057. var TorusKnotGeometry = /** @class */ (function (_super) {
  42058. __extends(TorusKnotGeometry, _super);
  42059. /**
  42060. * Creates a torus knot geometry
  42061. * @param id defines the unique ID of the geometry
  42062. * @param scene defines the hosting scene
  42063. * @param radius defines the radius of the torus knot
  42064. * @param tube defines the thickness of the torus knot tube
  42065. * @param radialSegments defines the number of radial segments
  42066. * @param tubularSegments defines the number of tubular segments
  42067. * @param p defines the first number of windings
  42068. * @param q defines the second number of windings
  42069. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42070. * @param mesh defines the hosting mesh (can be null)
  42071. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42072. */
  42073. function TorusKnotGeometry(id, scene,
  42074. /**
  42075. * Defines the radius of the torus knot
  42076. */
  42077. radius,
  42078. /**
  42079. * Defines the thickness of the torus knot tube
  42080. */
  42081. tube,
  42082. /**
  42083. * Defines the number of radial segments
  42084. */
  42085. radialSegments,
  42086. /**
  42087. * Defines the number of tubular segments
  42088. */
  42089. tubularSegments,
  42090. /**
  42091. * Defines the first number of windings
  42092. */
  42093. p,
  42094. /**
  42095. * Defines the second number of windings
  42096. */
  42097. q, canBeRegenerated, mesh,
  42098. /**
  42099. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42100. */
  42101. side) {
  42102. if (mesh === void 0) { mesh = null; }
  42103. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42104. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42105. _this.radius = radius;
  42106. _this.tube = tube;
  42107. _this.radialSegments = radialSegments;
  42108. _this.tubularSegments = tubularSegments;
  42109. _this.p = p;
  42110. _this.q = q;
  42111. _this.side = side;
  42112. return _this;
  42113. }
  42114. /** @hidden */
  42115. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  42116. 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 });
  42117. };
  42118. TorusKnotGeometry.prototype.copy = function (id) {
  42119. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  42120. };
  42121. TorusKnotGeometry.prototype.serialize = function () {
  42122. var serializationObject = _super.prototype.serialize.call(this);
  42123. serializationObject.radius = this.radius;
  42124. serializationObject.tube = this.tube;
  42125. serializationObject.radialSegments = this.radialSegments;
  42126. serializationObject.tubularSegments = this.tubularSegments;
  42127. serializationObject.p = this.p;
  42128. serializationObject.q = this.q;
  42129. return serializationObject;
  42130. };
  42131. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  42132. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  42133. return null; // null since geometry could be something else than a ground...
  42134. }
  42135. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  42136. if (BABYLON.Tags) {
  42137. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  42138. }
  42139. scene.pushGeometry(torusKnot, true);
  42140. return torusKnot;
  42141. };
  42142. return TorusKnotGeometry;
  42143. }(_PrimitiveGeometry));
  42144. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  42145. //}
  42146. })(BABYLON || (BABYLON = {}));
  42147. //# sourceMappingURL=babylon.geometry.js.map
  42148. var BABYLON;
  42149. (function (BABYLON) {
  42150. /**
  42151. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  42152. */
  42153. var PerformanceMonitor = /** @class */ (function () {
  42154. /**
  42155. * constructor
  42156. * @param frameSampleSize The number of samples required to saturate the sliding window
  42157. */
  42158. function PerformanceMonitor(frameSampleSize) {
  42159. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  42160. this._enabled = true;
  42161. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  42162. }
  42163. /**
  42164. * Samples current frame
  42165. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  42166. */
  42167. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  42168. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  42169. if (!this._enabled) {
  42170. return;
  42171. }
  42172. if (this._lastFrameTimeMs != null) {
  42173. var dt = timeMs - this._lastFrameTimeMs;
  42174. this._rollingFrameTime.add(dt);
  42175. }
  42176. this._lastFrameTimeMs = timeMs;
  42177. };
  42178. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  42179. /**
  42180. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  42181. */
  42182. get: function () {
  42183. return this._rollingFrameTime.average;
  42184. },
  42185. enumerable: true,
  42186. configurable: true
  42187. });
  42188. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  42189. /**
  42190. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  42191. */
  42192. get: function () {
  42193. return this._rollingFrameTime.variance;
  42194. },
  42195. enumerable: true,
  42196. configurable: true
  42197. });
  42198. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  42199. /**
  42200. * Returns the frame time of the most recent frame
  42201. */
  42202. get: function () {
  42203. return this._rollingFrameTime.history(0);
  42204. },
  42205. enumerable: true,
  42206. configurable: true
  42207. });
  42208. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  42209. /**
  42210. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  42211. */
  42212. get: function () {
  42213. return 1000.0 / this._rollingFrameTime.average;
  42214. },
  42215. enumerable: true,
  42216. configurable: true
  42217. });
  42218. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  42219. /**
  42220. * Returns the average framerate in frames per second using the most recent frame time
  42221. */
  42222. get: function () {
  42223. var history = this._rollingFrameTime.history(0);
  42224. if (history === 0) {
  42225. return 0;
  42226. }
  42227. return 1000.0 / history;
  42228. },
  42229. enumerable: true,
  42230. configurable: true
  42231. });
  42232. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  42233. /**
  42234. * Returns true if enough samples have been taken to completely fill the sliding window
  42235. */
  42236. get: function () {
  42237. return this._rollingFrameTime.isSaturated();
  42238. },
  42239. enumerable: true,
  42240. configurable: true
  42241. });
  42242. /**
  42243. * Enables contributions to the sliding window sample set
  42244. */
  42245. PerformanceMonitor.prototype.enable = function () {
  42246. this._enabled = true;
  42247. };
  42248. /**
  42249. * Disables contributions to the sliding window sample set
  42250. * Samples will not be interpolated over the disabled period
  42251. */
  42252. PerformanceMonitor.prototype.disable = function () {
  42253. this._enabled = false;
  42254. //clear last sample to avoid interpolating over the disabled period when next enabled
  42255. this._lastFrameTimeMs = null;
  42256. };
  42257. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  42258. /**
  42259. * Returns true if sampling is enabled
  42260. */
  42261. get: function () {
  42262. return this._enabled;
  42263. },
  42264. enumerable: true,
  42265. configurable: true
  42266. });
  42267. /**
  42268. * Resets performance monitor
  42269. */
  42270. PerformanceMonitor.prototype.reset = function () {
  42271. //clear last sample to avoid interpolating over the disabled period when next enabled
  42272. this._lastFrameTimeMs = null;
  42273. //wipe record
  42274. this._rollingFrameTime.reset();
  42275. };
  42276. return PerformanceMonitor;
  42277. }());
  42278. BABYLON.PerformanceMonitor = PerformanceMonitor;
  42279. /**
  42280. * RollingAverage
  42281. *
  42282. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  42283. */
  42284. var RollingAverage = /** @class */ (function () {
  42285. /**
  42286. * constructor
  42287. * @param length The number of samples required to saturate the sliding window
  42288. */
  42289. function RollingAverage(length) {
  42290. this._samples = new Array(length);
  42291. this.reset();
  42292. }
  42293. /**
  42294. * Adds a sample to the sample set
  42295. * @param v The sample value
  42296. */
  42297. RollingAverage.prototype.add = function (v) {
  42298. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  42299. var delta;
  42300. //we need to check if we've already wrapped round
  42301. if (this.isSaturated()) {
  42302. //remove bottom of stack from mean
  42303. var bottomValue = this._samples[this._pos];
  42304. delta = bottomValue - this.average;
  42305. this.average -= delta / (this._sampleCount - 1);
  42306. this._m2 -= delta * (bottomValue - this.average);
  42307. }
  42308. else {
  42309. this._sampleCount++;
  42310. }
  42311. //add new value to mean
  42312. delta = v - this.average;
  42313. this.average += delta / (this._sampleCount);
  42314. this._m2 += delta * (v - this.average);
  42315. //set the new variance
  42316. this.variance = this._m2 / (this._sampleCount - 1);
  42317. this._samples[this._pos] = v;
  42318. this._pos++;
  42319. this._pos %= this._samples.length; //positive wrap around
  42320. };
  42321. /**
  42322. * Returns previously added values or null if outside of history or outside the sliding window domain
  42323. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  42324. * @return Value previously recorded with add() or null if outside of range
  42325. */
  42326. RollingAverage.prototype.history = function (i) {
  42327. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  42328. return 0;
  42329. }
  42330. var i0 = this._wrapPosition(this._pos - 1.0);
  42331. return this._samples[this._wrapPosition(i0 - i)];
  42332. };
  42333. /**
  42334. * Returns true if enough samples have been taken to completely fill the sliding window
  42335. * @return true if sample-set saturated
  42336. */
  42337. RollingAverage.prototype.isSaturated = function () {
  42338. return this._sampleCount >= this._samples.length;
  42339. };
  42340. /**
  42341. * Resets the rolling average (equivalent to 0 samples taken so far)
  42342. */
  42343. RollingAverage.prototype.reset = function () {
  42344. this.average = 0;
  42345. this.variance = 0;
  42346. this._sampleCount = 0;
  42347. this._pos = 0;
  42348. this._m2 = 0;
  42349. };
  42350. /**
  42351. * Wraps a value around the sample range boundaries
  42352. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  42353. * @return Wrapped position in sample range
  42354. */
  42355. RollingAverage.prototype._wrapPosition = function (i) {
  42356. var max = this._samples.length;
  42357. return ((i % max) + max) % max;
  42358. };
  42359. return RollingAverage;
  42360. }());
  42361. BABYLON.RollingAverage = RollingAverage;
  42362. })(BABYLON || (BABYLON = {}));
  42363. //# sourceMappingURL=babylon.performanceMonitor.js.map
  42364. var BABYLON;
  42365. (function (BABYLON) {
  42366. /**
  42367. * "Static Class" containing the most commonly used helper while dealing with material for
  42368. * rendering purpose.
  42369. *
  42370. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  42371. *
  42372. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  42373. */
  42374. var MaterialHelper = /** @class */ (function () {
  42375. function MaterialHelper() {
  42376. }
  42377. /**
  42378. * Bind the current view position to an effect.
  42379. * @param effect The effect to be bound
  42380. * @param scene The scene the eyes position is used from
  42381. */
  42382. MaterialHelper.BindEyePosition = function (effect, scene) {
  42383. if (scene._forcedViewPosition) {
  42384. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  42385. return;
  42386. }
  42387. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42388. };
  42389. /**
  42390. * Helps preparing the defines values about the UVs in used in the effect.
  42391. * UVs are shared as much as we can accross channels in the shaders.
  42392. * @param texture The texture we are preparing the UVs for
  42393. * @param defines The defines to update
  42394. * @param key The channel key "diffuse", "specular"... used in the shader
  42395. */
  42396. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  42397. defines._needUVs = true;
  42398. defines[key] = true;
  42399. if (texture.getTextureMatrix().isIdentity(true)) {
  42400. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  42401. if (texture.coordinatesIndex === 0) {
  42402. defines["MAINUV1"] = true;
  42403. }
  42404. else {
  42405. defines["MAINUV2"] = true;
  42406. }
  42407. }
  42408. else {
  42409. defines[key + "DIRECTUV"] = 0;
  42410. }
  42411. };
  42412. /**
  42413. * Binds a texture matrix value to its corrsponding uniform
  42414. * @param texture The texture to bind the matrix for
  42415. * @param uniformBuffer The uniform buffer receivin the data
  42416. * @param key The channel key "diffuse", "specular"... used in the shader
  42417. */
  42418. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  42419. var matrix = texture.getTextureMatrix();
  42420. if (!matrix.isIdentity(true)) {
  42421. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  42422. }
  42423. };
  42424. /**
  42425. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  42426. * @param mesh defines the current mesh
  42427. * @param scene defines the current scene
  42428. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  42429. * @param pointsCloud defines if point cloud rendering has to be turned on
  42430. * @param fogEnabled defines if fog has to be turned on
  42431. * @param alphaTest defines if alpha testing has to be turned on
  42432. * @param defines defines the current list of defines
  42433. */
  42434. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  42435. if (defines._areMiscDirty) {
  42436. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  42437. defines["POINTSIZE"] = pointsCloud;
  42438. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  42439. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  42440. defines["ALPHATEST"] = alphaTest;
  42441. }
  42442. };
  42443. /**
  42444. * Helper used to prepare the list of defines associated with frame values for shader compilation
  42445. * @param scene defines the current scene
  42446. * @param engine defines the current engine
  42447. * @param defines specifies the list of active defines
  42448. * @param useInstances defines if instances have to be turned on
  42449. * @param useClipPlane defines if clip plane have to be turned on
  42450. */
  42451. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  42452. if (useClipPlane === void 0) { useClipPlane = null; }
  42453. var changed = false;
  42454. var useClipPlane1 = false;
  42455. var useClipPlane2 = false;
  42456. var useClipPlane3 = false;
  42457. var useClipPlane4 = false;
  42458. useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane;
  42459. useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane;
  42460. useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane;
  42461. useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane;
  42462. if (defines["CLIPPLANE"] !== useClipPlane1) {
  42463. defines["CLIPPLANE"] = useClipPlane1;
  42464. changed = true;
  42465. }
  42466. if (defines["CLIPPLANE2"] !== useClipPlane2) {
  42467. defines["CLIPPLANE2"] = useClipPlane2;
  42468. changed = true;
  42469. }
  42470. if (defines["CLIPPLANE3"] !== useClipPlane3) {
  42471. defines["CLIPPLANE3"] = useClipPlane3;
  42472. changed = true;
  42473. }
  42474. if (defines["CLIPPLANE4"] !== useClipPlane4) {
  42475. defines["CLIPPLANE4"] = useClipPlane4;
  42476. changed = true;
  42477. }
  42478. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  42479. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  42480. changed = true;
  42481. }
  42482. if (defines["INSTANCES"] !== useInstances) {
  42483. defines["INSTANCES"] = useInstances;
  42484. changed = true;
  42485. }
  42486. if (changed) {
  42487. defines.markAsUnprocessed();
  42488. }
  42489. };
  42490. /**
  42491. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  42492. * @param mesh The mesh containing the geometry data we will draw
  42493. * @param defines The defines to update
  42494. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  42495. * @param useBones Precise whether bones should be used or not (override mesh info)
  42496. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  42497. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  42498. * @returns false if defines are considered not dirty and have not been checked
  42499. */
  42500. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  42501. if (useMorphTargets === void 0) { useMorphTargets = false; }
  42502. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  42503. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  42504. return false;
  42505. }
  42506. defines._normals = defines._needNormals;
  42507. defines._uvs = defines._needUVs;
  42508. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  42509. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  42510. defines["TANGENT"] = true;
  42511. }
  42512. if (defines._needUVs) {
  42513. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  42514. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  42515. }
  42516. else {
  42517. defines["UV1"] = false;
  42518. defines["UV2"] = false;
  42519. }
  42520. if (useVertexColor) {
  42521. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  42522. defines["VERTEXCOLOR"] = hasVertexColors;
  42523. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  42524. }
  42525. if (useBones) {
  42526. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42527. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  42528. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  42529. }
  42530. else {
  42531. defines["NUM_BONE_INFLUENCERS"] = 0;
  42532. defines["BonesPerMesh"] = 0;
  42533. }
  42534. }
  42535. if (useMorphTargets) {
  42536. var manager = mesh.morphTargetManager;
  42537. if (manager) {
  42538. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  42539. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  42540. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  42541. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  42542. }
  42543. else {
  42544. defines["MORPHTARGETS_TANGENT"] = false;
  42545. defines["MORPHTARGETS_NORMAL"] = false;
  42546. defines["MORPHTARGETS"] = false;
  42547. defines["NUM_MORPH_INFLUENCERS"] = 0;
  42548. }
  42549. }
  42550. return true;
  42551. };
  42552. /**
  42553. * Prepares the defines related to the light information passed in parameter
  42554. * @param scene The scene we are intending to draw
  42555. * @param mesh The mesh the effect is compiling for
  42556. * @param defines The defines to update
  42557. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  42558. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  42559. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  42560. * @returns true if normals will be required for the rest of the effect
  42561. */
  42562. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  42563. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42564. if (disableLighting === void 0) { disableLighting = false; }
  42565. if (!defines._areLightsDirty) {
  42566. return defines._needNormals;
  42567. }
  42568. var lightIndex = 0;
  42569. var needNormals = false;
  42570. var needRebuild = false;
  42571. var lightmapMode = false;
  42572. var shadowEnabled = false;
  42573. var specularEnabled = false;
  42574. if (scene.lightsEnabled && !disableLighting) {
  42575. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  42576. var light = _a[_i];
  42577. needNormals = true;
  42578. if (defines["LIGHT" + lightIndex] === undefined) {
  42579. needRebuild = true;
  42580. }
  42581. defines["LIGHT" + lightIndex] = true;
  42582. defines["SPOTLIGHT" + lightIndex] = false;
  42583. defines["HEMILIGHT" + lightIndex] = false;
  42584. defines["POINTLIGHT" + lightIndex] = false;
  42585. defines["DIRLIGHT" + lightIndex] = false;
  42586. light.prepareLightSpecificDefines(defines, lightIndex);
  42587. // FallOff.
  42588. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  42589. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  42590. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  42591. switch (light.falloffType) {
  42592. case BABYLON.Light.FALLOFF_GLTF:
  42593. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  42594. break;
  42595. case BABYLON.Light.FALLOFF_PHYSICAL:
  42596. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  42597. break;
  42598. case BABYLON.Light.FALLOFF_STANDARD:
  42599. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  42600. break;
  42601. }
  42602. // Specular
  42603. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  42604. specularEnabled = true;
  42605. }
  42606. // Shadows
  42607. defines["SHADOW" + lightIndex] = false;
  42608. defines["SHADOWPCF" + lightIndex] = false;
  42609. defines["SHADOWPCSS" + lightIndex] = false;
  42610. defines["SHADOWPOISSON" + lightIndex] = false;
  42611. defines["SHADOWESM" + lightIndex] = false;
  42612. defines["SHADOWCUBE" + lightIndex] = false;
  42613. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  42614. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  42615. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  42616. var shadowGenerator = light.getShadowGenerator();
  42617. if (shadowGenerator) {
  42618. var shadowMap = shadowGenerator.getShadowMap();
  42619. if (shadowMap) {
  42620. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  42621. shadowEnabled = true;
  42622. shadowGenerator.prepareDefines(defines, lightIndex);
  42623. }
  42624. }
  42625. }
  42626. }
  42627. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  42628. lightmapMode = true;
  42629. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  42630. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  42631. }
  42632. else {
  42633. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  42634. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  42635. }
  42636. lightIndex++;
  42637. if (lightIndex === maxSimultaneousLights) {
  42638. break;
  42639. }
  42640. }
  42641. }
  42642. defines["SPECULARTERM"] = specularEnabled;
  42643. defines["SHADOWS"] = shadowEnabled;
  42644. // Resetting all other lights if any
  42645. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  42646. if (defines["LIGHT" + index] !== undefined) {
  42647. defines["LIGHT" + index] = false;
  42648. defines["HEMILIGHT" + lightIndex] = false;
  42649. defines["POINTLIGHT" + lightIndex] = false;
  42650. defines["DIRLIGHT" + lightIndex] = false;
  42651. defines["SPOTLIGHT" + lightIndex] = false;
  42652. defines["SHADOW" + lightIndex] = false;
  42653. }
  42654. }
  42655. var caps = scene.getEngine().getCaps();
  42656. if (defines["SHADOWFLOAT"] === undefined) {
  42657. needRebuild = true;
  42658. }
  42659. defines["SHADOWFLOAT"] = shadowEnabled &&
  42660. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42661. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42662. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42663. if (needRebuild) {
  42664. defines.rebuild();
  42665. }
  42666. return needNormals;
  42667. };
  42668. /**
  42669. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42670. * that won t be acctive due to defines being turned off.
  42671. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42672. * @param samplersList The samplers list
  42673. * @param defines The defines helping in the list generation
  42674. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42675. */
  42676. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42677. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42678. var uniformsList;
  42679. var uniformBuffersList = null;
  42680. if (uniformsListOrOptions.uniformsNames) {
  42681. var options = uniformsListOrOptions;
  42682. uniformsList = options.uniformsNames;
  42683. uniformBuffersList = options.uniformBuffersNames;
  42684. samplersList = options.samplers;
  42685. defines = options.defines;
  42686. maxSimultaneousLights = options.maxSimultaneousLights;
  42687. }
  42688. else {
  42689. uniformsList = uniformsListOrOptions;
  42690. if (!samplersList) {
  42691. samplersList = [];
  42692. }
  42693. }
  42694. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42695. if (!defines["LIGHT" + lightIndex]) {
  42696. break;
  42697. }
  42698. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42699. if (uniformBuffersList) {
  42700. uniformBuffersList.push("Light" + lightIndex);
  42701. }
  42702. samplersList.push("shadowSampler" + lightIndex);
  42703. samplersList.push("depthSampler" + lightIndex);
  42704. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42705. samplersList.push("projectionLightSampler" + lightIndex);
  42706. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42707. }
  42708. }
  42709. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42710. uniformsList.push("morphTargetInfluences");
  42711. }
  42712. };
  42713. /**
  42714. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42715. * @param defines The defines to update while falling back
  42716. * @param fallbacks The authorized effect fallbacks
  42717. * @param maxSimultaneousLights The maximum number of lights allowed
  42718. * @param rank the current rank of the Effect
  42719. * @returns The newly affected rank
  42720. */
  42721. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42722. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42723. if (rank === void 0) { rank = 0; }
  42724. var lightFallbackRank = 0;
  42725. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42726. if (!defines["LIGHT" + lightIndex]) {
  42727. break;
  42728. }
  42729. if (lightIndex > 0) {
  42730. lightFallbackRank = rank + lightIndex;
  42731. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42732. }
  42733. if (!defines["SHADOWS"]) {
  42734. if (defines["SHADOW" + lightIndex]) {
  42735. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42736. }
  42737. if (defines["SHADOWPCF" + lightIndex]) {
  42738. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42739. }
  42740. if (defines["SHADOWPCSS" + lightIndex]) {
  42741. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42742. }
  42743. if (defines["SHADOWPOISSON" + lightIndex]) {
  42744. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42745. }
  42746. if (defines["SHADOWESM" + lightIndex]) {
  42747. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  42748. }
  42749. }
  42750. }
  42751. return lightFallbackRank++;
  42752. };
  42753. /**
  42754. * Prepares the list of attributes required for morph targets according to the effect defines.
  42755. * @param attribs The current list of supported attribs
  42756. * @param mesh The mesh to prepare the morph targets attributes for
  42757. * @param defines The current Defines of the effect
  42758. */
  42759. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42760. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42761. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42762. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42763. var manager = mesh.morphTargetManager;
  42764. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42765. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42766. for (var index = 0; index < influencers; index++) {
  42767. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42768. if (normal) {
  42769. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42770. }
  42771. if (tangent) {
  42772. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42773. }
  42774. if (attribs.length > maxAttributesCount) {
  42775. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42776. }
  42777. }
  42778. }
  42779. };
  42780. /**
  42781. * Prepares the list of attributes required for bones according to the effect defines.
  42782. * @param attribs The current list of supported attribs
  42783. * @param mesh The mesh to prepare the bones attributes for
  42784. * @param defines The current Defines of the effect
  42785. * @param fallbacks The current efffect fallback strategy
  42786. */
  42787. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42788. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42789. fallbacks.addCPUSkinningFallback(0, mesh);
  42790. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42791. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42792. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  42793. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42794. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42795. }
  42796. }
  42797. };
  42798. /**
  42799. * Prepares the list of attributes required for instances according to the effect defines.
  42800. * @param attribs The current list of supported attribs
  42801. * @param defines The current Defines of the effect
  42802. */
  42803. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  42804. if (defines["INSTANCES"]) {
  42805. attribs.push("world0");
  42806. attribs.push("world1");
  42807. attribs.push("world2");
  42808. attribs.push("world3");
  42809. }
  42810. };
  42811. /**
  42812. * Binds the light shadow information to the effect for the given mesh.
  42813. * @param light The light containing the generator
  42814. * @param scene The scene the lights belongs to
  42815. * @param mesh The mesh we are binding the information to render
  42816. * @param lightIndex The light index in the effect used to render the mesh
  42817. * @param effect The effect we are binding the data to
  42818. */
  42819. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  42820. if (light.shadowEnabled && mesh.receiveShadows) {
  42821. var shadowGenerator = light.getShadowGenerator();
  42822. if (shadowGenerator) {
  42823. shadowGenerator.bindShadowLight(lightIndex, effect);
  42824. }
  42825. }
  42826. };
  42827. /**
  42828. * Binds the light information to the effect.
  42829. * @param light The light containing the generator
  42830. * @param effect The effect we are binding the data to
  42831. * @param lightIndex The light index in the effect used to render
  42832. */
  42833. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  42834. light.transferToEffect(effect, lightIndex + "");
  42835. };
  42836. /**
  42837. * Binds the lights information from the scene to the effect for the given mesh.
  42838. * @param scene The scene the lights belongs to
  42839. * @param mesh The mesh we are binding the information to render
  42840. * @param effect The effect we are binding the data to
  42841. * @param defines The generated defines for the effect
  42842. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  42843. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  42844. */
  42845. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  42846. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42847. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  42848. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  42849. for (var i = 0; i < len; i++) {
  42850. var light = mesh._lightSources[i];
  42851. var iAsString = i.toString();
  42852. var scaledIntensity = light.getScaledIntensity();
  42853. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  42854. MaterialHelper.BindLightProperties(light, effect, i);
  42855. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  42856. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  42857. if (defines["SPECULARTERM"]) {
  42858. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  42859. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  42860. }
  42861. // Shadows
  42862. if (scene.shadowsEnabled) {
  42863. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  42864. }
  42865. light._uniformBuffer.update();
  42866. }
  42867. };
  42868. /**
  42869. * Binds the fog information from the scene to the effect for the given mesh.
  42870. * @param scene The scene the lights belongs to
  42871. * @param mesh The mesh we are binding the information to render
  42872. * @param effect The effect we are binding the data to
  42873. * @param linearSpace Defines if the fog effect is applied in linear space
  42874. */
  42875. MaterialHelper.BindFogParameters = function (scene, mesh, effect, linearSpace) {
  42876. if (linearSpace === void 0) { linearSpace = false; }
  42877. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  42878. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  42879. // Convert fog color to linear space if used in a linear space computed shader.
  42880. if (linearSpace) {
  42881. scene.fogColor.toLinearSpaceToRef(this._tempFogColor);
  42882. effect.setColor3("vFogColor", this._tempFogColor);
  42883. }
  42884. else {
  42885. effect.setColor3("vFogColor", scene.fogColor);
  42886. }
  42887. }
  42888. };
  42889. /**
  42890. * Binds the bones information from the mesh to the effect.
  42891. * @param mesh The mesh we are binding the information to render
  42892. * @param effect The effect we are binding the data to
  42893. */
  42894. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  42895. if (!effect || !mesh) {
  42896. return;
  42897. }
  42898. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  42899. mesh.computeBonesUsingShaders = false;
  42900. }
  42901. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42902. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  42903. if (matrices) {
  42904. effect.setMatrices("mBones", matrices);
  42905. }
  42906. }
  42907. };
  42908. /**
  42909. * Binds the morph targets information from the mesh to the effect.
  42910. * @param abstractMesh The mesh we are binding the information to render
  42911. * @param effect The effect we are binding the data to
  42912. */
  42913. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  42914. var manager = abstractMesh.morphTargetManager;
  42915. if (!abstractMesh || !manager) {
  42916. return;
  42917. }
  42918. effect.setFloatArray("morphTargetInfluences", manager.influences);
  42919. };
  42920. /**
  42921. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  42922. * @param defines The generated defines used in the effect
  42923. * @param effect The effect we are binding the data to
  42924. * @param scene The scene we are willing to render with logarithmic scale for
  42925. */
  42926. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  42927. if (defines["LOGARITHMICDEPTH"]) {
  42928. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  42929. }
  42930. };
  42931. /**
  42932. * Binds the clip plane information from the scene to the effect.
  42933. * @param scene The scene the clip plane information are extracted from
  42934. * @param effect The effect we are binding the data to
  42935. */
  42936. MaterialHelper.BindClipPlane = function (effect, scene) {
  42937. if (scene.clipPlane) {
  42938. var clipPlane = scene.clipPlane;
  42939. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42940. }
  42941. if (scene.clipPlane2) {
  42942. var clipPlane = scene.clipPlane2;
  42943. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42944. }
  42945. if (scene.clipPlane3) {
  42946. var clipPlane = scene.clipPlane3;
  42947. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42948. }
  42949. if (scene.clipPlane4) {
  42950. var clipPlane = scene.clipPlane4;
  42951. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42952. }
  42953. };
  42954. MaterialHelper._tempFogColor = BABYLON.Color3.Black();
  42955. return MaterialHelper;
  42956. }());
  42957. BABYLON.MaterialHelper = MaterialHelper;
  42958. })(BABYLON || (BABYLON = {}));
  42959. //# sourceMappingURL=babylon.materialHelper.js.map
  42960. var BABYLON;
  42961. (function (BABYLON) {
  42962. /**
  42963. * Base class of materials working in push mode in babylon JS
  42964. * @hidden
  42965. */
  42966. var PushMaterial = /** @class */ (function (_super) {
  42967. __extends(PushMaterial, _super);
  42968. function PushMaterial(name, scene) {
  42969. var _this = _super.call(this, name, scene) || this;
  42970. _this._normalMatrix = new BABYLON.Matrix();
  42971. _this.storeEffectOnSubMeshes = true;
  42972. return _this;
  42973. }
  42974. PushMaterial.prototype.getEffect = function () {
  42975. return this._activeEffect;
  42976. };
  42977. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  42978. if (!mesh) {
  42979. return false;
  42980. }
  42981. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  42982. return true;
  42983. }
  42984. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  42985. };
  42986. /**
  42987. * Binds the given world matrix to the active effect
  42988. *
  42989. * @param world the matrix to bind
  42990. */
  42991. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  42992. this._activeEffect.setMatrix("world", world);
  42993. };
  42994. /**
  42995. * Binds the given normal matrix to the active effect
  42996. *
  42997. * @param normalMatrix the matrix to bind
  42998. */
  42999. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  43000. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  43001. };
  43002. PushMaterial.prototype.bind = function (world, mesh) {
  43003. if (!mesh) {
  43004. return;
  43005. }
  43006. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  43007. };
  43008. PushMaterial.prototype._afterBind = function (mesh, effect) {
  43009. if (effect === void 0) { effect = null; }
  43010. _super.prototype._afterBind.call(this, mesh);
  43011. this.getScene()._cachedEffect = effect;
  43012. };
  43013. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  43014. if (visibility === void 0) { visibility = 1; }
  43015. return scene.isCachedMaterialInvalid(this, effect, visibility);
  43016. };
  43017. return PushMaterial;
  43018. }(BABYLON.Material));
  43019. BABYLON.PushMaterial = PushMaterial;
  43020. })(BABYLON || (BABYLON = {}));
  43021. //# sourceMappingURL=babylon.pushMaterial.js.map
  43022. var BABYLON;
  43023. (function (BABYLON) {
  43024. /** @hidden */
  43025. var StandardMaterialDefines = /** @class */ (function (_super) {
  43026. __extends(StandardMaterialDefines, _super);
  43027. function StandardMaterialDefines() {
  43028. var _this = _super.call(this) || this;
  43029. _this.MAINUV1 = false;
  43030. _this.MAINUV2 = false;
  43031. _this.DIFFUSE = false;
  43032. _this.DIFFUSEDIRECTUV = 0;
  43033. _this.AMBIENT = false;
  43034. _this.AMBIENTDIRECTUV = 0;
  43035. _this.OPACITY = false;
  43036. _this.OPACITYDIRECTUV = 0;
  43037. _this.OPACITYRGB = false;
  43038. _this.REFLECTION = false;
  43039. _this.EMISSIVE = false;
  43040. _this.EMISSIVEDIRECTUV = 0;
  43041. _this.SPECULAR = false;
  43042. _this.SPECULARDIRECTUV = 0;
  43043. _this.BUMP = false;
  43044. _this.BUMPDIRECTUV = 0;
  43045. _this.PARALLAX = false;
  43046. _this.PARALLAXOCCLUSION = false;
  43047. _this.SPECULAROVERALPHA = false;
  43048. _this.CLIPPLANE = false;
  43049. _this.CLIPPLANE2 = false;
  43050. _this.CLIPPLANE3 = false;
  43051. _this.CLIPPLANE4 = false;
  43052. _this.ALPHATEST = false;
  43053. _this.DEPTHPREPASS = false;
  43054. _this.ALPHAFROMDIFFUSE = false;
  43055. _this.POINTSIZE = false;
  43056. _this.FOG = false;
  43057. _this.SPECULARTERM = false;
  43058. _this.DIFFUSEFRESNEL = false;
  43059. _this.OPACITYFRESNEL = false;
  43060. _this.REFLECTIONFRESNEL = false;
  43061. _this.REFRACTIONFRESNEL = false;
  43062. _this.EMISSIVEFRESNEL = false;
  43063. _this.FRESNEL = false;
  43064. _this.NORMAL = false;
  43065. _this.UV1 = false;
  43066. _this.UV2 = false;
  43067. _this.VERTEXCOLOR = false;
  43068. _this.VERTEXALPHA = false;
  43069. _this.NUM_BONE_INFLUENCERS = 0;
  43070. _this.BonesPerMesh = 0;
  43071. _this.INSTANCES = false;
  43072. _this.GLOSSINESS = false;
  43073. _this.ROUGHNESS = false;
  43074. _this.EMISSIVEASILLUMINATION = false;
  43075. _this.LINKEMISSIVEWITHDIFFUSE = false;
  43076. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  43077. _this.LIGHTMAP = false;
  43078. _this.LIGHTMAPDIRECTUV = 0;
  43079. _this.OBJECTSPACE_NORMALMAP = false;
  43080. _this.USELIGHTMAPASSHADOWMAP = false;
  43081. _this.REFLECTIONMAP_3D = false;
  43082. _this.REFLECTIONMAP_SPHERICAL = false;
  43083. _this.REFLECTIONMAP_PLANAR = false;
  43084. _this.REFLECTIONMAP_CUBIC = false;
  43085. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43086. _this.REFLECTIONMAP_PROJECTION = false;
  43087. _this.REFLECTIONMAP_SKYBOX = false;
  43088. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  43089. _this.REFLECTIONMAP_EXPLICIT = false;
  43090. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43091. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43092. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43093. _this.INVERTCUBICMAP = false;
  43094. _this.LOGARITHMICDEPTH = false;
  43095. _this.REFRACTION = false;
  43096. _this.REFRACTIONMAP_3D = false;
  43097. _this.REFLECTIONOVERALPHA = false;
  43098. _this.TWOSIDEDLIGHTING = false;
  43099. _this.SHADOWFLOAT = false;
  43100. _this.MORPHTARGETS = false;
  43101. _this.MORPHTARGETS_NORMAL = false;
  43102. _this.MORPHTARGETS_TANGENT = false;
  43103. _this.NUM_MORPH_INFLUENCERS = 0;
  43104. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  43105. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  43106. _this.IMAGEPROCESSING = false;
  43107. _this.VIGNETTE = false;
  43108. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43109. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43110. _this.TONEMAPPING = false;
  43111. _this.TONEMAPPING_ACES = false;
  43112. _this.CONTRAST = false;
  43113. _this.COLORCURVES = false;
  43114. _this.COLORGRADING = false;
  43115. _this.COLORGRADING3D = false;
  43116. _this.SAMPLER3DGREENDEPTH = false;
  43117. _this.SAMPLER3DBGRMAP = false;
  43118. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43119. /**
  43120. * If the reflection texture on this material is in linear color space
  43121. * @hidden
  43122. */
  43123. _this.IS_REFLECTION_LINEAR = false;
  43124. /**
  43125. * If the refraction texture on this material is in linear color space
  43126. * @hidden
  43127. */
  43128. _this.IS_REFRACTION_LINEAR = false;
  43129. _this.EXPOSURE = false;
  43130. _this.rebuild();
  43131. return _this;
  43132. }
  43133. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  43134. var modes = [
  43135. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  43136. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  43137. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  43138. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  43139. ];
  43140. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  43141. var mode = modes_1[_i];
  43142. this[mode] = (mode === modeToEnable);
  43143. }
  43144. };
  43145. return StandardMaterialDefines;
  43146. }(BABYLON.MaterialDefines));
  43147. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  43148. /**
  43149. * This is the default material used in Babylon. It is the best trade off between quality
  43150. * and performances.
  43151. * @see http://doc.babylonjs.com/babylon101/materials
  43152. */
  43153. var StandardMaterial = /** @class */ (function (_super) {
  43154. __extends(StandardMaterial, _super);
  43155. /**
  43156. * Instantiates a new standard material.
  43157. * This is the default material used in Babylon. It is the best trade off between quality
  43158. * and performances.
  43159. * @see http://doc.babylonjs.com/babylon101/materials
  43160. * @param name Define the name of the material in the scene
  43161. * @param scene Define the scene the material belong to
  43162. */
  43163. function StandardMaterial(name, scene) {
  43164. var _this = _super.call(this, name, scene) || this;
  43165. /**
  43166. * The color of the material lit by the environmental background lighting.
  43167. * @see http://doc.babylonjs.com/babylon101/materials#ambient-color-example
  43168. */
  43169. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  43170. /**
  43171. * The basic color of the material as viewed under a light.
  43172. */
  43173. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  43174. /**
  43175. * Define how the color and intensity of the highlight given by the light in the material.
  43176. */
  43177. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  43178. /**
  43179. * Define the color of the material as if self lit.
  43180. * This will be mixed in the final result even in the absence of light.
  43181. */
  43182. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  43183. /**
  43184. * Defines how sharp are the highlights in the material.
  43185. * The bigger the value the sharper giving a more glossy feeling to the result.
  43186. * Reversely, the smaller the value the blurrier giving a more rough feeling to the result.
  43187. */
  43188. _this.specularPower = 64;
  43189. _this._useAlphaFromDiffuseTexture = false;
  43190. _this._useEmissiveAsIllumination = false;
  43191. _this._linkEmissiveWithDiffuse = false;
  43192. _this._useSpecularOverAlpha = false;
  43193. _this._useReflectionOverAlpha = false;
  43194. _this._disableLighting = false;
  43195. _this._useObjectSpaceNormalMap = false;
  43196. _this._useParallax = false;
  43197. _this._useParallaxOcclusion = false;
  43198. /**
  43199. * 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.
  43200. */
  43201. _this.parallaxScaleBias = 0.05;
  43202. _this._roughness = 0;
  43203. /**
  43204. * In case of refraction, define the value of the indice of refraction.
  43205. * @see http://doc.babylonjs.com/how_to/reflect#how-to-obtain-reflections-and-refractions
  43206. */
  43207. _this.indexOfRefraction = 0.98;
  43208. /**
  43209. * Invert the refraction texture alongside the y axis.
  43210. * It can be usefull with procedural textures or probe for instance.
  43211. * @see http://doc.babylonjs.com/how_to/reflect#how-to-obtain-reflections-and-refractions
  43212. */
  43213. _this.invertRefractionY = true;
  43214. /**
  43215. * Defines the alpha limits in alpha test mode.
  43216. */
  43217. _this.alphaCutOff = 0.4;
  43218. _this._useLightmapAsShadowmap = false;
  43219. _this._useReflectionFresnelFromSpecular = false;
  43220. _this._useGlossinessFromSpecularMapAlpha = false;
  43221. _this._maxSimultaneousLights = 4;
  43222. _this._invertNormalMapX = false;
  43223. _this._invertNormalMapY = false;
  43224. _this._twoSidedLighting = false;
  43225. _this._renderTargets = new BABYLON.SmartArray(16);
  43226. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  43227. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43228. // Setup the default processing configuration to the scene.
  43229. _this._attachImageProcessingConfiguration(null);
  43230. _this.getRenderTargetTextures = function () {
  43231. _this._renderTargets.reset();
  43232. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43233. _this._renderTargets.push(_this._reflectionTexture);
  43234. }
  43235. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43236. _this._renderTargets.push(_this._refractionTexture);
  43237. }
  43238. return _this._renderTargets;
  43239. };
  43240. return _this;
  43241. }
  43242. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  43243. /**
  43244. * Gets the image processing configuration used either in this material.
  43245. */
  43246. get: function () {
  43247. return this._imageProcessingConfiguration;
  43248. },
  43249. /**
  43250. * Sets the Default image processing configuration used either in the this material.
  43251. *
  43252. * If sets to null, the scene one is in use.
  43253. */
  43254. set: function (value) {
  43255. this._attachImageProcessingConfiguration(value);
  43256. // Ensure the effect will be rebuilt.
  43257. this._markAllSubMeshesAsTexturesDirty();
  43258. },
  43259. enumerable: true,
  43260. configurable: true
  43261. });
  43262. /**
  43263. * Attaches a new image processing configuration to the Standard Material.
  43264. * @param configuration
  43265. */
  43266. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43267. var _this = this;
  43268. if (configuration === this._imageProcessingConfiguration) {
  43269. return;
  43270. }
  43271. // Detaches observer.
  43272. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43273. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43274. }
  43275. // Pick the scene configuration if needed.
  43276. if (!configuration) {
  43277. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43278. }
  43279. else {
  43280. this._imageProcessingConfiguration = configuration;
  43281. }
  43282. // Attaches observer.
  43283. if (this._imageProcessingConfiguration) {
  43284. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43285. _this._markAllSubMeshesAsImageProcessingDirty();
  43286. });
  43287. }
  43288. };
  43289. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  43290. /**
  43291. * Gets wether the color curves effect is enabled.
  43292. */
  43293. get: function () {
  43294. return this.imageProcessingConfiguration.colorCurvesEnabled;
  43295. },
  43296. /**
  43297. * Sets wether the color curves effect is enabled.
  43298. */
  43299. set: function (value) {
  43300. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  43301. },
  43302. enumerable: true,
  43303. configurable: true
  43304. });
  43305. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  43306. /**
  43307. * Gets wether the color grading effect is enabled.
  43308. */
  43309. get: function () {
  43310. return this.imageProcessingConfiguration.colorGradingEnabled;
  43311. },
  43312. /**
  43313. * Gets wether the color grading effect is enabled.
  43314. */
  43315. set: function (value) {
  43316. this.imageProcessingConfiguration.colorGradingEnabled = value;
  43317. },
  43318. enumerable: true,
  43319. configurable: true
  43320. });
  43321. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  43322. /**
  43323. * Gets wether tonemapping is enabled or not.
  43324. */
  43325. get: function () {
  43326. return this._imageProcessingConfiguration.toneMappingEnabled;
  43327. },
  43328. /**
  43329. * Sets wether tonemapping is enabled or not
  43330. */
  43331. set: function (value) {
  43332. this._imageProcessingConfiguration.toneMappingEnabled = value;
  43333. },
  43334. enumerable: true,
  43335. configurable: true
  43336. });
  43337. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  43338. /**
  43339. * The camera exposure used on this material.
  43340. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43341. * This corresponds to a photographic exposure.
  43342. */
  43343. get: function () {
  43344. return this._imageProcessingConfiguration.exposure;
  43345. },
  43346. /**
  43347. * The camera exposure used on this material.
  43348. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43349. * This corresponds to a photographic exposure.
  43350. */
  43351. set: function (value) {
  43352. this._imageProcessingConfiguration.exposure = value;
  43353. },
  43354. enumerable: true,
  43355. configurable: true
  43356. });
  43357. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  43358. /**
  43359. * Gets The camera contrast used on this material.
  43360. */
  43361. get: function () {
  43362. return this._imageProcessingConfiguration.contrast;
  43363. },
  43364. /**
  43365. * Sets The camera contrast used on this material.
  43366. */
  43367. set: function (value) {
  43368. this._imageProcessingConfiguration.contrast = value;
  43369. },
  43370. enumerable: true,
  43371. configurable: true
  43372. });
  43373. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  43374. /**
  43375. * Gets the Color Grading 2D Lookup Texture.
  43376. */
  43377. get: function () {
  43378. return this._imageProcessingConfiguration.colorGradingTexture;
  43379. },
  43380. /**
  43381. * Sets the Color Grading 2D Lookup Texture.
  43382. */
  43383. set: function (value) {
  43384. this._imageProcessingConfiguration.colorGradingTexture = value;
  43385. },
  43386. enumerable: true,
  43387. configurable: true
  43388. });
  43389. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  43390. /**
  43391. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43392. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43393. * 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;
  43394. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43395. */
  43396. get: function () {
  43397. return this._imageProcessingConfiguration.colorCurves;
  43398. },
  43399. /**
  43400. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43401. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43402. * 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;
  43403. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43404. */
  43405. set: function (value) {
  43406. this._imageProcessingConfiguration.colorCurves = value;
  43407. },
  43408. enumerable: true,
  43409. configurable: true
  43410. });
  43411. Object.defineProperty(StandardMaterial.prototype, "hasRenderTargetTextures", {
  43412. /**
  43413. * Gets a boolean indicating that current material needs to register RTT
  43414. */
  43415. get: function () {
  43416. if (StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43417. return true;
  43418. }
  43419. if (StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43420. return true;
  43421. }
  43422. return false;
  43423. },
  43424. enumerable: true,
  43425. configurable: true
  43426. });
  43427. /**
  43428. * Gets the current class name of the material e.g. "StandardMaterial"
  43429. * Mainly use in serialization.
  43430. * @returns the class name
  43431. */
  43432. StandardMaterial.prototype.getClassName = function () {
  43433. return "StandardMaterial";
  43434. };
  43435. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  43436. /**
  43437. * In case the depth buffer does not allow enough depth precision for your scene (might be the case in large scenes)
  43438. * You can try switching to logarithmic depth.
  43439. * @see http://doc.babylonjs.com/how_to/using_logarithmic_depth_buffer
  43440. */
  43441. get: function () {
  43442. return this._useLogarithmicDepth;
  43443. },
  43444. set: function (value) {
  43445. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43446. this._markAllSubMeshesAsMiscDirty();
  43447. },
  43448. enumerable: true,
  43449. configurable: true
  43450. });
  43451. /**
  43452. * Specifies if the material will require alpha blending
  43453. * @returns a boolean specifying if alpha blending is needed
  43454. */
  43455. StandardMaterial.prototype.needAlphaBlending = function () {
  43456. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  43457. };
  43458. /**
  43459. * Specifies if this material should be rendered in alpha test mode
  43460. * @returns a boolean specifying if an alpha test is needed.
  43461. */
  43462. StandardMaterial.prototype.needAlphaTesting = function () {
  43463. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  43464. };
  43465. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  43466. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  43467. };
  43468. /**
  43469. * Get the texture used for alpha test purpose.
  43470. * @returns the diffuse texture in case of the standard material.
  43471. */
  43472. StandardMaterial.prototype.getAlphaTestTexture = function () {
  43473. return this._diffuseTexture;
  43474. };
  43475. /**
  43476. * Get if the submesh is ready to be used and all its information available.
  43477. * Child classes can use it to update shaders
  43478. * @param mesh defines the mesh to check
  43479. * @param subMesh defines which submesh to check
  43480. * @param useInstances specifies that instances should be used
  43481. * @returns a boolean indicating that the submesh is ready or not
  43482. */
  43483. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43484. if (useInstances === void 0) { useInstances = false; }
  43485. if (subMesh.effect && this.isFrozen) {
  43486. if (this._wasPreviouslyReady) {
  43487. return true;
  43488. }
  43489. }
  43490. if (!subMesh._materialDefines) {
  43491. subMesh._materialDefines = new StandardMaterialDefines();
  43492. }
  43493. var scene = this.getScene();
  43494. var defines = subMesh._materialDefines;
  43495. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43496. if (defines._renderId === scene.getRenderId()) {
  43497. return true;
  43498. }
  43499. }
  43500. var engine = scene.getEngine();
  43501. // Lights
  43502. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43503. // Textures
  43504. if (defines._areTexturesDirty) {
  43505. defines._needUVs = false;
  43506. defines.MAINUV1 = false;
  43507. defines.MAINUV2 = false;
  43508. if (scene.texturesEnabled) {
  43509. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43510. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  43511. return false;
  43512. }
  43513. else {
  43514. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  43515. }
  43516. }
  43517. else {
  43518. defines.DIFFUSE = false;
  43519. }
  43520. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43521. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43522. return false;
  43523. }
  43524. else {
  43525. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43526. }
  43527. }
  43528. else {
  43529. defines.AMBIENT = false;
  43530. }
  43531. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43532. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43533. return false;
  43534. }
  43535. else {
  43536. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43537. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43538. }
  43539. }
  43540. else {
  43541. defines.OPACITY = false;
  43542. }
  43543. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43544. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  43545. return false;
  43546. }
  43547. else {
  43548. defines._needNormals = true;
  43549. defines.REFLECTION = true;
  43550. defines.ROUGHNESS = (this._roughness > 0);
  43551. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  43552. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  43553. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  43554. switch (this._reflectionTexture.coordinatesMode) {
  43555. case BABYLON.Texture.EXPLICIT_MODE:
  43556. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  43557. break;
  43558. case BABYLON.Texture.PLANAR_MODE:
  43559. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  43560. break;
  43561. case BABYLON.Texture.PROJECTION_MODE:
  43562. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  43563. break;
  43564. case BABYLON.Texture.SKYBOX_MODE:
  43565. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  43566. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !this._reflectionTexture.getReflectionTextureMatrix().isIdentity();
  43567. break;
  43568. case BABYLON.Texture.SPHERICAL_MODE:
  43569. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  43570. break;
  43571. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43572. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  43573. break;
  43574. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43575. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  43576. break;
  43577. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43578. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  43579. break;
  43580. case BABYLON.Texture.CUBIC_MODE:
  43581. case BABYLON.Texture.INVCUBIC_MODE:
  43582. default:
  43583. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  43584. break;
  43585. }
  43586. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  43587. }
  43588. }
  43589. else {
  43590. defines.REFLECTION = false;
  43591. }
  43592. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43593. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43594. return false;
  43595. }
  43596. else {
  43597. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43598. }
  43599. }
  43600. else {
  43601. defines.EMISSIVE = false;
  43602. }
  43603. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43604. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43605. return false;
  43606. }
  43607. else {
  43608. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43609. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43610. }
  43611. }
  43612. else {
  43613. defines.LIGHTMAP = false;
  43614. }
  43615. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43616. if (!this._specularTexture.isReadyOrNotBlocking()) {
  43617. return false;
  43618. }
  43619. else {
  43620. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  43621. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  43622. }
  43623. }
  43624. else {
  43625. defines.SPECULAR = false;
  43626. }
  43627. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  43628. // Bump texure can not be not blocking.
  43629. if (!this._bumpTexture.isReady()) {
  43630. return false;
  43631. }
  43632. else {
  43633. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43634. defines.PARALLAX = this._useParallax;
  43635. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  43636. }
  43637. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43638. }
  43639. else {
  43640. defines.BUMP = false;
  43641. }
  43642. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43643. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  43644. return false;
  43645. }
  43646. else {
  43647. defines._needUVs = true;
  43648. defines.REFRACTION = true;
  43649. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  43650. }
  43651. }
  43652. else {
  43653. defines.REFRACTION = false;
  43654. }
  43655. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  43656. }
  43657. else {
  43658. defines.DIFFUSE = false;
  43659. defines.AMBIENT = false;
  43660. defines.OPACITY = false;
  43661. defines.REFLECTION = false;
  43662. defines.EMISSIVE = false;
  43663. defines.LIGHTMAP = false;
  43664. defines.BUMP = false;
  43665. defines.REFRACTION = false;
  43666. }
  43667. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  43668. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  43669. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  43670. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43671. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43672. }
  43673. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43674. if (!this._imageProcessingConfiguration.isReady()) {
  43675. return false;
  43676. }
  43677. this._imageProcessingConfiguration.prepareDefines(defines);
  43678. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  43679. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  43680. }
  43681. if (defines._areFresnelDirty) {
  43682. if (StandardMaterial.FresnelEnabled) {
  43683. // Fresnel
  43684. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  43685. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  43686. this._reflectionFresnelParameters) {
  43687. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  43688. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  43689. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  43690. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  43691. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  43692. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  43693. defines._needNormals = true;
  43694. defines.FRESNEL = true;
  43695. }
  43696. }
  43697. else {
  43698. defines.FRESNEL = false;
  43699. }
  43700. }
  43701. // Misc.
  43702. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  43703. // Attribs
  43704. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  43705. // Values that need to be evaluated on every frame
  43706. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  43707. // Get correct effect
  43708. if (defines.isDirty) {
  43709. defines.markAsProcessed();
  43710. scene.resetCachedMaterial();
  43711. // Fallbacks
  43712. var fallbacks = new BABYLON.EffectFallbacks();
  43713. if (defines.REFLECTION) {
  43714. fallbacks.addFallback(0, "REFLECTION");
  43715. }
  43716. if (defines.SPECULAR) {
  43717. fallbacks.addFallback(0, "SPECULAR");
  43718. }
  43719. if (defines.BUMP) {
  43720. fallbacks.addFallback(0, "BUMP");
  43721. }
  43722. if (defines.PARALLAX) {
  43723. fallbacks.addFallback(1, "PARALLAX");
  43724. }
  43725. if (defines.PARALLAXOCCLUSION) {
  43726. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  43727. }
  43728. if (defines.SPECULAROVERALPHA) {
  43729. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  43730. }
  43731. if (defines.FOG) {
  43732. fallbacks.addFallback(1, "FOG");
  43733. }
  43734. if (defines.POINTSIZE) {
  43735. fallbacks.addFallback(0, "POINTSIZE");
  43736. }
  43737. if (defines.LOGARITHMICDEPTH) {
  43738. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  43739. }
  43740. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  43741. if (defines.SPECULARTERM) {
  43742. fallbacks.addFallback(0, "SPECULARTERM");
  43743. }
  43744. if (defines.DIFFUSEFRESNEL) {
  43745. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  43746. }
  43747. if (defines.OPACITYFRESNEL) {
  43748. fallbacks.addFallback(2, "OPACITYFRESNEL");
  43749. }
  43750. if (defines.REFLECTIONFRESNEL) {
  43751. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  43752. }
  43753. if (defines.EMISSIVEFRESNEL) {
  43754. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  43755. }
  43756. if (defines.FRESNEL) {
  43757. fallbacks.addFallback(4, "FRESNEL");
  43758. }
  43759. //Attributes
  43760. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43761. if (defines.NORMAL) {
  43762. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43763. }
  43764. if (defines.UV1) {
  43765. attribs.push(BABYLON.VertexBuffer.UVKind);
  43766. }
  43767. if (defines.UV2) {
  43768. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43769. }
  43770. if (defines.VERTEXCOLOR) {
  43771. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43772. }
  43773. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43774. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43775. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43776. var shaderName = "default";
  43777. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  43778. "vFogInfos", "vFogColor", "pointSize",
  43779. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43780. "mBones",
  43781. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  43782. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  43783. "vReflectionPosition", "vReflectionSize",
  43784. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  43785. ];
  43786. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  43787. var uniformBuffers = ["Material", "Scene"];
  43788. if (BABYLON.ImageProcessingConfiguration) {
  43789. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43790. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43791. }
  43792. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43793. uniformsNames: uniforms,
  43794. uniformBuffersNames: uniformBuffers,
  43795. samplers: samplers,
  43796. defines: defines,
  43797. maxSimultaneousLights: this._maxSimultaneousLights
  43798. });
  43799. if (this.customShaderNameResolve) {
  43800. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  43801. }
  43802. var join = defines.toString();
  43803. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  43804. attributes: attribs,
  43805. uniformsNames: uniforms,
  43806. uniformBuffersNames: uniformBuffers,
  43807. samplers: samplers,
  43808. defines: join,
  43809. fallbacks: fallbacks,
  43810. onCompiled: this.onCompiled,
  43811. onError: this.onError,
  43812. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43813. }, engine), defines);
  43814. this.buildUniformLayout();
  43815. }
  43816. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43817. return false;
  43818. }
  43819. defines._renderId = scene.getRenderId();
  43820. this._wasPreviouslyReady = true;
  43821. return true;
  43822. };
  43823. /**
  43824. * Builds the material UBO layouts.
  43825. * Used internally during the effect preparation.
  43826. */
  43827. StandardMaterial.prototype.buildUniformLayout = function () {
  43828. // Order is important !
  43829. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43830. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43831. this._uniformBuffer.addUniform("opacityParts", 4);
  43832. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43833. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43834. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43835. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43836. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43837. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43838. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43839. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43840. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43841. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43842. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43843. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43844. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43845. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43846. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43847. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43848. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43849. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43850. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43851. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43852. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43853. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43854. this._uniformBuffer.addUniform("specularMatrix", 16);
  43855. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43856. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43857. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43858. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43859. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43860. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43861. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43862. this._uniformBuffer.addUniform("pointSize", 1);
  43863. this._uniformBuffer.create();
  43864. };
  43865. /**
  43866. * Unbinds the material from the mesh
  43867. */
  43868. StandardMaterial.prototype.unbind = function () {
  43869. if (this._activeEffect) {
  43870. var needFlag = false;
  43871. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43872. this._activeEffect.setTexture("reflection2DSampler", null);
  43873. needFlag = true;
  43874. }
  43875. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43876. this._activeEffect.setTexture("refraction2DSampler", null);
  43877. needFlag = true;
  43878. }
  43879. if (needFlag) {
  43880. this._markAllSubMeshesAsTexturesDirty();
  43881. }
  43882. }
  43883. _super.prototype.unbind.call(this);
  43884. };
  43885. /**
  43886. * Binds the submesh to this material by preparing the effect and shader to draw
  43887. * @param world defines the world transformation matrix
  43888. * @param mesh defines the mesh containing the submesh
  43889. * @param subMesh defines the submesh to bind the material to
  43890. */
  43891. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43892. var scene = this.getScene();
  43893. var defines = subMesh._materialDefines;
  43894. if (!defines) {
  43895. return;
  43896. }
  43897. var effect = subMesh.effect;
  43898. if (!effect) {
  43899. return;
  43900. }
  43901. this._activeEffect = effect;
  43902. // Matrices
  43903. this.bindOnlyWorldMatrix(world);
  43904. // Normal Matrix
  43905. if (defines.OBJECTSPACE_NORMALMAP) {
  43906. world.toNormalMatrix(this._normalMatrix);
  43907. this.bindOnlyNormalMatrix(this._normalMatrix);
  43908. }
  43909. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43910. // Bones
  43911. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43912. if (mustRebind) {
  43913. this._uniformBuffer.bindToEffect(effect, "Material");
  43914. this.bindViewProjection(effect);
  43915. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43916. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43917. // Fresnel
  43918. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43919. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43920. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43921. }
  43922. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43923. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43924. }
  43925. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43926. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43927. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43928. }
  43929. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43930. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43931. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43932. }
  43933. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43934. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43935. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43936. }
  43937. }
  43938. // Textures
  43939. if (scene.texturesEnabled) {
  43940. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43941. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43942. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43943. if (this._diffuseTexture.hasAlpha) {
  43944. effect.setFloat("alphaCutOff", this.alphaCutOff);
  43945. }
  43946. }
  43947. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43948. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43949. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43950. }
  43951. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43952. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43953. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43954. }
  43955. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43956. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  43957. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  43958. if (this._reflectionTexture.boundingBoxSize) {
  43959. var cubeTexture = this._reflectionTexture;
  43960. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43961. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43962. }
  43963. }
  43964. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43965. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43966. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43967. }
  43968. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43969. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43970. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43971. }
  43972. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43973. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  43974. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  43975. }
  43976. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43977. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  43978. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43979. if (scene._mirroredCameraPosition) {
  43980. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43981. }
  43982. else {
  43983. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43984. }
  43985. }
  43986. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43987. var depth = 1.0;
  43988. if (!this._refractionTexture.isCube) {
  43989. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  43990. if (this._refractionTexture.depth) {
  43991. depth = this._refractionTexture.depth;
  43992. }
  43993. }
  43994. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  43995. }
  43996. }
  43997. // Point size
  43998. if (this.pointsCloud) {
  43999. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44000. }
  44001. if (defines.SPECULARTERM) {
  44002. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  44003. }
  44004. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  44005. // Diffuse
  44006. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  44007. }
  44008. // Textures
  44009. if (scene.texturesEnabled) {
  44010. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  44011. effect.setTexture("diffuseSampler", this._diffuseTexture);
  44012. }
  44013. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  44014. effect.setTexture("ambientSampler", this._ambientTexture);
  44015. }
  44016. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  44017. effect.setTexture("opacitySampler", this._opacityTexture);
  44018. }
  44019. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44020. if (this._reflectionTexture.isCube) {
  44021. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  44022. }
  44023. else {
  44024. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  44025. }
  44026. }
  44027. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  44028. effect.setTexture("emissiveSampler", this._emissiveTexture);
  44029. }
  44030. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44031. effect.setTexture("lightmapSampler", this._lightmapTexture);
  44032. }
  44033. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44034. effect.setTexture("specularSampler", this._specularTexture);
  44035. }
  44036. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  44037. effect.setTexture("bumpSampler", this._bumpTexture);
  44038. }
  44039. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44040. var depth = 1.0;
  44041. if (this._refractionTexture.isCube) {
  44042. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  44043. }
  44044. else {
  44045. effect.setTexture("refraction2DSampler", this._refractionTexture);
  44046. }
  44047. }
  44048. }
  44049. // Clip plane
  44050. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  44051. // Colors
  44052. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  44053. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  44054. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44055. }
  44056. if (mustRebind || !this.isFrozen) {
  44057. // Lights
  44058. if (scene.lightsEnabled && !this._disableLighting) {
  44059. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  44060. }
  44061. // View
  44062. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  44063. this.bindView(effect);
  44064. }
  44065. // Fog
  44066. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  44067. // Morph targets
  44068. if (defines.NUM_MORPH_INFLUENCERS) {
  44069. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  44070. }
  44071. // Log. depth
  44072. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  44073. // image processing
  44074. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  44075. this._imageProcessingConfiguration.bind(this._activeEffect);
  44076. }
  44077. }
  44078. this._uniformBuffer.update();
  44079. this._afterBind(mesh, this._activeEffect);
  44080. };
  44081. /**
  44082. * Get the list of animatables in the material.
  44083. * @returns the list of animatables object used in the material
  44084. */
  44085. StandardMaterial.prototype.getAnimatables = function () {
  44086. var results = [];
  44087. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  44088. results.push(this._diffuseTexture);
  44089. }
  44090. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44091. results.push(this._ambientTexture);
  44092. }
  44093. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44094. results.push(this._opacityTexture);
  44095. }
  44096. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44097. results.push(this._reflectionTexture);
  44098. }
  44099. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44100. results.push(this._emissiveTexture);
  44101. }
  44102. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  44103. results.push(this._specularTexture);
  44104. }
  44105. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44106. results.push(this._bumpTexture);
  44107. }
  44108. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44109. results.push(this._lightmapTexture);
  44110. }
  44111. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44112. results.push(this._refractionTexture);
  44113. }
  44114. return results;
  44115. };
  44116. /**
  44117. * Gets the active textures from the material
  44118. * @returns an array of textures
  44119. */
  44120. StandardMaterial.prototype.getActiveTextures = function () {
  44121. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44122. if (this._diffuseTexture) {
  44123. activeTextures.push(this._diffuseTexture);
  44124. }
  44125. if (this._ambientTexture) {
  44126. activeTextures.push(this._ambientTexture);
  44127. }
  44128. if (this._opacityTexture) {
  44129. activeTextures.push(this._opacityTexture);
  44130. }
  44131. if (this._reflectionTexture) {
  44132. activeTextures.push(this._reflectionTexture);
  44133. }
  44134. if (this._emissiveTexture) {
  44135. activeTextures.push(this._emissiveTexture);
  44136. }
  44137. if (this._specularTexture) {
  44138. activeTextures.push(this._specularTexture);
  44139. }
  44140. if (this._bumpTexture) {
  44141. activeTextures.push(this._bumpTexture);
  44142. }
  44143. if (this._lightmapTexture) {
  44144. activeTextures.push(this._lightmapTexture);
  44145. }
  44146. if (this._refractionTexture) {
  44147. activeTextures.push(this._refractionTexture);
  44148. }
  44149. return activeTextures;
  44150. };
  44151. /**
  44152. * Specifies if the material uses a texture
  44153. * @param texture defines the texture to check against the material
  44154. * @returns a boolean specifying if the material uses the texture
  44155. */
  44156. StandardMaterial.prototype.hasTexture = function (texture) {
  44157. if (_super.prototype.hasTexture.call(this, texture)) {
  44158. return true;
  44159. }
  44160. if (this._diffuseTexture === texture) {
  44161. return true;
  44162. }
  44163. if (this._ambientTexture === texture) {
  44164. return true;
  44165. }
  44166. if (this._opacityTexture === texture) {
  44167. return true;
  44168. }
  44169. if (this._reflectionTexture === texture) {
  44170. return true;
  44171. }
  44172. if (this._emissiveTexture === texture) {
  44173. return true;
  44174. }
  44175. if (this._specularTexture === texture) {
  44176. return true;
  44177. }
  44178. if (this._bumpTexture === texture) {
  44179. return true;
  44180. }
  44181. if (this._lightmapTexture === texture) {
  44182. return true;
  44183. }
  44184. if (this._refractionTexture === texture) {
  44185. return true;
  44186. }
  44187. return false;
  44188. };
  44189. /**
  44190. * Disposes the material
  44191. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  44192. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  44193. */
  44194. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44195. if (forceDisposeTextures) {
  44196. if (this._diffuseTexture) {
  44197. this._diffuseTexture.dispose();
  44198. }
  44199. if (this._ambientTexture) {
  44200. this._ambientTexture.dispose();
  44201. }
  44202. if (this._opacityTexture) {
  44203. this._opacityTexture.dispose();
  44204. }
  44205. if (this._reflectionTexture) {
  44206. this._reflectionTexture.dispose();
  44207. }
  44208. if (this._emissiveTexture) {
  44209. this._emissiveTexture.dispose();
  44210. }
  44211. if (this._specularTexture) {
  44212. this._specularTexture.dispose();
  44213. }
  44214. if (this._bumpTexture) {
  44215. this._bumpTexture.dispose();
  44216. }
  44217. if (this._lightmapTexture) {
  44218. this._lightmapTexture.dispose();
  44219. }
  44220. if (this._refractionTexture) {
  44221. this._refractionTexture.dispose();
  44222. }
  44223. }
  44224. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44225. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44226. }
  44227. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44228. };
  44229. /**
  44230. * Makes a duplicate of the material, and gives it a new name
  44231. * @param name defines the new name for the duplicated material
  44232. * @returns the cloned material
  44233. */
  44234. StandardMaterial.prototype.clone = function (name) {
  44235. var _this = this;
  44236. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  44237. result.name = name;
  44238. result.id = name;
  44239. return result;
  44240. };
  44241. /**
  44242. * Serializes this material in a JSON representation
  44243. * @returns the serialized material object
  44244. */
  44245. StandardMaterial.prototype.serialize = function () {
  44246. return BABYLON.SerializationHelper.Serialize(this);
  44247. };
  44248. /**
  44249. * Creates a standard material from parsed material data
  44250. * @param source defines the JSON represnetation of the material
  44251. * @param scene defines the hosting scene
  44252. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  44253. * @returns a new material
  44254. */
  44255. StandardMaterial.Parse = function (source, scene, rootUrl) {
  44256. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  44257. };
  44258. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  44259. /**
  44260. * Are diffuse textures enabled in the application.
  44261. */
  44262. get: function () {
  44263. return StandardMaterial._DiffuseTextureEnabled;
  44264. },
  44265. set: function (value) {
  44266. if (StandardMaterial._DiffuseTextureEnabled === value) {
  44267. return;
  44268. }
  44269. StandardMaterial._DiffuseTextureEnabled = value;
  44270. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44271. },
  44272. enumerable: true,
  44273. configurable: true
  44274. });
  44275. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  44276. /**
  44277. * Are ambient textures enabled in the application.
  44278. */
  44279. get: function () {
  44280. return StandardMaterial._AmbientTextureEnabled;
  44281. },
  44282. set: function (value) {
  44283. if (StandardMaterial._AmbientTextureEnabled === value) {
  44284. return;
  44285. }
  44286. StandardMaterial._AmbientTextureEnabled = value;
  44287. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44288. },
  44289. enumerable: true,
  44290. configurable: true
  44291. });
  44292. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  44293. /**
  44294. * Are opacity textures enabled in the application.
  44295. */
  44296. get: function () {
  44297. return StandardMaterial._OpacityTextureEnabled;
  44298. },
  44299. set: function (value) {
  44300. if (StandardMaterial._OpacityTextureEnabled === value) {
  44301. return;
  44302. }
  44303. StandardMaterial._OpacityTextureEnabled = value;
  44304. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44305. },
  44306. enumerable: true,
  44307. configurable: true
  44308. });
  44309. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  44310. /**
  44311. * Are reflection textures enabled in the application.
  44312. */
  44313. get: function () {
  44314. return StandardMaterial._ReflectionTextureEnabled;
  44315. },
  44316. set: function (value) {
  44317. if (StandardMaterial._ReflectionTextureEnabled === value) {
  44318. return;
  44319. }
  44320. StandardMaterial._ReflectionTextureEnabled = value;
  44321. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44322. },
  44323. enumerable: true,
  44324. configurable: true
  44325. });
  44326. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  44327. /**
  44328. * Are emissive textures enabled in the application.
  44329. */
  44330. get: function () {
  44331. return StandardMaterial._EmissiveTextureEnabled;
  44332. },
  44333. set: function (value) {
  44334. if (StandardMaterial._EmissiveTextureEnabled === value) {
  44335. return;
  44336. }
  44337. StandardMaterial._EmissiveTextureEnabled = value;
  44338. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44339. },
  44340. enumerable: true,
  44341. configurable: true
  44342. });
  44343. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  44344. /**
  44345. * Are specular textures enabled in the application.
  44346. */
  44347. get: function () {
  44348. return StandardMaterial._SpecularTextureEnabled;
  44349. },
  44350. set: function (value) {
  44351. if (StandardMaterial._SpecularTextureEnabled === value) {
  44352. return;
  44353. }
  44354. StandardMaterial._SpecularTextureEnabled = value;
  44355. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44356. },
  44357. enumerable: true,
  44358. configurable: true
  44359. });
  44360. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  44361. /**
  44362. * Are bump textures enabled in the application.
  44363. */
  44364. get: function () {
  44365. return StandardMaterial._BumpTextureEnabled;
  44366. },
  44367. set: function (value) {
  44368. if (StandardMaterial._BumpTextureEnabled === value) {
  44369. return;
  44370. }
  44371. StandardMaterial._BumpTextureEnabled = value;
  44372. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44373. },
  44374. enumerable: true,
  44375. configurable: true
  44376. });
  44377. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  44378. /**
  44379. * Are lightmap textures enabled in the application.
  44380. */
  44381. get: function () {
  44382. return StandardMaterial._LightmapTextureEnabled;
  44383. },
  44384. set: function (value) {
  44385. if (StandardMaterial._LightmapTextureEnabled === value) {
  44386. return;
  44387. }
  44388. StandardMaterial._LightmapTextureEnabled = value;
  44389. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44390. },
  44391. enumerable: true,
  44392. configurable: true
  44393. });
  44394. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  44395. /**
  44396. * Are refraction textures enabled in the application.
  44397. */
  44398. get: function () {
  44399. return StandardMaterial._RefractionTextureEnabled;
  44400. },
  44401. set: function (value) {
  44402. if (StandardMaterial._RefractionTextureEnabled === value) {
  44403. return;
  44404. }
  44405. StandardMaterial._RefractionTextureEnabled = value;
  44406. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44407. },
  44408. enumerable: true,
  44409. configurable: true
  44410. });
  44411. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  44412. /**
  44413. * Are color grading textures enabled in the application.
  44414. */
  44415. get: function () {
  44416. return StandardMaterial._ColorGradingTextureEnabled;
  44417. },
  44418. set: function (value) {
  44419. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  44420. return;
  44421. }
  44422. StandardMaterial._ColorGradingTextureEnabled = value;
  44423. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44424. },
  44425. enumerable: true,
  44426. configurable: true
  44427. });
  44428. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  44429. /**
  44430. * Are fresnels enabled in the application.
  44431. */
  44432. get: function () {
  44433. return StandardMaterial._FresnelEnabled;
  44434. },
  44435. set: function (value) {
  44436. if (StandardMaterial._FresnelEnabled === value) {
  44437. return;
  44438. }
  44439. StandardMaterial._FresnelEnabled = value;
  44440. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  44441. },
  44442. enumerable: true,
  44443. configurable: true
  44444. });
  44445. // Flags used to enable or disable a type of texture for all Standard Materials
  44446. StandardMaterial._DiffuseTextureEnabled = true;
  44447. StandardMaterial._AmbientTextureEnabled = true;
  44448. StandardMaterial._OpacityTextureEnabled = true;
  44449. StandardMaterial._ReflectionTextureEnabled = true;
  44450. StandardMaterial._EmissiveTextureEnabled = true;
  44451. StandardMaterial._SpecularTextureEnabled = true;
  44452. StandardMaterial._BumpTextureEnabled = true;
  44453. StandardMaterial._LightmapTextureEnabled = true;
  44454. StandardMaterial._RefractionTextureEnabled = true;
  44455. StandardMaterial._ColorGradingTextureEnabled = true;
  44456. StandardMaterial._FresnelEnabled = true;
  44457. __decorate([
  44458. BABYLON.serializeAsTexture("diffuseTexture")
  44459. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  44460. __decorate([
  44461. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44462. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  44463. __decorate([
  44464. BABYLON.serializeAsTexture("ambientTexture")
  44465. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  44466. __decorate([
  44467. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44468. ], StandardMaterial.prototype, "ambientTexture", void 0);
  44469. __decorate([
  44470. BABYLON.serializeAsTexture("opacityTexture")
  44471. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  44472. __decorate([
  44473. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44474. ], StandardMaterial.prototype, "opacityTexture", void 0);
  44475. __decorate([
  44476. BABYLON.serializeAsTexture("reflectionTexture")
  44477. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  44478. __decorate([
  44479. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44480. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  44481. __decorate([
  44482. BABYLON.serializeAsTexture("emissiveTexture")
  44483. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  44484. __decorate([
  44485. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44486. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  44487. __decorate([
  44488. BABYLON.serializeAsTexture("specularTexture")
  44489. ], StandardMaterial.prototype, "_specularTexture", void 0);
  44490. __decorate([
  44491. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44492. ], StandardMaterial.prototype, "specularTexture", void 0);
  44493. __decorate([
  44494. BABYLON.serializeAsTexture("bumpTexture")
  44495. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  44496. __decorate([
  44497. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44498. ], StandardMaterial.prototype, "bumpTexture", void 0);
  44499. __decorate([
  44500. BABYLON.serializeAsTexture("lightmapTexture")
  44501. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  44502. __decorate([
  44503. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44504. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  44505. __decorate([
  44506. BABYLON.serializeAsTexture("refractionTexture")
  44507. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  44508. __decorate([
  44509. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44510. ], StandardMaterial.prototype, "refractionTexture", void 0);
  44511. __decorate([
  44512. BABYLON.serializeAsColor3("ambient")
  44513. ], StandardMaterial.prototype, "ambientColor", void 0);
  44514. __decorate([
  44515. BABYLON.serializeAsColor3("diffuse")
  44516. ], StandardMaterial.prototype, "diffuseColor", void 0);
  44517. __decorate([
  44518. BABYLON.serializeAsColor3("specular")
  44519. ], StandardMaterial.prototype, "specularColor", void 0);
  44520. __decorate([
  44521. BABYLON.serializeAsColor3("emissive")
  44522. ], StandardMaterial.prototype, "emissiveColor", void 0);
  44523. __decorate([
  44524. BABYLON.serialize()
  44525. ], StandardMaterial.prototype, "specularPower", void 0);
  44526. __decorate([
  44527. BABYLON.serialize("useAlphaFromDiffuseTexture")
  44528. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  44529. __decorate([
  44530. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44531. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  44532. __decorate([
  44533. BABYLON.serialize("useEmissiveAsIllumination")
  44534. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  44535. __decorate([
  44536. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44537. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  44538. __decorate([
  44539. BABYLON.serialize("linkEmissiveWithDiffuse")
  44540. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  44541. __decorate([
  44542. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44543. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  44544. __decorate([
  44545. BABYLON.serialize("useSpecularOverAlpha")
  44546. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  44547. __decorate([
  44548. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44549. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  44550. __decorate([
  44551. BABYLON.serialize("useReflectionOverAlpha")
  44552. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  44553. __decorate([
  44554. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44555. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  44556. __decorate([
  44557. BABYLON.serialize("disableLighting")
  44558. ], StandardMaterial.prototype, "_disableLighting", void 0);
  44559. __decorate([
  44560. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44561. ], StandardMaterial.prototype, "disableLighting", void 0);
  44562. __decorate([
  44563. BABYLON.serialize("useObjectSpaceNormalMap")
  44564. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  44565. __decorate([
  44566. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44567. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  44568. __decorate([
  44569. BABYLON.serialize("useParallax")
  44570. ], StandardMaterial.prototype, "_useParallax", void 0);
  44571. __decorate([
  44572. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44573. ], StandardMaterial.prototype, "useParallax", void 0);
  44574. __decorate([
  44575. BABYLON.serialize("useParallaxOcclusion")
  44576. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  44577. __decorate([
  44578. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44579. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  44580. __decorate([
  44581. BABYLON.serialize()
  44582. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  44583. __decorate([
  44584. BABYLON.serialize("roughness")
  44585. ], StandardMaterial.prototype, "_roughness", void 0);
  44586. __decorate([
  44587. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44588. ], StandardMaterial.prototype, "roughness", void 0);
  44589. __decorate([
  44590. BABYLON.serialize()
  44591. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  44592. __decorate([
  44593. BABYLON.serialize()
  44594. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  44595. __decorate([
  44596. BABYLON.serialize()
  44597. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  44598. __decorate([
  44599. BABYLON.serialize("useLightmapAsShadowmap")
  44600. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  44601. __decorate([
  44602. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44603. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44604. __decorate([
  44605. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  44606. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  44607. __decorate([
  44608. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44609. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  44610. __decorate([
  44611. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  44612. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  44613. __decorate([
  44614. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  44615. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  44616. __decorate([
  44617. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  44618. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  44619. __decorate([
  44620. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44621. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  44622. __decorate([
  44623. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  44624. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  44625. __decorate([
  44626. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44627. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  44628. __decorate([
  44629. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  44630. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  44631. __decorate([
  44632. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44633. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  44634. __decorate([
  44635. BABYLON.serialize("useReflectionFresnelFromSpecular")
  44636. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  44637. __decorate([
  44638. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44639. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  44640. __decorate([
  44641. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  44642. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  44643. __decorate([
  44644. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44645. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  44646. __decorate([
  44647. BABYLON.serialize("maxSimultaneousLights")
  44648. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  44649. __decorate([
  44650. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44651. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  44652. __decorate([
  44653. BABYLON.serialize("invertNormalMapX")
  44654. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  44655. __decorate([
  44656. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44657. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  44658. __decorate([
  44659. BABYLON.serialize("invertNormalMapY")
  44660. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  44661. __decorate([
  44662. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44663. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  44664. __decorate([
  44665. BABYLON.serialize("twoSidedLighting")
  44666. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  44667. __decorate([
  44668. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44669. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  44670. __decorate([
  44671. BABYLON.serialize()
  44672. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  44673. return StandardMaterial;
  44674. }(BABYLON.PushMaterial));
  44675. BABYLON.StandardMaterial = StandardMaterial;
  44676. })(BABYLON || (BABYLON = {}));
  44677. //# sourceMappingURL=babylon.standardMaterial.js.map
  44678. var BABYLON;
  44679. (function (BABYLON) {
  44680. /**
  44681. * Class representing spherical polynomial coefficients to the 3rd degree
  44682. */
  44683. var SphericalPolynomial = /** @class */ (function () {
  44684. function SphericalPolynomial() {
  44685. /**
  44686. * The x coefficients of the spherical polynomial
  44687. */
  44688. this.x = BABYLON.Vector3.Zero();
  44689. /**
  44690. * The y coefficients of the spherical polynomial
  44691. */
  44692. this.y = BABYLON.Vector3.Zero();
  44693. /**
  44694. * The z coefficients of the spherical polynomial
  44695. */
  44696. this.z = BABYLON.Vector3.Zero();
  44697. /**
  44698. * The xx coefficients of the spherical polynomial
  44699. */
  44700. this.xx = BABYLON.Vector3.Zero();
  44701. /**
  44702. * The yy coefficients of the spherical polynomial
  44703. */
  44704. this.yy = BABYLON.Vector3.Zero();
  44705. /**
  44706. * The zz coefficients of the spherical polynomial
  44707. */
  44708. this.zz = BABYLON.Vector3.Zero();
  44709. /**
  44710. * The xy coefficients of the spherical polynomial
  44711. */
  44712. this.xy = BABYLON.Vector3.Zero();
  44713. /**
  44714. * The yz coefficients of the spherical polynomial
  44715. */
  44716. this.yz = BABYLON.Vector3.Zero();
  44717. /**
  44718. * The zx coefficients of the spherical polynomial
  44719. */
  44720. this.zx = BABYLON.Vector3.Zero();
  44721. }
  44722. /**
  44723. * Adds an ambient color to the spherical polynomial
  44724. * @param color the color to add
  44725. */
  44726. SphericalPolynomial.prototype.addAmbient = function (color) {
  44727. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  44728. this.xx = this.xx.add(colorVector);
  44729. this.yy = this.yy.add(colorVector);
  44730. this.zz = this.zz.add(colorVector);
  44731. };
  44732. /**
  44733. * Scales the spherical polynomial by the given amount
  44734. * @param scale the amount to scale
  44735. */
  44736. SphericalPolynomial.prototype.scale = function (scale) {
  44737. this.x = this.x.scale(scale);
  44738. this.y = this.y.scale(scale);
  44739. this.z = this.z.scale(scale);
  44740. this.xx = this.xx.scale(scale);
  44741. this.yy = this.yy.scale(scale);
  44742. this.zz = this.zz.scale(scale);
  44743. this.yz = this.yz.scale(scale);
  44744. this.zx = this.zx.scale(scale);
  44745. this.xy = this.xy.scale(scale);
  44746. };
  44747. /**
  44748. * Gets the spherical polynomial from harmonics
  44749. * @param harmonics the spherical harmonics
  44750. * @returns the spherical polynomial
  44751. */
  44752. SphericalPolynomial.FromHarmonics = function (harmonics) {
  44753. var result = new SphericalPolynomial();
  44754. result.x = harmonics.l11.scale(1.02333);
  44755. result.y = harmonics.l1_1.scale(1.02333);
  44756. result.z = harmonics.l10.scale(1.02333);
  44757. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  44758. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  44759. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  44760. result.yz = harmonics.l2_1.scale(0.858086);
  44761. result.zx = harmonics.l21.scale(0.858086);
  44762. result.xy = harmonics.l2_2.scale(0.858086);
  44763. result.scale(1.0 / Math.PI);
  44764. return result;
  44765. };
  44766. /**
  44767. * Constructs a spherical polynomial from an array.
  44768. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  44769. * @returns the spherical polynomial
  44770. */
  44771. SphericalPolynomial.FromArray = function (data) {
  44772. var sp = new SphericalPolynomial();
  44773. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  44774. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  44775. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  44776. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  44777. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  44778. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  44779. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  44780. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  44781. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  44782. return sp;
  44783. };
  44784. return SphericalPolynomial;
  44785. }());
  44786. BABYLON.SphericalPolynomial = SphericalPolynomial;
  44787. /**
  44788. * Class representing spherical harmonics coefficients to the 3rd degree
  44789. */
  44790. var SphericalHarmonics = /** @class */ (function () {
  44791. function SphericalHarmonics() {
  44792. /**
  44793. * The l0,0 coefficients of the spherical harmonics
  44794. */
  44795. this.l00 = BABYLON.Vector3.Zero();
  44796. /**
  44797. * The l1,-1 coefficients of the spherical harmonics
  44798. */
  44799. this.l1_1 = BABYLON.Vector3.Zero();
  44800. /**
  44801. * The l1,0 coefficients of the spherical harmonics
  44802. */
  44803. this.l10 = BABYLON.Vector3.Zero();
  44804. /**
  44805. * The l1,1 coefficients of the spherical harmonics
  44806. */
  44807. this.l11 = BABYLON.Vector3.Zero();
  44808. /**
  44809. * The l2,-2 coefficients of the spherical harmonics
  44810. */
  44811. this.l2_2 = BABYLON.Vector3.Zero();
  44812. /**
  44813. * The l2,-1 coefficients of the spherical harmonics
  44814. */
  44815. this.l2_1 = BABYLON.Vector3.Zero();
  44816. /**
  44817. * The l2,0 coefficients of the spherical harmonics
  44818. */
  44819. this.l20 = BABYLON.Vector3.Zero();
  44820. /**
  44821. * The l2,1 coefficients of the spherical harmonics
  44822. */
  44823. this.l21 = BABYLON.Vector3.Zero();
  44824. /**
  44825. * The l2,2 coefficients of the spherical harmonics
  44826. */
  44827. this.lL22 = BABYLON.Vector3.Zero();
  44828. }
  44829. /**
  44830. * Adds a light to the spherical harmonics
  44831. * @param direction the direction of the light
  44832. * @param color the color of the light
  44833. * @param deltaSolidAngle the delta solid angle of the light
  44834. */
  44835. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  44836. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  44837. var c = colorVector.scale(deltaSolidAngle);
  44838. this.l00 = this.l00.add(c.scale(0.282095));
  44839. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  44840. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  44841. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  44842. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  44843. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  44844. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  44845. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  44846. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  44847. };
  44848. /**
  44849. * Scales the spherical harmonics by the given amount
  44850. * @param scale the amount to scale
  44851. */
  44852. SphericalHarmonics.prototype.scale = function (scale) {
  44853. this.l00 = this.l00.scale(scale);
  44854. this.l1_1 = this.l1_1.scale(scale);
  44855. this.l10 = this.l10.scale(scale);
  44856. this.l11 = this.l11.scale(scale);
  44857. this.l2_2 = this.l2_2.scale(scale);
  44858. this.l2_1 = this.l2_1.scale(scale);
  44859. this.l20 = this.l20.scale(scale);
  44860. this.l21 = this.l21.scale(scale);
  44861. this.lL22 = this.lL22.scale(scale);
  44862. };
  44863. /**
  44864. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  44865. *
  44866. * ```
  44867. * E_lm = A_l * L_lm
  44868. * ```
  44869. *
  44870. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  44871. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  44872. * the scaling factors are given in equation 9.
  44873. */
  44874. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  44875. // Constant (Band 0)
  44876. this.l00 = this.l00.scale(3.141593);
  44877. // Linear (Band 1)
  44878. this.l1_1 = this.l1_1.scale(2.094395);
  44879. this.l10 = this.l10.scale(2.094395);
  44880. this.l11 = this.l11.scale(2.094395);
  44881. // Quadratic (Band 2)
  44882. this.l2_2 = this.l2_2.scale(0.785398);
  44883. this.l2_1 = this.l2_1.scale(0.785398);
  44884. this.l20 = this.l20.scale(0.785398);
  44885. this.l21 = this.l21.scale(0.785398);
  44886. this.lL22 = this.lL22.scale(0.785398);
  44887. };
  44888. /**
  44889. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  44890. *
  44891. * ```
  44892. * L = (1/pi) * E * rho
  44893. * ```
  44894. *
  44895. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  44896. */
  44897. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  44898. this.scale(1.0 / Math.PI);
  44899. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  44900. // (The pixel shader must apply albedo after texture fetches, etc).
  44901. };
  44902. /**
  44903. * Gets the spherical harmonics from polynomial
  44904. * @param polynomial the spherical polynomial
  44905. * @returns the spherical harmonics
  44906. */
  44907. SphericalHarmonics.FromPolynomial = function (polynomial) {
  44908. var result = new SphericalHarmonics();
  44909. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  44910. result.l1_1 = polynomial.y.scale(0.977204);
  44911. result.l10 = polynomial.z.scale(0.977204);
  44912. result.l11 = polynomial.x.scale(0.977204);
  44913. result.l2_2 = polynomial.xy.scale(1.16538);
  44914. result.l2_1 = polynomial.yz.scale(1.16538);
  44915. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  44916. result.l21 = polynomial.zx.scale(1.16538);
  44917. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  44918. result.scale(Math.PI);
  44919. return result;
  44920. };
  44921. /**
  44922. * Constructs a spherical harmonics from an array.
  44923. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  44924. * @returns the spherical harmonics
  44925. */
  44926. SphericalHarmonics.FromArray = function (data) {
  44927. var sh = new SphericalHarmonics();
  44928. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  44929. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  44930. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  44931. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  44932. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  44933. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  44934. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  44935. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  44936. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  44937. return sh;
  44938. };
  44939. return SphericalHarmonics;
  44940. }());
  44941. BABYLON.SphericalHarmonics = SphericalHarmonics;
  44942. })(BABYLON || (BABYLON = {}));
  44943. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  44944. var BABYLON;
  44945. (function (BABYLON) {
  44946. var FileFaceOrientation = /** @class */ (function () {
  44947. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  44948. this.name = name;
  44949. this.worldAxisForNormal = worldAxisForNormal;
  44950. this.worldAxisForFileX = worldAxisForFileX;
  44951. this.worldAxisForFileY = worldAxisForFileY;
  44952. }
  44953. return FileFaceOrientation;
  44954. }());
  44955. /**
  44956. * Helper class dealing with the extraction of spherical polynomial dataArray
  44957. * from a cube map.
  44958. */
  44959. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  44960. function CubeMapToSphericalPolynomialTools() {
  44961. }
  44962. /**
  44963. * Converts a texture to the according Spherical Polynomial data.
  44964. * This extracts the first 3 orders only as they are the only one used in the lighting.
  44965. *
  44966. * @param texture The texture to extract the information from.
  44967. * @return The Spherical Polynomial data.
  44968. */
  44969. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  44970. if (!texture.isCube) {
  44971. // Only supports cube Textures currently.
  44972. return null;
  44973. }
  44974. var size = texture.getSize().width;
  44975. var right = texture.readPixels(0);
  44976. var left = texture.readPixels(1);
  44977. var up;
  44978. var down;
  44979. if (texture.isRenderTarget) {
  44980. up = texture.readPixels(3);
  44981. down = texture.readPixels(2);
  44982. }
  44983. else {
  44984. up = texture.readPixels(2);
  44985. down = texture.readPixels(3);
  44986. }
  44987. var front = texture.readPixels(4);
  44988. var back = texture.readPixels(5);
  44989. var gammaSpace = texture.gammaSpace;
  44990. // Always read as RGBA.
  44991. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  44992. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  44993. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  44994. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  44995. }
  44996. var cubeInfo = {
  44997. size: size,
  44998. right: right,
  44999. left: left,
  45000. up: up,
  45001. down: down,
  45002. front: front,
  45003. back: back,
  45004. format: format,
  45005. type: type,
  45006. gammaSpace: gammaSpace,
  45007. };
  45008. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  45009. };
  45010. /**
  45011. * Converts a cubemap to the according Spherical Polynomial data.
  45012. * This extracts the first 3 orders only as they are the only one used in the lighting.
  45013. *
  45014. * @param cubeInfo The Cube map to extract the information from.
  45015. * @return The Spherical Polynomial data.
  45016. */
  45017. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  45018. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  45019. var totalSolidAngle = 0.0;
  45020. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  45021. var du = 2.0 / cubeInfo.size;
  45022. var dv = du;
  45023. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  45024. var minUV = du * 0.5 - 1.0;
  45025. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  45026. var fileFace = this.FileFaces[faceIndex];
  45027. var dataArray = cubeInfo[fileFace.name];
  45028. var v = minUV;
  45029. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  45030. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  45031. // Because SP is still linear, so summation is fine in that basis.
  45032. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  45033. for (var y = 0; y < cubeInfo.size; y++) {
  45034. var u = minUV;
  45035. for (var x = 0; x < cubeInfo.size; x++) {
  45036. // World direction (not normalised)
  45037. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  45038. worldDirection.normalize();
  45039. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  45040. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  45041. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  45042. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  45043. // Handle Integer types.
  45044. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  45045. r /= 255;
  45046. g /= 255;
  45047. b /= 255;
  45048. }
  45049. // Handle Gamma space textures.
  45050. if (cubeInfo.gammaSpace) {
  45051. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  45052. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  45053. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  45054. }
  45055. var color = new BABYLON.Color3(r, g, b);
  45056. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  45057. totalSolidAngle += deltaSolidAngle;
  45058. u += du;
  45059. }
  45060. v += dv;
  45061. }
  45062. }
  45063. // Solid angle for entire sphere is 4*pi
  45064. var sphereSolidAngle = 4.0 * Math.PI;
  45065. // Adjust the solid angle to allow for how many faces we processed.
  45066. var facesProcessed = 6.0;
  45067. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  45068. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  45069. // This is needed because the numerical integration over the cube uses a
  45070. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  45071. // and also to compensate for accumulative error due to float precision in the summation.
  45072. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  45073. sphericalHarmonics.scale(correctionFactor);
  45074. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  45075. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  45076. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  45077. };
  45078. CubeMapToSphericalPolynomialTools.FileFaces = [
  45079. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  45080. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  45081. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  45082. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  45083. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  45084. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  45085. ];
  45086. return CubeMapToSphericalPolynomialTools;
  45087. }());
  45088. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  45089. })(BABYLON || (BABYLON = {}));
  45090. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  45091. var BABYLON;
  45092. (function (BABYLON) {
  45093. /**
  45094. * Manages the defines for the PBR Material.
  45095. * @hiddenChildren
  45096. */
  45097. var PBRMaterialDefines = /** @class */ (function (_super) {
  45098. __extends(PBRMaterialDefines, _super);
  45099. /**
  45100. * Initializes the PBR Material defines.
  45101. */
  45102. function PBRMaterialDefines() {
  45103. var _this = _super.call(this) || this;
  45104. _this.PBR = true;
  45105. _this.MAINUV1 = false;
  45106. _this.MAINUV2 = false;
  45107. _this.UV1 = false;
  45108. _this.UV2 = false;
  45109. _this.ALBEDO = false;
  45110. _this.ALBEDODIRECTUV = 0;
  45111. _this.VERTEXCOLOR = false;
  45112. _this.AMBIENT = false;
  45113. _this.AMBIENTDIRECTUV = 0;
  45114. _this.AMBIENTINGRAYSCALE = false;
  45115. _this.OPACITY = false;
  45116. _this.VERTEXALPHA = false;
  45117. _this.OPACITYDIRECTUV = 0;
  45118. _this.OPACITYRGB = false;
  45119. _this.ALPHATEST = false;
  45120. _this.DEPTHPREPASS = false;
  45121. _this.ALPHABLEND = false;
  45122. _this.ALPHAFROMALBEDO = false;
  45123. _this.ALPHATESTVALUE = "0.5";
  45124. _this.SPECULAROVERALPHA = false;
  45125. _this.RADIANCEOVERALPHA = false;
  45126. _this.ALPHAFRESNEL = false;
  45127. _this.LINEARALPHAFRESNEL = false;
  45128. _this.PREMULTIPLYALPHA = false;
  45129. _this.EMISSIVE = false;
  45130. _this.EMISSIVEDIRECTUV = 0;
  45131. _this.REFLECTIVITY = false;
  45132. _this.REFLECTIVITYDIRECTUV = 0;
  45133. _this.SPECULARTERM = false;
  45134. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  45135. _this.MICROSURFACEAUTOMATIC = false;
  45136. _this.LODBASEDMICROSFURACE = false;
  45137. _this.MICROSURFACEMAP = false;
  45138. _this.MICROSURFACEMAPDIRECTUV = 0;
  45139. _this.METALLICWORKFLOW = false;
  45140. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  45141. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  45142. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  45143. _this.AOSTOREINMETALMAPRED = false;
  45144. _this.ENVIRONMENTBRDF = false;
  45145. _this.NORMAL = false;
  45146. _this.TANGENT = false;
  45147. _this.BUMP = false;
  45148. _this.BUMPDIRECTUV = 0;
  45149. _this.OBJECTSPACE_NORMALMAP = false;
  45150. _this.PARALLAX = false;
  45151. _this.PARALLAXOCCLUSION = false;
  45152. _this.NORMALXYSCALE = true;
  45153. _this.LIGHTMAP = false;
  45154. _this.LIGHTMAPDIRECTUV = 0;
  45155. _this.USELIGHTMAPASSHADOWMAP = false;
  45156. _this.GAMMALIGHTMAP = false;
  45157. _this.REFLECTION = false;
  45158. _this.REFLECTIONMAP_3D = false;
  45159. _this.REFLECTIONMAP_SPHERICAL = false;
  45160. _this.REFLECTIONMAP_PLANAR = false;
  45161. _this.REFLECTIONMAP_CUBIC = false;
  45162. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  45163. _this.REFLECTIONMAP_PROJECTION = false;
  45164. _this.REFLECTIONMAP_SKYBOX = false;
  45165. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  45166. _this.REFLECTIONMAP_EXPLICIT = false;
  45167. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45168. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  45169. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  45170. _this.INVERTCUBICMAP = false;
  45171. _this.USESPHERICALFROMREFLECTIONMAP = false;
  45172. _this.USESPHERICALINVERTEX = false;
  45173. _this.REFLECTIONMAP_OPPOSITEZ = false;
  45174. _this.LODINREFLECTIONALPHA = false;
  45175. _this.GAMMAREFLECTION = false;
  45176. _this.RGBDREFLECTION = false;
  45177. _this.RADIANCEOCCLUSION = false;
  45178. _this.HORIZONOCCLUSION = false;
  45179. _this.REFRACTION = false;
  45180. _this.REFRACTIONMAP_3D = false;
  45181. _this.REFRACTIONMAP_OPPOSITEZ = false;
  45182. _this.LODINREFRACTIONALPHA = false;
  45183. _this.GAMMAREFRACTION = false;
  45184. _this.RGBDREFRACTION = false;
  45185. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  45186. _this.INSTANCES = false;
  45187. _this.NUM_BONE_INFLUENCERS = 0;
  45188. _this.BonesPerMesh = 0;
  45189. _this.NONUNIFORMSCALING = false;
  45190. _this.MORPHTARGETS = false;
  45191. _this.MORPHTARGETS_NORMAL = false;
  45192. _this.MORPHTARGETS_TANGENT = false;
  45193. _this.NUM_MORPH_INFLUENCERS = 0;
  45194. _this.IMAGEPROCESSING = false;
  45195. _this.VIGNETTE = false;
  45196. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  45197. _this.VIGNETTEBLENDMODEOPAQUE = false;
  45198. _this.TONEMAPPING = false;
  45199. _this.TONEMAPPING_ACES = false;
  45200. _this.CONTRAST = false;
  45201. _this.COLORCURVES = false;
  45202. _this.COLORGRADING = false;
  45203. _this.COLORGRADING3D = false;
  45204. _this.SAMPLER3DGREENDEPTH = false;
  45205. _this.SAMPLER3DBGRMAP = false;
  45206. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  45207. _this.EXPOSURE = false;
  45208. _this.USEPHYSICALLIGHTFALLOFF = false;
  45209. _this.USEGLTFLIGHTFALLOFF = false;
  45210. _this.TWOSIDEDLIGHTING = false;
  45211. _this.SHADOWFLOAT = false;
  45212. _this.CLIPPLANE = false;
  45213. _this.CLIPPLANE2 = false;
  45214. _this.CLIPPLANE3 = false;
  45215. _this.CLIPPLANE4 = false;
  45216. _this.POINTSIZE = false;
  45217. _this.FOG = false;
  45218. _this.LOGARITHMICDEPTH = false;
  45219. _this.FORCENORMALFORWARD = false;
  45220. _this.SPECULARAA = false;
  45221. _this.UNLIT = false;
  45222. _this.rebuild();
  45223. return _this;
  45224. }
  45225. /**
  45226. * Resets the PBR Material defines.
  45227. */
  45228. PBRMaterialDefines.prototype.reset = function () {
  45229. _super.prototype.reset.call(this);
  45230. this.ALPHATESTVALUE = "0.5";
  45231. this.PBR = true;
  45232. };
  45233. return PBRMaterialDefines;
  45234. }(BABYLON.MaterialDefines));
  45235. /**
  45236. * The Physically based material base class of BJS.
  45237. *
  45238. * This offers the main features of a standard PBR material.
  45239. * For more information, please refer to the documentation :
  45240. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45241. */
  45242. var PBRBaseMaterial = /** @class */ (function (_super) {
  45243. __extends(PBRBaseMaterial, _super);
  45244. /**
  45245. * Instantiates a new PBRMaterial instance.
  45246. *
  45247. * @param name The material name
  45248. * @param scene The scene the material will be use in.
  45249. */
  45250. function PBRBaseMaterial(name, scene) {
  45251. var _this = _super.call(this, name, scene) || this;
  45252. /**
  45253. * Intensity of the direct lights e.g. the four lights available in your scene.
  45254. * This impacts both the direct diffuse and specular highlights.
  45255. */
  45256. _this._directIntensity = 1.0;
  45257. /**
  45258. * Intensity of the emissive part of the material.
  45259. * This helps controlling the emissive effect without modifying the emissive color.
  45260. */
  45261. _this._emissiveIntensity = 1.0;
  45262. /**
  45263. * Intensity of the environment e.g. how much the environment will light the object
  45264. * either through harmonics for rough material or through the refelction for shiny ones.
  45265. */
  45266. _this._environmentIntensity = 1.0;
  45267. /**
  45268. * This is a special control allowing the reduction of the specular highlights coming from the
  45269. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45270. */
  45271. _this._specularIntensity = 1.0;
  45272. /**
  45273. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  45274. */
  45275. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  45276. /**
  45277. * Debug Control allowing disabling the bump map on this material.
  45278. */
  45279. _this._disableBumpMap = false;
  45280. /**
  45281. * AKA Occlusion Texture Intensity in other nomenclature.
  45282. */
  45283. _this._ambientTextureStrength = 1.0;
  45284. /**
  45285. * Defines how much the AO map is occluding the analytical lights (point spot...).
  45286. * 1 means it completely occludes it
  45287. * 0 mean it has no impact
  45288. */
  45289. _this._ambientTextureImpactOnAnalyticalLights = BABYLON.PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  45290. /**
  45291. * The color of a material in ambient lighting.
  45292. */
  45293. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  45294. /**
  45295. * AKA Diffuse Color in other nomenclature.
  45296. */
  45297. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  45298. /**
  45299. * AKA Specular Color in other nomenclature.
  45300. */
  45301. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45302. /**
  45303. * The color applied when light is reflected from a material.
  45304. */
  45305. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  45306. /**
  45307. * The color applied when light is emitted from a material.
  45308. */
  45309. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  45310. /**
  45311. * AKA Glossiness in other nomenclature.
  45312. */
  45313. _this._microSurface = 0.9;
  45314. /**
  45315. * source material index of refraction (IOR)' / 'destination material IOR.
  45316. */
  45317. _this._indexOfRefraction = 0.66;
  45318. /**
  45319. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45320. */
  45321. _this._invertRefractionY = false;
  45322. /**
  45323. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45324. * Materials half opaque for instance using refraction could benefit from this control.
  45325. */
  45326. _this._linkRefractionWithTransparency = false;
  45327. /**
  45328. * Specifies that the material will use the light map as a show map.
  45329. */
  45330. _this._useLightmapAsShadowmap = false;
  45331. /**
  45332. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45333. * makes the reflect vector face the model (under horizon).
  45334. */
  45335. _this._useHorizonOcclusion = true;
  45336. /**
  45337. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45338. * too much the area relying on ambient texture to define their ambient occlusion.
  45339. */
  45340. _this._useRadianceOcclusion = true;
  45341. /**
  45342. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45343. */
  45344. _this._useAlphaFromAlbedoTexture = false;
  45345. /**
  45346. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45347. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45348. */
  45349. _this._useSpecularOverAlpha = true;
  45350. /**
  45351. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45352. */
  45353. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  45354. /**
  45355. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45356. */
  45357. _this._useRoughnessFromMetallicTextureAlpha = true;
  45358. /**
  45359. * Specifies if the metallic texture contains the roughness information in its green channel.
  45360. */
  45361. _this._useRoughnessFromMetallicTextureGreen = false;
  45362. /**
  45363. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45364. */
  45365. _this._useMetallnessFromMetallicTextureBlue = false;
  45366. /**
  45367. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45368. */
  45369. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  45370. /**
  45371. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45372. */
  45373. _this._useAmbientInGrayScale = false;
  45374. /**
  45375. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45376. * The material will try to infer what glossiness each pixel should be.
  45377. */
  45378. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  45379. /**
  45380. * Defines the falloff type used in this material.
  45381. * It by default is Physical.
  45382. */
  45383. _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45384. /**
  45385. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45386. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45387. */
  45388. _this._useRadianceOverAlpha = true;
  45389. /**
  45390. * Allows using an object space normal map (instead of tangent space).
  45391. */
  45392. _this._useObjectSpaceNormalMap = false;
  45393. /**
  45394. * Allows using the bump map in parallax mode.
  45395. */
  45396. _this._useParallax = false;
  45397. /**
  45398. * Allows using the bump map in parallax occlusion mode.
  45399. */
  45400. _this._useParallaxOcclusion = false;
  45401. /**
  45402. * Controls the scale bias of the parallax mode.
  45403. */
  45404. _this._parallaxScaleBias = 0.05;
  45405. /**
  45406. * If sets to true, disables all the lights affecting the material.
  45407. */
  45408. _this._disableLighting = false;
  45409. /**
  45410. * Number of Simultaneous lights allowed on the material.
  45411. */
  45412. _this._maxSimultaneousLights = 4;
  45413. /**
  45414. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  45415. */
  45416. _this._invertNormalMapX = false;
  45417. /**
  45418. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  45419. */
  45420. _this._invertNormalMapY = false;
  45421. /**
  45422. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45423. */
  45424. _this._twoSidedLighting = false;
  45425. /**
  45426. * Defines the alpha limits in alpha test mode.
  45427. */
  45428. _this._alphaCutOff = 0.4;
  45429. /**
  45430. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45431. */
  45432. _this._forceAlphaTest = false;
  45433. /**
  45434. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45435. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45436. */
  45437. _this._useAlphaFresnel = false;
  45438. /**
  45439. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45440. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45441. */
  45442. _this._useLinearAlphaFresnel = false;
  45443. /**
  45444. * The transparency mode of the material.
  45445. */
  45446. _this._transparencyMode = null;
  45447. /**
  45448. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  45449. * from cos thetav and roughness:
  45450. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  45451. */
  45452. _this._environmentBRDFTexture = null;
  45453. /**
  45454. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45455. */
  45456. _this._forceIrradianceInFragment = false;
  45457. /**
  45458. * Force normal to face away from face.
  45459. */
  45460. _this._forceNormalForward = false;
  45461. /**
  45462. * Enables specular anti aliasing in the PBR shader.
  45463. * It will both interacts on the Geometry for analytical and IBL lighting.
  45464. * It also prefilter the roughness map based on the bump values.
  45465. */
  45466. _this._enableSpecularAntiAliasing = false;
  45467. /**
  45468. * Stores the available render targets.
  45469. */
  45470. _this._renderTargets = new BABYLON.SmartArray(16);
  45471. /**
  45472. * Sets the global ambient color for the material used in lighting calculations.
  45473. */
  45474. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  45475. /**
  45476. * If set to true, no lighting calculations will be applied.
  45477. */
  45478. _this._unlit = false;
  45479. // Setup the default processing configuration to the scene.
  45480. _this._attachImageProcessingConfiguration(null);
  45481. _this.getRenderTargetTextures = function () {
  45482. _this._renderTargets.reset();
  45483. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  45484. _this._renderTargets.push(_this._reflectionTexture);
  45485. }
  45486. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  45487. _this._renderTargets.push(_this._refractionTexture);
  45488. }
  45489. return _this._renderTargets;
  45490. };
  45491. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45492. return _this;
  45493. }
  45494. /**
  45495. * Attaches a new image processing configuration to the PBR Material.
  45496. * @param configuration
  45497. */
  45498. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  45499. var _this = this;
  45500. if (configuration === this._imageProcessingConfiguration) {
  45501. return;
  45502. }
  45503. // Detaches observer.
  45504. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45505. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45506. }
  45507. // Pick the scene configuration if needed.
  45508. if (!configuration) {
  45509. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  45510. }
  45511. else {
  45512. this._imageProcessingConfiguration = configuration;
  45513. }
  45514. // Attaches observer.
  45515. if (this._imageProcessingConfiguration) {
  45516. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  45517. _this._markAllSubMeshesAsImageProcessingDirty();
  45518. });
  45519. }
  45520. };
  45521. Object.defineProperty(PBRBaseMaterial.prototype, "hasRenderTargetTextures", {
  45522. /**
  45523. * Gets a boolean indicating that current material needs to register RTT
  45524. */
  45525. get: function () {
  45526. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45527. return true;
  45528. }
  45529. if (BABYLON.StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45530. return true;
  45531. }
  45532. return false;
  45533. },
  45534. enumerable: true,
  45535. configurable: true
  45536. });
  45537. /**
  45538. * Gets the name of the material class.
  45539. */
  45540. PBRBaseMaterial.prototype.getClassName = function () {
  45541. return "PBRBaseMaterial";
  45542. };
  45543. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  45544. /**
  45545. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  45546. */
  45547. get: function () {
  45548. return this._useLogarithmicDepth;
  45549. },
  45550. /**
  45551. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  45552. */
  45553. set: function (value) {
  45554. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  45555. },
  45556. enumerable: true,
  45557. configurable: true
  45558. });
  45559. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  45560. /**
  45561. * Gets the current transparency mode.
  45562. */
  45563. get: function () {
  45564. return this._transparencyMode;
  45565. },
  45566. /**
  45567. * Sets the transparency mode of the material.
  45568. *
  45569. * | Value | Type | Description |
  45570. * | ----- | ----------------------------------- | ----------- |
  45571. * | 0 | OPAQUE | |
  45572. * | 1 | ALPHATEST | |
  45573. * | 2 | ALPHABLEND | |
  45574. * | 3 | ALPHATESTANDBLEND | |
  45575. *
  45576. */
  45577. set: function (value) {
  45578. if (this._transparencyMode === value) {
  45579. return;
  45580. }
  45581. this._transparencyMode = value;
  45582. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  45583. this._markAllSubMeshesAsTexturesAndMiscDirty();
  45584. },
  45585. enumerable: true,
  45586. configurable: true
  45587. });
  45588. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  45589. /**
  45590. * Returns true if alpha blending should be disabled.
  45591. */
  45592. get: function () {
  45593. return (this._linkRefractionWithTransparency ||
  45594. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  45595. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  45596. },
  45597. enumerable: true,
  45598. configurable: true
  45599. });
  45600. /**
  45601. * Specifies whether or not this material should be rendered in alpha blend mode.
  45602. */
  45603. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  45604. if (this._disableAlphaBlending) {
  45605. return false;
  45606. }
  45607. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  45608. };
  45609. /**
  45610. * Specifies if the mesh will require alpha blending.
  45611. * @param mesh - BJS mesh.
  45612. */
  45613. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  45614. if (this._disableAlphaBlending) {
  45615. return false;
  45616. }
  45617. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  45618. };
  45619. /**
  45620. * Specifies whether or not this material should be rendered in alpha test mode.
  45621. */
  45622. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  45623. if (this._forceAlphaTest) {
  45624. return true;
  45625. }
  45626. if (this._linkRefractionWithTransparency) {
  45627. return false;
  45628. }
  45629. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  45630. };
  45631. /**
  45632. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  45633. */
  45634. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  45635. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  45636. };
  45637. /**
  45638. * Gets the texture used for the alpha test.
  45639. */
  45640. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  45641. return this._albedoTexture;
  45642. };
  45643. /**
  45644. * Specifies that the submesh is ready to be used.
  45645. * @param mesh - BJS mesh.
  45646. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  45647. * @param useInstances - Specifies that instances should be used.
  45648. * @returns - boolean indicating that the submesh is ready or not.
  45649. */
  45650. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  45651. if (subMesh.effect && this.isFrozen) {
  45652. if (this._wasPreviouslyReady) {
  45653. return true;
  45654. }
  45655. }
  45656. if (!subMesh._materialDefines) {
  45657. subMesh._materialDefines = new PBRMaterialDefines();
  45658. }
  45659. var defines = subMesh._materialDefines;
  45660. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  45661. if (defines._renderId === this.getScene().getRenderId()) {
  45662. return true;
  45663. }
  45664. }
  45665. var scene = this.getScene();
  45666. var engine = scene.getEngine();
  45667. if (defines._areTexturesDirty) {
  45668. if (scene.texturesEnabled) {
  45669. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45670. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  45671. return false;
  45672. }
  45673. }
  45674. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45675. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  45676. return false;
  45677. }
  45678. }
  45679. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45680. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  45681. return false;
  45682. }
  45683. }
  45684. var reflectionTexture = this._getReflectionTexture();
  45685. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45686. if (!reflectionTexture.isReadyOrNotBlocking()) {
  45687. return false;
  45688. }
  45689. }
  45690. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45691. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  45692. return false;
  45693. }
  45694. }
  45695. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45696. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  45697. return false;
  45698. }
  45699. }
  45700. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45701. if (this._metallicTexture) {
  45702. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  45703. return false;
  45704. }
  45705. }
  45706. else if (this._reflectivityTexture) {
  45707. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  45708. return false;
  45709. }
  45710. }
  45711. if (this._microSurfaceTexture) {
  45712. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  45713. return false;
  45714. }
  45715. }
  45716. }
  45717. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45718. // Bump texture cannot be not blocking.
  45719. if (!this._bumpTexture.isReady()) {
  45720. return false;
  45721. }
  45722. }
  45723. var refractionTexture = this._getRefractionTexture();
  45724. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45725. if (!refractionTexture.isReadyOrNotBlocking()) {
  45726. return false;
  45727. }
  45728. }
  45729. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45730. // This is blocking.
  45731. if (!this._environmentBRDFTexture.isReady()) {
  45732. return false;
  45733. }
  45734. }
  45735. }
  45736. }
  45737. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  45738. if (!this._imageProcessingConfiguration.isReady()) {
  45739. return false;
  45740. }
  45741. }
  45742. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  45743. mesh.createNormals(true);
  45744. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  45745. }
  45746. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  45747. if (effect) {
  45748. scene.resetCachedMaterial();
  45749. subMesh.setEffect(effect, defines);
  45750. this.buildUniformLayout();
  45751. }
  45752. if (!subMesh.effect || !subMesh.effect.isReady()) {
  45753. return false;
  45754. }
  45755. defines._renderId = scene.getRenderId();
  45756. this._wasPreviouslyReady = true;
  45757. return true;
  45758. };
  45759. /**
  45760. * Specifies if the material uses metallic roughness workflow.
  45761. * @returns boolean specifiying if the material uses metallic roughness workflow.
  45762. */
  45763. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  45764. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  45765. return true;
  45766. }
  45767. return false;
  45768. };
  45769. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  45770. if (onCompiled === void 0) { onCompiled = null; }
  45771. if (onError === void 0) { onError = null; }
  45772. if (useInstances === void 0) { useInstances = null; }
  45773. if (useClipPlane === void 0) { useClipPlane = null; }
  45774. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  45775. if (!defines.isDirty) {
  45776. return null;
  45777. }
  45778. defines.markAsProcessed();
  45779. var scene = this.getScene();
  45780. var engine = scene.getEngine();
  45781. // Fallbacks
  45782. var fallbacks = new BABYLON.EffectFallbacks();
  45783. var fallbackRank = 0;
  45784. if (defines.USESPHERICALINVERTEX) {
  45785. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  45786. }
  45787. if (defines.FOG) {
  45788. fallbacks.addFallback(fallbackRank, "FOG");
  45789. }
  45790. if (defines.SPECULARAA) {
  45791. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  45792. }
  45793. if (defines.POINTSIZE) {
  45794. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  45795. }
  45796. if (defines.LOGARITHMICDEPTH) {
  45797. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  45798. }
  45799. if (defines.PARALLAX) {
  45800. fallbacks.addFallback(fallbackRank, "PARALLAX");
  45801. }
  45802. if (defines.PARALLAXOCCLUSION) {
  45803. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  45804. }
  45805. if (defines.ENVIRONMENTBRDF) {
  45806. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  45807. }
  45808. if (defines.TANGENT) {
  45809. fallbacks.addFallback(fallbackRank++, "TANGENT");
  45810. }
  45811. if (defines.BUMP) {
  45812. fallbacks.addFallback(fallbackRank++, "BUMP");
  45813. }
  45814. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  45815. if (defines.SPECULARTERM) {
  45816. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  45817. }
  45818. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  45819. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  45820. }
  45821. if (defines.LIGHTMAP) {
  45822. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  45823. }
  45824. if (defines.NORMAL) {
  45825. fallbacks.addFallback(fallbackRank++, "NORMAL");
  45826. }
  45827. if (defines.AMBIENT) {
  45828. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  45829. }
  45830. if (defines.EMISSIVE) {
  45831. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  45832. }
  45833. if (defines.VERTEXCOLOR) {
  45834. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  45835. }
  45836. if (defines.NUM_BONE_INFLUENCERS > 0) {
  45837. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  45838. }
  45839. if (defines.MORPHTARGETS) {
  45840. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  45841. }
  45842. //Attributes
  45843. var attribs = [BABYLON.VertexBuffer.PositionKind];
  45844. if (defines.NORMAL) {
  45845. attribs.push(BABYLON.VertexBuffer.NormalKind);
  45846. }
  45847. if (defines.TANGENT) {
  45848. attribs.push(BABYLON.VertexBuffer.TangentKind);
  45849. }
  45850. if (defines.UV1) {
  45851. attribs.push(BABYLON.VertexBuffer.UVKind);
  45852. }
  45853. if (defines.UV2) {
  45854. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45855. }
  45856. if (defines.VERTEXCOLOR) {
  45857. attribs.push(BABYLON.VertexBuffer.ColorKind);
  45858. }
  45859. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  45860. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  45861. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  45862. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  45863. "vFogInfos", "vFogColor", "pointSize",
  45864. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  45865. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  45866. "mBones",
  45867. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  45868. "vLightingIntensity",
  45869. "logarithmicDepthConstant",
  45870. "vSphericalX", "vSphericalY", "vSphericalZ",
  45871. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  45872. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  45873. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  45874. "vTangentSpaceParams"
  45875. ];
  45876. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  45877. "bumpSampler", "lightmapSampler", "opacitySampler",
  45878. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  45879. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  45880. "microSurfaceSampler", "environmentBrdfSampler"];
  45881. var uniformBuffers = ["Material", "Scene"];
  45882. if (BABYLON.ImageProcessingConfiguration) {
  45883. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  45884. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  45885. }
  45886. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  45887. uniformsNames: uniforms,
  45888. uniformBuffersNames: uniformBuffers,
  45889. samplers: samplers,
  45890. defines: defines,
  45891. maxSimultaneousLights: this._maxSimultaneousLights
  45892. });
  45893. var join = defines.toString();
  45894. return engine.createEffect("pbr", {
  45895. attributes: attribs,
  45896. uniformsNames: uniforms,
  45897. uniformBuffersNames: uniformBuffers,
  45898. samplers: samplers,
  45899. defines: join,
  45900. fallbacks: fallbacks,
  45901. onCompiled: onCompiled,
  45902. onError: onError,
  45903. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  45904. }, engine);
  45905. };
  45906. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  45907. if (useInstances === void 0) { useInstances = null; }
  45908. if (useClipPlane === void 0) { useClipPlane = null; }
  45909. var scene = this.getScene();
  45910. var engine = scene.getEngine();
  45911. // Lights
  45912. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  45913. defines._needNormals = true;
  45914. // Textures
  45915. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  45916. if (defines._areTexturesDirty) {
  45917. defines._needUVs = false;
  45918. if (scene.texturesEnabled) {
  45919. if (scene.getEngine().getCaps().textureLOD) {
  45920. defines.LODBASEDMICROSFURACE = true;
  45921. }
  45922. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45923. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  45924. }
  45925. else {
  45926. defines.ALBEDO = false;
  45927. }
  45928. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45929. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  45930. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  45931. }
  45932. else {
  45933. defines.AMBIENT = false;
  45934. }
  45935. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45936. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  45937. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  45938. }
  45939. else {
  45940. defines.OPACITY = false;
  45941. }
  45942. var reflectionTexture = this._getReflectionTexture();
  45943. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45944. defines.REFLECTION = true;
  45945. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  45946. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  45947. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  45948. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  45949. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  45950. defines.INVERTCUBICMAP = true;
  45951. }
  45952. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  45953. switch (reflectionTexture.coordinatesMode) {
  45954. case BABYLON.Texture.EXPLICIT_MODE:
  45955. defines.REFLECTIONMAP_EXPLICIT = true;
  45956. break;
  45957. case BABYLON.Texture.PLANAR_MODE:
  45958. defines.REFLECTIONMAP_PLANAR = true;
  45959. break;
  45960. case BABYLON.Texture.PROJECTION_MODE:
  45961. defines.REFLECTIONMAP_PROJECTION = true;
  45962. break;
  45963. case BABYLON.Texture.SKYBOX_MODE:
  45964. defines.REFLECTIONMAP_SKYBOX = true;
  45965. break;
  45966. case BABYLON.Texture.SPHERICAL_MODE:
  45967. defines.REFLECTIONMAP_SPHERICAL = true;
  45968. break;
  45969. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  45970. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  45971. break;
  45972. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  45973. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  45974. break;
  45975. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  45976. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  45977. break;
  45978. case BABYLON.Texture.CUBIC_MODE:
  45979. case BABYLON.Texture.INVCUBIC_MODE:
  45980. default:
  45981. defines.REFLECTIONMAP_CUBIC = true;
  45982. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  45983. break;
  45984. }
  45985. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  45986. if (reflectionTexture.sphericalPolynomial) {
  45987. defines.USESPHERICALFROMREFLECTIONMAP = true;
  45988. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  45989. defines.USESPHERICALINVERTEX = false;
  45990. }
  45991. else {
  45992. defines.USESPHERICALINVERTEX = true;
  45993. }
  45994. }
  45995. }
  45996. else {
  45997. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  45998. }
  45999. }
  46000. else {
  46001. defines.REFLECTION = false;
  46002. defines.REFLECTIONMAP_3D = false;
  46003. defines.REFLECTIONMAP_SPHERICAL = false;
  46004. defines.REFLECTIONMAP_PLANAR = false;
  46005. defines.REFLECTIONMAP_CUBIC = false;
  46006. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  46007. defines.REFLECTIONMAP_PROJECTION = false;
  46008. defines.REFLECTIONMAP_SKYBOX = false;
  46009. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  46010. defines.REFLECTIONMAP_EXPLICIT = false;
  46011. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  46012. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  46013. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  46014. defines.INVERTCUBICMAP = false;
  46015. defines.USESPHERICALFROMREFLECTIONMAP = false;
  46016. defines.USESPHERICALINVERTEX = false;
  46017. defines.REFLECTIONMAP_OPPOSITEZ = false;
  46018. defines.LODINREFLECTIONALPHA = false;
  46019. defines.GAMMAREFLECTION = false;
  46020. defines.RGBDREFLECTION = false;
  46021. }
  46022. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  46023. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  46024. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  46025. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  46026. }
  46027. else {
  46028. defines.LIGHTMAP = false;
  46029. }
  46030. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  46031. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  46032. }
  46033. else {
  46034. defines.EMISSIVE = false;
  46035. }
  46036. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  46037. if (this._metallicTexture) {
  46038. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  46039. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  46040. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  46041. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  46042. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  46043. }
  46044. else if (this._reflectivityTexture) {
  46045. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  46046. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  46047. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  46048. }
  46049. else {
  46050. defines.REFLECTIVITY = false;
  46051. }
  46052. if (this._microSurfaceTexture) {
  46053. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  46054. }
  46055. else {
  46056. defines.MICROSURFACEMAP = false;
  46057. }
  46058. }
  46059. else {
  46060. defines.REFLECTIVITY = false;
  46061. defines.MICROSURFACEMAP = false;
  46062. }
  46063. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  46064. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  46065. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  46066. defines.PARALLAX = true;
  46067. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  46068. }
  46069. else {
  46070. defines.PARALLAX = false;
  46071. }
  46072. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  46073. }
  46074. else {
  46075. defines.BUMP = false;
  46076. }
  46077. var refractionTexture = this._getRefractionTexture();
  46078. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  46079. defines.REFRACTION = true;
  46080. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  46081. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  46082. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  46083. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  46084. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  46085. if (this._linkRefractionWithTransparency) {
  46086. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  46087. }
  46088. }
  46089. else {
  46090. defines.REFRACTION = false;
  46091. }
  46092. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46093. defines.ENVIRONMENTBRDF = true;
  46094. }
  46095. else {
  46096. defines.ENVIRONMENTBRDF = false;
  46097. }
  46098. if (this._shouldUseAlphaFromAlbedoTexture()) {
  46099. defines.ALPHAFROMALBEDO = true;
  46100. }
  46101. else {
  46102. defines.ALPHAFROMALBEDO = false;
  46103. }
  46104. }
  46105. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  46106. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  46107. defines.USEPHYSICALLIGHTFALLOFF = false;
  46108. defines.USEGLTFLIGHTFALLOFF = false;
  46109. }
  46110. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  46111. defines.USEPHYSICALLIGHTFALLOFF = false;
  46112. defines.USEGLTFLIGHTFALLOFF = true;
  46113. }
  46114. else {
  46115. defines.USEPHYSICALLIGHTFALLOFF = true;
  46116. defines.USEGLTFLIGHTFALLOFF = false;
  46117. }
  46118. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  46119. if (!this.backFaceCulling && this._twoSidedLighting) {
  46120. defines.TWOSIDEDLIGHTING = true;
  46121. }
  46122. else {
  46123. defines.TWOSIDEDLIGHTING = false;
  46124. }
  46125. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  46126. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  46127. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  46128. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  46129. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  46130. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  46131. }
  46132. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  46133. this._imageProcessingConfiguration.prepareDefines(defines);
  46134. }
  46135. defines.FORCENORMALFORWARD = this._forceNormalForward;
  46136. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  46137. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  46138. // Misc.
  46139. if (defines._areMiscDirty) {
  46140. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  46141. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  46142. }
  46143. // Values that need to be evaluated on every frame
  46144. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  46145. // Attribs
  46146. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  46147. };
  46148. /**
  46149. * Force shader compilation
  46150. */
  46151. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  46152. var _this = this;
  46153. var localOptions = __assign({ clipPlane: false }, options);
  46154. var defines = new PBRMaterialDefines();
  46155. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  46156. if (effect.isReady()) {
  46157. if (onCompiled) {
  46158. onCompiled(this);
  46159. }
  46160. }
  46161. else {
  46162. effect.onCompileObservable.add(function () {
  46163. if (onCompiled) {
  46164. onCompiled(_this);
  46165. }
  46166. });
  46167. }
  46168. };
  46169. /**
  46170. * Initializes the uniform buffer layout for the shader.
  46171. */
  46172. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  46173. // Order is important !
  46174. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  46175. this._uniformBuffer.addUniform("vAmbientInfos", 4);
  46176. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  46177. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  46178. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  46179. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  46180. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  46181. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  46182. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  46183. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  46184. this._uniformBuffer.addUniform("vReflectionSize", 3);
  46185. this._uniformBuffer.addUniform("vBumpInfos", 3);
  46186. this._uniformBuffer.addUniform("albedoMatrix", 16);
  46187. this._uniformBuffer.addUniform("ambientMatrix", 16);
  46188. this._uniformBuffer.addUniform("opacityMatrix", 16);
  46189. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  46190. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  46191. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  46192. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  46193. this._uniformBuffer.addUniform("bumpMatrix", 16);
  46194. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  46195. this._uniformBuffer.addUniform("refractionMatrix", 16);
  46196. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  46197. this._uniformBuffer.addUniform("vReflectionColor", 3);
  46198. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  46199. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  46200. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  46201. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  46202. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  46203. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  46204. this._uniformBuffer.addUniform("pointSize", 1);
  46205. this._uniformBuffer.create();
  46206. };
  46207. /**
  46208. * Unbinds the textures.
  46209. */
  46210. PBRBaseMaterial.prototype.unbind = function () {
  46211. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  46212. this._uniformBuffer.setTexture("reflectionSampler", null);
  46213. }
  46214. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  46215. this._uniformBuffer.setTexture("refractionSampler", null);
  46216. }
  46217. _super.prototype.unbind.call(this);
  46218. };
  46219. /**
  46220. * Binds the submesh data.
  46221. * @param world - The world matrix.
  46222. * @param mesh - The BJS mesh.
  46223. * @param subMesh - A submesh of the BJS mesh.
  46224. */
  46225. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  46226. var scene = this.getScene();
  46227. var defines = subMesh._materialDefines;
  46228. if (!defines) {
  46229. return;
  46230. }
  46231. var effect = subMesh.effect;
  46232. if (!effect) {
  46233. return;
  46234. }
  46235. this._activeEffect = effect;
  46236. // Matrices
  46237. this.bindOnlyWorldMatrix(world);
  46238. // Normal Matrix
  46239. if (defines.OBJECTSPACE_NORMALMAP) {
  46240. world.toNormalMatrix(this._normalMatrix);
  46241. this.bindOnlyNormalMatrix(this._normalMatrix);
  46242. }
  46243. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  46244. // Bones
  46245. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  46246. var reflectionTexture = null;
  46247. if (mustRebind) {
  46248. this._uniformBuffer.bindToEffect(effect, "Material");
  46249. this.bindViewProjection(effect);
  46250. reflectionTexture = this._getReflectionTexture();
  46251. var refractionTexture = this._getRefractionTexture();
  46252. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  46253. // Texture uniforms
  46254. if (scene.texturesEnabled) {
  46255. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  46256. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  46257. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  46258. }
  46259. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  46260. this._uniformBuffer.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
  46261. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  46262. }
  46263. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  46264. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  46265. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  46266. }
  46267. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46268. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  46269. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  46270. if (reflectionTexture.boundingBoxSize) {
  46271. var cubeTexture = reflectionTexture;
  46272. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  46273. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  46274. }
  46275. var polynomials = reflectionTexture.sphericalPolynomial;
  46276. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  46277. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  46278. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  46279. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  46280. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  46281. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  46282. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  46283. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  46284. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  46285. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  46286. }
  46287. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  46288. }
  46289. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  46290. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  46291. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  46292. }
  46293. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  46294. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  46295. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  46296. }
  46297. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  46298. if (this._metallicTexture) {
  46299. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  46300. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  46301. }
  46302. else if (this._reflectivityTexture) {
  46303. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  46304. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  46305. }
  46306. if (this._microSurfaceTexture) {
  46307. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  46308. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  46309. }
  46310. }
  46311. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  46312. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  46313. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  46314. if (scene._mirroredCameraPosition) {
  46315. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  46316. }
  46317. else {
  46318. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  46319. }
  46320. }
  46321. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  46322. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  46323. var depth = 1.0;
  46324. if (!refractionTexture.isCube) {
  46325. if (refractionTexture.depth) {
  46326. depth = refractionTexture.depth;
  46327. }
  46328. }
  46329. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  46330. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  46331. }
  46332. }
  46333. // Point size
  46334. if (this.pointsCloud) {
  46335. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  46336. }
  46337. // Colors
  46338. if (defines.METALLICWORKFLOW) {
  46339. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  46340. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  46341. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  46342. }
  46343. else {
  46344. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  46345. }
  46346. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  46347. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  46348. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  46349. // Misc
  46350. this._lightingInfos.x = this._directIntensity;
  46351. this._lightingInfos.y = this._emissiveIntensity;
  46352. this._lightingInfos.z = this._environmentIntensity;
  46353. this._lightingInfos.w = this._specularIntensity;
  46354. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  46355. }
  46356. // Textures
  46357. if (scene.texturesEnabled) {
  46358. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  46359. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  46360. }
  46361. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  46362. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  46363. }
  46364. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  46365. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  46366. }
  46367. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46368. if (defines.LODBASEDMICROSFURACE) {
  46369. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  46370. }
  46371. else {
  46372. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  46373. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  46374. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  46375. }
  46376. }
  46377. if (defines.ENVIRONMENTBRDF) {
  46378. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  46379. }
  46380. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  46381. if (defines.LODBASEDMICROSFURACE) {
  46382. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  46383. }
  46384. else {
  46385. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  46386. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  46387. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  46388. }
  46389. }
  46390. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  46391. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  46392. }
  46393. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  46394. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  46395. }
  46396. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  46397. if (this._metallicTexture) {
  46398. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  46399. }
  46400. else if (this._reflectivityTexture) {
  46401. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  46402. }
  46403. if (this._microSurfaceTexture) {
  46404. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  46405. }
  46406. }
  46407. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  46408. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  46409. }
  46410. }
  46411. // Clip plane
  46412. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  46413. // Colors
  46414. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  46415. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  46416. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  46417. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  46418. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  46419. }
  46420. if (mustRebind || !this.isFrozen) {
  46421. // Lights
  46422. if (scene.lightsEnabled && !this._disableLighting) {
  46423. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
  46424. }
  46425. // View
  46426. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  46427. this.bindView(effect);
  46428. }
  46429. // Fog
  46430. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  46431. // Morph targets
  46432. if (defines.NUM_MORPH_INFLUENCERS) {
  46433. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  46434. }
  46435. // image processing
  46436. this._imageProcessingConfiguration.bind(this._activeEffect);
  46437. // Log. depth
  46438. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  46439. }
  46440. this._uniformBuffer.update();
  46441. this._afterBind(mesh, this._activeEffect);
  46442. };
  46443. /**
  46444. * Returns the animatable textures.
  46445. * @returns - Array of animatable textures.
  46446. */
  46447. PBRBaseMaterial.prototype.getAnimatables = function () {
  46448. var results = [];
  46449. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  46450. results.push(this._albedoTexture);
  46451. }
  46452. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  46453. results.push(this._ambientTexture);
  46454. }
  46455. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  46456. results.push(this._opacityTexture);
  46457. }
  46458. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  46459. results.push(this._reflectionTexture);
  46460. }
  46461. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  46462. results.push(this._emissiveTexture);
  46463. }
  46464. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  46465. results.push(this._metallicTexture);
  46466. }
  46467. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  46468. results.push(this._reflectivityTexture);
  46469. }
  46470. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  46471. results.push(this._bumpTexture);
  46472. }
  46473. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  46474. results.push(this._lightmapTexture);
  46475. }
  46476. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  46477. results.push(this._refractionTexture);
  46478. }
  46479. return results;
  46480. };
  46481. /**
  46482. * Returns the texture used for reflections.
  46483. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  46484. */
  46485. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  46486. if (this._reflectionTexture) {
  46487. return this._reflectionTexture;
  46488. }
  46489. return this.getScene().environmentTexture;
  46490. };
  46491. /**
  46492. * Returns the texture used for refraction or null if none is used.
  46493. * @returns - Refection texture if present. If no refraction texture and refraction
  46494. * is linked with transparency, returns environment texture. Otherwise, returns null.
  46495. */
  46496. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  46497. if (this._refractionTexture) {
  46498. return this._refractionTexture;
  46499. }
  46500. if (this._linkRefractionWithTransparency) {
  46501. return this.getScene().environmentTexture;
  46502. }
  46503. return null;
  46504. };
  46505. /**
  46506. * Disposes the resources of the material.
  46507. * @param forceDisposeEffect - Forces the disposal of effects.
  46508. * @param forceDisposeTextures - Forces the disposal of all textures.
  46509. */
  46510. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  46511. if (forceDisposeTextures) {
  46512. if (this._albedoTexture) {
  46513. this._albedoTexture.dispose();
  46514. }
  46515. if (this._ambientTexture) {
  46516. this._ambientTexture.dispose();
  46517. }
  46518. if (this._opacityTexture) {
  46519. this._opacityTexture.dispose();
  46520. }
  46521. if (this._reflectionTexture) {
  46522. this._reflectionTexture.dispose();
  46523. }
  46524. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  46525. this._environmentBRDFTexture.dispose();
  46526. }
  46527. if (this._emissiveTexture) {
  46528. this._emissiveTexture.dispose();
  46529. }
  46530. if (this._metallicTexture) {
  46531. this._metallicTexture.dispose();
  46532. }
  46533. if (this._reflectivityTexture) {
  46534. this._reflectivityTexture.dispose();
  46535. }
  46536. if (this._bumpTexture) {
  46537. this._bumpTexture.dispose();
  46538. }
  46539. if (this._lightmapTexture) {
  46540. this._lightmapTexture.dispose();
  46541. }
  46542. if (this._refractionTexture) {
  46543. this._refractionTexture.dispose();
  46544. }
  46545. }
  46546. this._renderTargets.dispose();
  46547. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  46548. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  46549. }
  46550. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  46551. };
  46552. /**
  46553. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  46554. */
  46555. PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
  46556. /**
  46557. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  46558. * to enhance interoperability with other engines.
  46559. */
  46560. PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
  46561. /**
  46562. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  46563. * to enhance interoperability with other materials.
  46564. */
  46565. PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
  46566. /**
  46567. * Stores the reflectivity values based on metallic roughness workflow.
  46568. */
  46569. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  46570. __decorate([
  46571. BABYLON.serializeAsImageProcessingConfiguration()
  46572. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  46573. __decorate([
  46574. BABYLON.serialize()
  46575. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  46576. __decorate([
  46577. BABYLON.serialize()
  46578. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  46579. return PBRBaseMaterial;
  46580. }(BABYLON.PushMaterial));
  46581. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  46582. })(BABYLON || (BABYLON = {}));
  46583. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  46584. var BABYLON;
  46585. (function (BABYLON) {
  46586. /**
  46587. * The Physically based simple base material of BJS.
  46588. *
  46589. * This enables better naming and convention enforcements on top of the pbrMaterial.
  46590. * It is used as the base class for both the specGloss and metalRough conventions.
  46591. */
  46592. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  46593. __extends(PBRBaseSimpleMaterial, _super);
  46594. /**
  46595. * Instantiates a new PBRMaterial instance.
  46596. *
  46597. * @param name The material name
  46598. * @param scene The scene the material will be use in.
  46599. */
  46600. function PBRBaseSimpleMaterial(name, scene) {
  46601. var _this = _super.call(this, name, scene) || this;
  46602. /**
  46603. * Number of Simultaneous lights allowed on the material.
  46604. */
  46605. _this.maxSimultaneousLights = 4;
  46606. /**
  46607. * If sets to true, disables all the lights affecting the material.
  46608. */
  46609. _this.disableLighting = false;
  46610. /**
  46611. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46612. */
  46613. _this.invertNormalMapX = false;
  46614. /**
  46615. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46616. */
  46617. _this.invertNormalMapY = false;
  46618. /**
  46619. * Emissivie color used to self-illuminate the model.
  46620. */
  46621. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  46622. /**
  46623. * Occlusion Channel Strenght.
  46624. */
  46625. _this.occlusionStrength = 1.0;
  46626. /**
  46627. * If true, the light map contains occlusion information instead of lighting info.
  46628. */
  46629. _this.useLightmapAsShadowmap = false;
  46630. _this._useAlphaFromAlbedoTexture = true;
  46631. _this._useAmbientInGrayScale = true;
  46632. return _this;
  46633. }
  46634. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  46635. /**
  46636. * Gets the current double sided mode.
  46637. */
  46638. get: function () {
  46639. return this._twoSidedLighting;
  46640. },
  46641. /**
  46642. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46643. */
  46644. set: function (value) {
  46645. if (this._twoSidedLighting === value) {
  46646. return;
  46647. }
  46648. this._twoSidedLighting = value;
  46649. this.backFaceCulling = !value;
  46650. this._markAllSubMeshesAsTexturesDirty();
  46651. },
  46652. enumerable: true,
  46653. configurable: true
  46654. });
  46655. /**
  46656. * Return the active textures of the material.
  46657. */
  46658. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  46659. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46660. if (this.environmentTexture) {
  46661. activeTextures.push(this.environmentTexture);
  46662. }
  46663. if (this.normalTexture) {
  46664. activeTextures.push(this.normalTexture);
  46665. }
  46666. if (this.emissiveTexture) {
  46667. activeTextures.push(this.emissiveTexture);
  46668. }
  46669. if (this.occlusionTexture) {
  46670. activeTextures.push(this.occlusionTexture);
  46671. }
  46672. if (this.lightmapTexture) {
  46673. activeTextures.push(this.lightmapTexture);
  46674. }
  46675. return activeTextures;
  46676. };
  46677. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  46678. if (_super.prototype.hasTexture.call(this, texture)) {
  46679. return true;
  46680. }
  46681. if (this.lightmapTexture === texture) {
  46682. return true;
  46683. }
  46684. return false;
  46685. };
  46686. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  46687. return "PBRBaseSimpleMaterial";
  46688. };
  46689. __decorate([
  46690. BABYLON.serialize(),
  46691. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46692. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  46693. __decorate([
  46694. BABYLON.serialize(),
  46695. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46696. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  46697. __decorate([
  46698. BABYLON.serializeAsTexture(),
  46699. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  46700. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  46701. __decorate([
  46702. BABYLON.serialize(),
  46703. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46704. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  46705. __decorate([
  46706. BABYLON.serialize(),
  46707. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46708. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  46709. __decorate([
  46710. BABYLON.serializeAsTexture(),
  46711. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  46712. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  46713. __decorate([
  46714. BABYLON.serializeAsColor3("emissive"),
  46715. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46716. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  46717. __decorate([
  46718. BABYLON.serializeAsTexture(),
  46719. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46720. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  46721. __decorate([
  46722. BABYLON.serialize(),
  46723. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  46724. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  46725. __decorate([
  46726. BABYLON.serializeAsTexture(),
  46727. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  46728. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  46729. __decorate([
  46730. BABYLON.serialize(),
  46731. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  46732. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  46733. __decorate([
  46734. BABYLON.serialize()
  46735. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  46736. __decorate([
  46737. BABYLON.serializeAsTexture(),
  46738. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46739. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  46740. __decorate([
  46741. BABYLON.serialize(),
  46742. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46743. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46744. return PBRBaseSimpleMaterial;
  46745. }(BABYLON.PBRBaseMaterial));
  46746. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  46747. })(BABYLON || (BABYLON = {}));
  46748. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  46749. var BABYLON;
  46750. (function (BABYLON) {
  46751. /**
  46752. * The Physically based material of BJS.
  46753. *
  46754. * This offers the main features of a standard PBR material.
  46755. * For more information, please refer to the documentation :
  46756. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  46757. */
  46758. var PBRMaterial = /** @class */ (function (_super) {
  46759. __extends(PBRMaterial, _super);
  46760. /**
  46761. * Instantiates a new PBRMaterial instance.
  46762. *
  46763. * @param name The material name
  46764. * @param scene The scene the material will be use in.
  46765. */
  46766. function PBRMaterial(name, scene) {
  46767. var _this = _super.call(this, name, scene) || this;
  46768. /**
  46769. * Intensity of the direct lights e.g. the four lights available in your scene.
  46770. * This impacts both the direct diffuse and specular highlights.
  46771. */
  46772. _this.directIntensity = 1.0;
  46773. /**
  46774. * Intensity of the emissive part of the material.
  46775. * This helps controlling the emissive effect without modifying the emissive color.
  46776. */
  46777. _this.emissiveIntensity = 1.0;
  46778. /**
  46779. * Intensity of the environment e.g. how much the environment will light the object
  46780. * either through harmonics for rough material or through the refelction for shiny ones.
  46781. */
  46782. _this.environmentIntensity = 1.0;
  46783. /**
  46784. * This is a special control allowing the reduction of the specular highlights coming from the
  46785. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  46786. */
  46787. _this.specularIntensity = 1.0;
  46788. /**
  46789. * Debug Control allowing disabling the bump map on this material.
  46790. */
  46791. _this.disableBumpMap = false;
  46792. /**
  46793. * AKA Occlusion Texture Intensity in other nomenclature.
  46794. */
  46795. _this.ambientTextureStrength = 1.0;
  46796. /**
  46797. * Defines how much the AO map is occluding the analytical lights (point spot...).
  46798. * 1 means it completely occludes it
  46799. * 0 mean it has no impact
  46800. */
  46801. _this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  46802. /**
  46803. * The color of a material in ambient lighting.
  46804. */
  46805. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  46806. /**
  46807. * AKA Diffuse Color in other nomenclature.
  46808. */
  46809. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  46810. /**
  46811. * AKA Specular Color in other nomenclature.
  46812. */
  46813. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  46814. /**
  46815. * The color reflected from the material.
  46816. */
  46817. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  46818. /**
  46819. * The color emitted from the material.
  46820. */
  46821. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  46822. /**
  46823. * AKA Glossiness in other nomenclature.
  46824. */
  46825. _this.microSurface = 1.0;
  46826. /**
  46827. * source material index of refraction (IOR)' / 'destination material IOR.
  46828. */
  46829. _this.indexOfRefraction = 0.66;
  46830. /**
  46831. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  46832. */
  46833. _this.invertRefractionY = false;
  46834. /**
  46835. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  46836. * Materials half opaque for instance using refraction could benefit from this control.
  46837. */
  46838. _this.linkRefractionWithTransparency = false;
  46839. /**
  46840. * If true, the light map contains occlusion information instead of lighting info.
  46841. */
  46842. _this.useLightmapAsShadowmap = false;
  46843. /**
  46844. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  46845. */
  46846. _this.useAlphaFromAlbedoTexture = false;
  46847. /**
  46848. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  46849. */
  46850. _this.forceAlphaTest = false;
  46851. /**
  46852. * Defines the alpha limits in alpha test mode.
  46853. */
  46854. _this.alphaCutOff = 0.4;
  46855. /**
  46856. * Specifies that the material will keep the specular highlights over a transparent surface (only the most limunous ones).
  46857. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  46858. */
  46859. _this.useSpecularOverAlpha = true;
  46860. /**
  46861. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  46862. */
  46863. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  46864. /**
  46865. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  46866. */
  46867. _this.useRoughnessFromMetallicTextureAlpha = true;
  46868. /**
  46869. * Specifies if the metallic texture contains the roughness information in its green channel.
  46870. */
  46871. _this.useRoughnessFromMetallicTextureGreen = false;
  46872. /**
  46873. * Specifies if the metallic texture contains the metallness information in its blue channel.
  46874. */
  46875. _this.useMetallnessFromMetallicTextureBlue = false;
  46876. /**
  46877. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  46878. */
  46879. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  46880. /**
  46881. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  46882. */
  46883. _this.useAmbientInGrayScale = false;
  46884. /**
  46885. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  46886. * The material will try to infer what glossiness each pixel should be.
  46887. */
  46888. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  46889. /**
  46890. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  46891. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  46892. */
  46893. _this.useRadianceOverAlpha = true;
  46894. /**
  46895. * Allows using an object space normal map (instead of tangent space).
  46896. */
  46897. _this.useObjectSpaceNormalMap = false;
  46898. /**
  46899. * Allows using the bump map in parallax mode.
  46900. */
  46901. _this.useParallax = false;
  46902. /**
  46903. * Allows using the bump map in parallax occlusion mode.
  46904. */
  46905. _this.useParallaxOcclusion = false;
  46906. /**
  46907. * Controls the scale bias of the parallax mode.
  46908. */
  46909. _this.parallaxScaleBias = 0.05;
  46910. /**
  46911. * If sets to true, disables all the lights affecting the material.
  46912. */
  46913. _this.disableLighting = false;
  46914. /**
  46915. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  46916. */
  46917. _this.forceIrradianceInFragment = false;
  46918. /**
  46919. * Number of Simultaneous lights allowed on the material.
  46920. */
  46921. _this.maxSimultaneousLights = 4;
  46922. /**
  46923. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46924. */
  46925. _this.invertNormalMapX = false;
  46926. /**
  46927. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46928. */
  46929. _this.invertNormalMapY = false;
  46930. /**
  46931. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46932. */
  46933. _this.twoSidedLighting = false;
  46934. /**
  46935. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46936. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  46937. */
  46938. _this.useAlphaFresnel = false;
  46939. /**
  46940. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46941. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  46942. */
  46943. _this.useLinearAlphaFresnel = false;
  46944. /**
  46945. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46946. * And/Or occlude the blended part.
  46947. */
  46948. _this.environmentBRDFTexture = null;
  46949. /**
  46950. * Force normal to face away from face.
  46951. */
  46952. _this.forceNormalForward = false;
  46953. /**
  46954. * Enables specular anti aliasing in the PBR shader.
  46955. * It will both interacts on the Geometry for analytical and IBL lighting.
  46956. * It also prefilter the roughness map based on the bump values.
  46957. */
  46958. _this.enableSpecularAntiAliasing = false;
  46959. /**
  46960. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  46961. * makes the reflect vector face the model (under horizon).
  46962. */
  46963. _this.useHorizonOcclusion = true;
  46964. /**
  46965. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  46966. * too much the area relying on ambient texture to define their ambient occlusion.
  46967. */
  46968. _this.useRadianceOcclusion = true;
  46969. /**
  46970. * If set to true, no lighting calculations will be applied.
  46971. */
  46972. _this.unlit = false;
  46973. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  46974. return _this;
  46975. }
  46976. Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
  46977. /**
  46978. * BJS is using an harcoded light falloff based on a manually sets up range.
  46979. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  46980. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  46981. */
  46982. get: function () {
  46983. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  46984. },
  46985. /**
  46986. * BJS is using an harcoded light falloff based on a manually sets up range.
  46987. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  46988. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  46989. */
  46990. set: function (value) {
  46991. if (value !== this.usePhysicalLightFalloff) {
  46992. // Ensure the effect will be rebuilt.
  46993. this._markAllSubMeshesAsTexturesDirty();
  46994. if (value) {
  46995. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  46996. }
  46997. else {
  46998. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  46999. }
  47000. }
  47001. },
  47002. enumerable: true,
  47003. configurable: true
  47004. });
  47005. Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
  47006. /**
  47007. * In order to support the falloff compatibility with gltf, a special mode has been added
  47008. * to reproduce the gltf light falloff.
  47009. */
  47010. get: function () {
  47011. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  47012. },
  47013. /**
  47014. * In order to support the falloff compatibility with gltf, a special mode has been added
  47015. * to reproduce the gltf light falloff.
  47016. */
  47017. set: function (value) {
  47018. if (value !== this.useGLTFLightFalloff) {
  47019. // Ensure the effect will be rebuilt.
  47020. this._markAllSubMeshesAsTexturesDirty();
  47021. if (value) {
  47022. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  47023. }
  47024. else {
  47025. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  47026. }
  47027. }
  47028. },
  47029. enumerable: true,
  47030. configurable: true
  47031. });
  47032. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  47033. /**
  47034. * Gets the image processing configuration used either in this material.
  47035. */
  47036. get: function () {
  47037. return this._imageProcessingConfiguration;
  47038. },
  47039. /**
  47040. * Sets the Default image processing configuration used either in the this material.
  47041. *
  47042. * If sets to null, the scene one is in use.
  47043. */
  47044. set: function (value) {
  47045. this._attachImageProcessingConfiguration(value);
  47046. // Ensure the effect will be rebuilt.
  47047. this._markAllSubMeshesAsTexturesDirty();
  47048. },
  47049. enumerable: true,
  47050. configurable: true
  47051. });
  47052. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  47053. /**
  47054. * Gets wether the color curves effect is enabled.
  47055. */
  47056. get: function () {
  47057. return this.imageProcessingConfiguration.colorCurvesEnabled;
  47058. },
  47059. /**
  47060. * Sets wether the color curves effect is enabled.
  47061. */
  47062. set: function (value) {
  47063. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  47064. },
  47065. enumerable: true,
  47066. configurable: true
  47067. });
  47068. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  47069. /**
  47070. * Gets wether the color grading effect is enabled.
  47071. */
  47072. get: function () {
  47073. return this.imageProcessingConfiguration.colorGradingEnabled;
  47074. },
  47075. /**
  47076. * Gets wether the color grading effect is enabled.
  47077. */
  47078. set: function (value) {
  47079. this.imageProcessingConfiguration.colorGradingEnabled = value;
  47080. },
  47081. enumerable: true,
  47082. configurable: true
  47083. });
  47084. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  47085. /**
  47086. * Gets wether tonemapping is enabled or not.
  47087. */
  47088. get: function () {
  47089. return this._imageProcessingConfiguration.toneMappingEnabled;
  47090. },
  47091. /**
  47092. * Sets wether tonemapping is enabled or not
  47093. */
  47094. set: function (value) {
  47095. this._imageProcessingConfiguration.toneMappingEnabled = value;
  47096. },
  47097. enumerable: true,
  47098. configurable: true
  47099. });
  47100. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  47101. /**
  47102. * The camera exposure used on this material.
  47103. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  47104. * This corresponds to a photographic exposure.
  47105. */
  47106. get: function () {
  47107. return this._imageProcessingConfiguration.exposure;
  47108. },
  47109. /**
  47110. * The camera exposure used on this material.
  47111. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  47112. * This corresponds to a photographic exposure.
  47113. */
  47114. set: function (value) {
  47115. this._imageProcessingConfiguration.exposure = value;
  47116. },
  47117. enumerable: true,
  47118. configurable: true
  47119. });
  47120. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  47121. /**
  47122. * Gets The camera contrast used on this material.
  47123. */
  47124. get: function () {
  47125. return this._imageProcessingConfiguration.contrast;
  47126. },
  47127. /**
  47128. * Sets The camera contrast used on this material.
  47129. */
  47130. set: function (value) {
  47131. this._imageProcessingConfiguration.contrast = value;
  47132. },
  47133. enumerable: true,
  47134. configurable: true
  47135. });
  47136. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  47137. /**
  47138. * Gets the Color Grading 2D Lookup Texture.
  47139. */
  47140. get: function () {
  47141. return this._imageProcessingConfiguration.colorGradingTexture;
  47142. },
  47143. /**
  47144. * Sets the Color Grading 2D Lookup Texture.
  47145. */
  47146. set: function (value) {
  47147. this._imageProcessingConfiguration.colorGradingTexture = value;
  47148. },
  47149. enumerable: true,
  47150. configurable: true
  47151. });
  47152. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  47153. /**
  47154. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  47155. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  47156. * 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;
  47157. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  47158. */
  47159. get: function () {
  47160. return this._imageProcessingConfiguration.colorCurves;
  47161. },
  47162. /**
  47163. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  47164. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  47165. * 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;
  47166. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  47167. */
  47168. set: function (value) {
  47169. this._imageProcessingConfiguration.colorCurves = value;
  47170. },
  47171. enumerable: true,
  47172. configurable: true
  47173. });
  47174. /**
  47175. * Returns the name of this material class.
  47176. */
  47177. PBRMaterial.prototype.getClassName = function () {
  47178. return "PBRMaterial";
  47179. };
  47180. /**
  47181. * Returns an array of the actively used textures.
  47182. * @returns - Array of BaseTextures
  47183. */
  47184. PBRMaterial.prototype.getActiveTextures = function () {
  47185. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47186. if (this._albedoTexture) {
  47187. activeTextures.push(this._albedoTexture);
  47188. }
  47189. if (this._ambientTexture) {
  47190. activeTextures.push(this._ambientTexture);
  47191. }
  47192. if (this._opacityTexture) {
  47193. activeTextures.push(this._opacityTexture);
  47194. }
  47195. if (this._reflectionTexture) {
  47196. activeTextures.push(this._reflectionTexture);
  47197. }
  47198. if (this._emissiveTexture) {
  47199. activeTextures.push(this._emissiveTexture);
  47200. }
  47201. if (this._reflectivityTexture) {
  47202. activeTextures.push(this._reflectivityTexture);
  47203. }
  47204. if (this._metallicTexture) {
  47205. activeTextures.push(this._metallicTexture);
  47206. }
  47207. if (this._microSurfaceTexture) {
  47208. activeTextures.push(this._microSurfaceTexture);
  47209. }
  47210. if (this._bumpTexture) {
  47211. activeTextures.push(this._bumpTexture);
  47212. }
  47213. if (this._lightmapTexture) {
  47214. activeTextures.push(this._lightmapTexture);
  47215. }
  47216. if (this._refractionTexture) {
  47217. activeTextures.push(this._refractionTexture);
  47218. }
  47219. return activeTextures;
  47220. };
  47221. /**
  47222. * Checks to see if a texture is used in the material.
  47223. * @param texture - Base texture to use.
  47224. * @returns - Boolean specifying if a texture is used in the material.
  47225. */
  47226. PBRMaterial.prototype.hasTexture = function (texture) {
  47227. if (_super.prototype.hasTexture.call(this, texture)) {
  47228. return true;
  47229. }
  47230. if (this._albedoTexture === texture) {
  47231. return true;
  47232. }
  47233. if (this._ambientTexture === texture) {
  47234. return true;
  47235. }
  47236. if (this._opacityTexture === texture) {
  47237. return true;
  47238. }
  47239. if (this._reflectionTexture === texture) {
  47240. return true;
  47241. }
  47242. if (this._reflectivityTexture === texture) {
  47243. return true;
  47244. }
  47245. if (this._metallicTexture === texture) {
  47246. return true;
  47247. }
  47248. if (this._microSurfaceTexture === texture) {
  47249. return true;
  47250. }
  47251. if (this._bumpTexture === texture) {
  47252. return true;
  47253. }
  47254. if (this._lightmapTexture === texture) {
  47255. return true;
  47256. }
  47257. if (this._refractionTexture === texture) {
  47258. return true;
  47259. }
  47260. return false;
  47261. };
  47262. /**
  47263. * Makes a duplicate of the current material.
  47264. * @param name - name to use for the new material.
  47265. */
  47266. PBRMaterial.prototype.clone = function (name) {
  47267. var _this = this;
  47268. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  47269. clone.id = name;
  47270. clone.name = name;
  47271. return clone;
  47272. };
  47273. /**
  47274. * Serializes this PBR Material.
  47275. * @returns - An object with the serialized material.
  47276. */
  47277. PBRMaterial.prototype.serialize = function () {
  47278. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47279. serializationObject.customType = "BABYLON.PBRMaterial";
  47280. return serializationObject;
  47281. };
  47282. // Statics
  47283. /**
  47284. * Parses a PBR Material from a serialized object.
  47285. * @param source - Serialized object.
  47286. * @param scene - BJS scene instance.
  47287. * @param rootUrl - url for the scene object
  47288. * @returns - PBRMaterial
  47289. */
  47290. PBRMaterial.Parse = function (source, scene, rootUrl) {
  47291. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  47292. };
  47293. /**
  47294. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  47295. */
  47296. PBRMaterial.PBRMATERIAL_OPAQUE = 0;
  47297. /**
  47298. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  47299. */
  47300. PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
  47301. /**
  47302. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  47303. */
  47304. PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
  47305. /**
  47306. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  47307. * They are also discarded below the alpha cutoff threshold to improve performances.
  47308. */
  47309. PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
  47310. /**
  47311. * Defines the default value of how much AO map is occluding the analytical lights
  47312. * (point spot...).
  47313. */
  47314. PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 1;
  47315. __decorate([
  47316. BABYLON.serialize(),
  47317. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47318. ], PBRMaterial.prototype, "directIntensity", void 0);
  47319. __decorate([
  47320. BABYLON.serialize(),
  47321. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47322. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  47323. __decorate([
  47324. BABYLON.serialize(),
  47325. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47326. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  47327. __decorate([
  47328. BABYLON.serialize(),
  47329. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47330. ], PBRMaterial.prototype, "specularIntensity", void 0);
  47331. __decorate([
  47332. BABYLON.serialize(),
  47333. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47334. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  47335. __decorate([
  47336. BABYLON.serializeAsTexture(),
  47337. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47338. ], PBRMaterial.prototype, "albedoTexture", void 0);
  47339. __decorate([
  47340. BABYLON.serializeAsTexture(),
  47341. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47342. ], PBRMaterial.prototype, "ambientTexture", void 0);
  47343. __decorate([
  47344. BABYLON.serialize(),
  47345. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47346. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  47347. __decorate([
  47348. BABYLON.serialize(),
  47349. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47350. ], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0);
  47351. __decorate([
  47352. BABYLON.serializeAsTexture(),
  47353. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  47354. ], PBRMaterial.prototype, "opacityTexture", void 0);
  47355. __decorate([
  47356. BABYLON.serializeAsTexture(),
  47357. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47358. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  47359. __decorate([
  47360. BABYLON.serializeAsTexture(),
  47361. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47362. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  47363. __decorate([
  47364. BABYLON.serializeAsTexture(),
  47365. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47366. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  47367. __decorate([
  47368. BABYLON.serializeAsTexture(),
  47369. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47370. ], PBRMaterial.prototype, "metallicTexture", void 0);
  47371. __decorate([
  47372. BABYLON.serialize(),
  47373. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47374. ], PBRMaterial.prototype, "metallic", void 0);
  47375. __decorate([
  47376. BABYLON.serialize(),
  47377. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47378. ], PBRMaterial.prototype, "roughness", void 0);
  47379. __decorate([
  47380. BABYLON.serializeAsTexture(),
  47381. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47382. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  47383. __decorate([
  47384. BABYLON.serializeAsTexture(),
  47385. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47386. ], PBRMaterial.prototype, "bumpTexture", void 0);
  47387. __decorate([
  47388. BABYLON.serializeAsTexture(),
  47389. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  47390. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  47391. __decorate([
  47392. BABYLON.serializeAsTexture(),
  47393. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47394. ], PBRMaterial.prototype, "refractionTexture", void 0);
  47395. __decorate([
  47396. BABYLON.serializeAsColor3("ambient"),
  47397. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47398. ], PBRMaterial.prototype, "ambientColor", void 0);
  47399. __decorate([
  47400. BABYLON.serializeAsColor3("albedo"),
  47401. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47402. ], PBRMaterial.prototype, "albedoColor", void 0);
  47403. __decorate([
  47404. BABYLON.serializeAsColor3("reflectivity"),
  47405. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47406. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  47407. __decorate([
  47408. BABYLON.serializeAsColor3("reflection"),
  47409. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47410. ], PBRMaterial.prototype, "reflectionColor", void 0);
  47411. __decorate([
  47412. BABYLON.serializeAsColor3("emissive"),
  47413. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47414. ], PBRMaterial.prototype, "emissiveColor", void 0);
  47415. __decorate([
  47416. BABYLON.serialize(),
  47417. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47418. ], PBRMaterial.prototype, "microSurface", void 0);
  47419. __decorate([
  47420. BABYLON.serialize(),
  47421. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47422. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  47423. __decorate([
  47424. BABYLON.serialize(),
  47425. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47426. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  47427. __decorate([
  47428. BABYLON.serialize(),
  47429. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47430. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  47431. __decorate([
  47432. BABYLON.serialize(),
  47433. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47434. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  47435. __decorate([
  47436. BABYLON.serialize(),
  47437. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  47438. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  47439. __decorate([
  47440. BABYLON.serialize(),
  47441. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  47442. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  47443. __decorate([
  47444. BABYLON.serialize(),
  47445. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  47446. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  47447. __decorate([
  47448. BABYLON.serialize(),
  47449. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47450. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  47451. __decorate([
  47452. BABYLON.serialize(),
  47453. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47454. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  47455. __decorate([
  47456. BABYLON.serialize(),
  47457. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47458. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  47459. __decorate([
  47460. BABYLON.serialize(),
  47461. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47462. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  47463. __decorate([
  47464. BABYLON.serialize(),
  47465. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47466. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  47467. __decorate([
  47468. BABYLON.serialize(),
  47469. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47470. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  47471. __decorate([
  47472. BABYLON.serialize(),
  47473. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47474. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  47475. __decorate([
  47476. BABYLON.serialize(),
  47477. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47478. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  47479. __decorate([
  47480. BABYLON.serialize()
  47481. ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
  47482. __decorate([
  47483. BABYLON.serialize()
  47484. ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
  47485. __decorate([
  47486. BABYLON.serialize(),
  47487. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47488. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  47489. __decorate([
  47490. BABYLON.serialize(),
  47491. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47492. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  47493. __decorate([
  47494. BABYLON.serialize(),
  47495. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47496. ], PBRMaterial.prototype, "useParallax", void 0);
  47497. __decorate([
  47498. BABYLON.serialize(),
  47499. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47500. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  47501. __decorate([
  47502. BABYLON.serialize(),
  47503. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47504. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  47505. __decorate([
  47506. BABYLON.serialize(),
  47507. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  47508. ], PBRMaterial.prototype, "disableLighting", void 0);
  47509. __decorate([
  47510. BABYLON.serialize(),
  47511. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47512. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  47513. __decorate([
  47514. BABYLON.serialize(),
  47515. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  47516. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  47517. __decorate([
  47518. BABYLON.serialize(),
  47519. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47520. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  47521. __decorate([
  47522. BABYLON.serialize(),
  47523. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47524. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  47525. __decorate([
  47526. BABYLON.serialize(),
  47527. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47528. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  47529. __decorate([
  47530. BABYLON.serialize(),
  47531. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47532. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  47533. __decorate([
  47534. BABYLON.serialize(),
  47535. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47536. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  47537. __decorate([
  47538. BABYLON.serializeAsTexture(),
  47539. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47540. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  47541. __decorate([
  47542. BABYLON.serialize(),
  47543. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47544. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  47545. __decorate([
  47546. BABYLON.serialize(),
  47547. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47548. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  47549. __decorate([
  47550. BABYLON.serialize(),
  47551. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47552. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  47553. __decorate([
  47554. BABYLON.serialize(),
  47555. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47556. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  47557. __decorate([
  47558. BABYLON.serialize(),
  47559. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  47560. ], PBRMaterial.prototype, "unlit", void 0);
  47561. return PBRMaterial;
  47562. }(BABYLON.PBRBaseMaterial));
  47563. BABYLON.PBRMaterial = PBRMaterial;
  47564. })(BABYLON || (BABYLON = {}));
  47565. //# sourceMappingURL=babylon.pbrMaterial.js.map
  47566. var BABYLON;
  47567. (function (BABYLON) {
  47568. /**
  47569. * The PBR material of BJS following the metal roughness convention.
  47570. *
  47571. * This fits to the PBR convention in the GLTF definition:
  47572. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  47573. */
  47574. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  47575. __extends(PBRMetallicRoughnessMaterial, _super);
  47576. /**
  47577. * Instantiates a new PBRMetalRoughnessMaterial instance.
  47578. *
  47579. * @param name The material name
  47580. * @param scene The scene the material will be use in.
  47581. */
  47582. function PBRMetallicRoughnessMaterial(name, scene) {
  47583. var _this = _super.call(this, name, scene) || this;
  47584. _this._useRoughnessFromMetallicTextureAlpha = false;
  47585. _this._useRoughnessFromMetallicTextureGreen = true;
  47586. _this._useMetallnessFromMetallicTextureBlue = true;
  47587. _this.metallic = 1.0;
  47588. _this.roughness = 1.0;
  47589. return _this;
  47590. }
  47591. /**
  47592. * Return the currrent class name of the material.
  47593. */
  47594. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  47595. return "PBRMetallicRoughnessMaterial";
  47596. };
  47597. /**
  47598. * Return the active textures of the material.
  47599. */
  47600. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  47601. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47602. if (this.baseTexture) {
  47603. activeTextures.push(this.baseTexture);
  47604. }
  47605. if (this.metallicRoughnessTexture) {
  47606. activeTextures.push(this.metallicRoughnessTexture);
  47607. }
  47608. return activeTextures;
  47609. };
  47610. /**
  47611. * Checks to see if a texture is used in the material.
  47612. * @param texture - Base texture to use.
  47613. * @returns - Boolean specifying if a texture is used in the material.
  47614. */
  47615. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  47616. if (_super.prototype.hasTexture.call(this, texture)) {
  47617. return true;
  47618. }
  47619. if (this.baseTexture === texture) {
  47620. return true;
  47621. }
  47622. if (this.metallicRoughnessTexture === texture) {
  47623. return true;
  47624. }
  47625. return false;
  47626. };
  47627. /**
  47628. * Makes a duplicate of the current material.
  47629. * @param name - name to use for the new material.
  47630. */
  47631. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  47632. var _this = this;
  47633. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  47634. clone.id = name;
  47635. clone.name = name;
  47636. return clone;
  47637. };
  47638. /**
  47639. * Serialize the material to a parsable JSON object.
  47640. */
  47641. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  47642. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47643. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  47644. return serializationObject;
  47645. };
  47646. /**
  47647. * Parses a JSON object correponding to the serialize function.
  47648. */
  47649. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  47650. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  47651. };
  47652. __decorate([
  47653. BABYLON.serializeAsColor3(),
  47654. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  47655. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  47656. __decorate([
  47657. BABYLON.serializeAsTexture(),
  47658. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  47659. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  47660. __decorate([
  47661. BABYLON.serialize(),
  47662. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47663. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  47664. __decorate([
  47665. BABYLON.serialize(),
  47666. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47667. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  47668. __decorate([
  47669. BABYLON.serializeAsTexture(),
  47670. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  47671. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  47672. return PBRMetallicRoughnessMaterial;
  47673. }(BABYLON.PBRBaseSimpleMaterial));
  47674. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  47675. })(BABYLON || (BABYLON = {}));
  47676. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  47677. var BABYLON;
  47678. (function (BABYLON) {
  47679. /**
  47680. * The PBR material of BJS following the specular glossiness convention.
  47681. *
  47682. * This fits to the PBR convention in the GLTF definition:
  47683. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  47684. */
  47685. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  47686. __extends(PBRSpecularGlossinessMaterial, _super);
  47687. /**
  47688. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  47689. *
  47690. * @param name The material name
  47691. * @param scene The scene the material will be use in.
  47692. */
  47693. function PBRSpecularGlossinessMaterial(name, scene) {
  47694. var _this = _super.call(this, name, scene) || this;
  47695. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  47696. return _this;
  47697. }
  47698. /**
  47699. * Return the currrent class name of the material.
  47700. */
  47701. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  47702. return "PBRSpecularGlossinessMaterial";
  47703. };
  47704. /**
  47705. * Return the active textures of the material.
  47706. */
  47707. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  47708. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47709. if (this.diffuseTexture) {
  47710. activeTextures.push(this.diffuseTexture);
  47711. }
  47712. if (this.specularGlossinessTexture) {
  47713. activeTextures.push(this.specularGlossinessTexture);
  47714. }
  47715. return activeTextures;
  47716. };
  47717. /**
  47718. * Checks to see if a texture is used in the material.
  47719. * @param texture - Base texture to use.
  47720. * @returns - Boolean specifying if a texture is used in the material.
  47721. */
  47722. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  47723. if (_super.prototype.hasTexture.call(this, texture)) {
  47724. return true;
  47725. }
  47726. if (this.diffuseTexture === texture) {
  47727. return true;
  47728. }
  47729. if (this.specularGlossinessTexture === texture) {
  47730. return true;
  47731. }
  47732. return false;
  47733. };
  47734. /**
  47735. * Makes a duplicate of the current material.
  47736. * @param name - name to use for the new material.
  47737. */
  47738. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  47739. var _this = this;
  47740. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  47741. clone.id = name;
  47742. clone.name = name;
  47743. return clone;
  47744. };
  47745. /**
  47746. * Serialize the material to a parsable JSON object.
  47747. */
  47748. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  47749. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47750. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  47751. return serializationObject;
  47752. };
  47753. /**
  47754. * Parses a JSON object correponding to the serialize function.
  47755. */
  47756. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  47757. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  47758. };
  47759. __decorate([
  47760. BABYLON.serializeAsColor3("diffuse"),
  47761. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  47762. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  47763. __decorate([
  47764. BABYLON.serializeAsTexture(),
  47765. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  47766. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  47767. __decorate([
  47768. BABYLON.serializeAsColor3("specular"),
  47769. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  47770. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  47771. __decorate([
  47772. BABYLON.serialize(),
  47773. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  47774. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  47775. __decorate([
  47776. BABYLON.serializeAsTexture(),
  47777. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  47778. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  47779. return PBRSpecularGlossinessMaterial;
  47780. }(BABYLON.PBRBaseSimpleMaterial));
  47781. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  47782. })(BABYLON || (BABYLON = {}));
  47783. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  47784. var BABYLON;
  47785. (function (BABYLON) {
  47786. /**
  47787. * @ignore
  47788. * This is a list of all the different input types that are available in the application.
  47789. * Fo instance: ArcRotateCameraGamepadInput...
  47790. */
  47791. BABYLON.CameraInputTypes = {};
  47792. /**
  47793. * This represents the input manager used within a camera.
  47794. * It helps dealing with all the different kind of input attached to a camera.
  47795. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47796. */
  47797. var CameraInputsManager = /** @class */ (function () {
  47798. /**
  47799. * Instantiate a new Camera Input Manager.
  47800. * @param camera Defines the camera the input manager blongs to
  47801. */
  47802. function CameraInputsManager(camera) {
  47803. this.attached = {};
  47804. this.camera = camera;
  47805. this.checkInputs = function () { };
  47806. }
  47807. /**
  47808. * Add an input method to a camera
  47809. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47810. * @param input camera input method
  47811. */
  47812. CameraInputsManager.prototype.add = function (input) {
  47813. var type = input.getSimpleName();
  47814. if (this.attached[type]) {
  47815. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  47816. return;
  47817. }
  47818. this.attached[type] = input;
  47819. input.camera = this.camera;
  47820. //for checkInputs, we are dynamically creating a function
  47821. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  47822. if (input.checkInputs) {
  47823. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47824. }
  47825. if (this.attachedElement) {
  47826. input.attachControl(this.attachedElement);
  47827. }
  47828. };
  47829. /**
  47830. * Remove a specific input method from a camera
  47831. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  47832. * @param inputToRemove camera input method
  47833. */
  47834. CameraInputsManager.prototype.remove = function (inputToRemove) {
  47835. for (var cam in this.attached) {
  47836. var input = this.attached[cam];
  47837. if (input === inputToRemove) {
  47838. input.detachControl(this.attachedElement);
  47839. input.camera = null;
  47840. delete this.attached[cam];
  47841. this.rebuildInputCheck();
  47842. }
  47843. }
  47844. };
  47845. /**
  47846. * Remove a specific input type from a camera
  47847. * example: camera.inputs.remove("ArcRotateCameraGamepadInput");
  47848. * @param inputType the type of the input to remove
  47849. */
  47850. CameraInputsManager.prototype.removeByType = function (inputType) {
  47851. for (var cam in this.attached) {
  47852. var input = this.attached[cam];
  47853. if (input.getClassName() === inputType) {
  47854. input.detachControl(this.attachedElement);
  47855. input.camera = null;
  47856. delete this.attached[cam];
  47857. this.rebuildInputCheck();
  47858. }
  47859. }
  47860. };
  47861. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  47862. var current = this.checkInputs;
  47863. return function () {
  47864. current();
  47865. fn();
  47866. };
  47867. };
  47868. /**
  47869. * Attach the input controls to the currently attached dom element to listen the events from.
  47870. * @param input Defines the input to attach
  47871. */
  47872. CameraInputsManager.prototype.attachInput = function (input) {
  47873. if (this.attachedElement) {
  47874. input.attachControl(this.attachedElement, this.noPreventDefault);
  47875. }
  47876. };
  47877. /**
  47878. * Attach the current manager inputs controls to a specific dom element to listen the events from.
  47879. * @param element Defines the dom element to collect the events from
  47880. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47881. */
  47882. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  47883. if (noPreventDefault === void 0) { noPreventDefault = false; }
  47884. if (this.attachedElement) {
  47885. return;
  47886. }
  47887. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  47888. this.attachedElement = element;
  47889. this.noPreventDefault = noPreventDefault;
  47890. for (var cam in this.attached) {
  47891. this.attached[cam].attachControl(element, noPreventDefault);
  47892. }
  47893. };
  47894. /**
  47895. * Detach the current manager inputs controls from a specific dom element.
  47896. * @param element Defines the dom element to collect the events from
  47897. * @param disconnect Defines whether the input should be removed from the current list of attached inputs
  47898. */
  47899. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  47900. if (disconnect === void 0) { disconnect = false; }
  47901. if (this.attachedElement !== element) {
  47902. return;
  47903. }
  47904. for (var cam in this.attached) {
  47905. this.attached[cam].detachControl(element);
  47906. if (disconnect) {
  47907. this.attached[cam].camera = null;
  47908. }
  47909. }
  47910. this.attachedElement = null;
  47911. };
  47912. /**
  47913. * Rebuild the dynamic inputCheck function from the current list of
  47914. * defined inputs in the manager.
  47915. */
  47916. CameraInputsManager.prototype.rebuildInputCheck = function () {
  47917. this.checkInputs = function () { };
  47918. for (var cam in this.attached) {
  47919. var input = this.attached[cam];
  47920. if (input.checkInputs) {
  47921. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47922. }
  47923. }
  47924. };
  47925. /**
  47926. * Remove all attached input methods from a camera
  47927. */
  47928. CameraInputsManager.prototype.clear = function () {
  47929. if (this.attachedElement) {
  47930. this.detachElement(this.attachedElement, true);
  47931. }
  47932. this.attached = {};
  47933. this.attachedElement = null;
  47934. this.checkInputs = function () { };
  47935. };
  47936. /**
  47937. * Serialize the current input manager attached to a camera.
  47938. * This ensures than once parsed,
  47939. * the input associated to the camera will be identical to the current ones
  47940. * @param serializedCamera Defines the camera serialization JSON the input serialization should write to
  47941. */
  47942. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  47943. var inputs = {};
  47944. for (var cam in this.attached) {
  47945. var input = this.attached[cam];
  47946. var res = BABYLON.SerializationHelper.Serialize(input);
  47947. inputs[input.getClassName()] = res;
  47948. }
  47949. serializedCamera.inputsmgr = inputs;
  47950. };
  47951. /**
  47952. * Parses an input manager serialized JSON to restore the previous list of inputs
  47953. * and states associated to a camera.
  47954. * @param parsedCamera Defines the JSON to parse
  47955. */
  47956. CameraInputsManager.prototype.parse = function (parsedCamera) {
  47957. var parsedInputs = parsedCamera.inputsmgr;
  47958. if (parsedInputs) {
  47959. this.clear();
  47960. for (var n in parsedInputs) {
  47961. var construct = BABYLON.CameraInputTypes[n];
  47962. if (construct) {
  47963. var parsedinput = parsedInputs[n];
  47964. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  47965. this.add(input);
  47966. }
  47967. }
  47968. }
  47969. else {
  47970. //2016-03-08 this part is for managing backward compatibility
  47971. for (var n in this.attached) {
  47972. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  47973. if (construct) {
  47974. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  47975. this.remove(this.attached[n]);
  47976. this.add(input);
  47977. }
  47978. }
  47979. }
  47980. };
  47981. return CameraInputsManager;
  47982. }());
  47983. BABYLON.CameraInputsManager = CameraInputsManager;
  47984. })(BABYLON || (BABYLON = {}));
  47985. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  47986. var BABYLON;
  47987. (function (BABYLON) {
  47988. /**
  47989. * A target camera takes a mesh or position as a target and continues to look at it while it moves.
  47990. * This is the base of the follow, arc rotate cameras and Free camera
  47991. * @see http://doc.babylonjs.com/features/cameras
  47992. */
  47993. var TargetCamera = /** @class */ (function (_super) {
  47994. __extends(TargetCamera, _super);
  47995. /**
  47996. * Instantiates a target camera that takes a meshor position as a target and continues to look at it while it moves.
  47997. * This is the base of the follow, arc rotate cameras and Free camera
  47998. * @see http://doc.babylonjs.com/features/cameras
  47999. * @param name Defines the name of the camera in the scene
  48000. * @param position Defines the start position of the camera in the scene
  48001. * @param scene Defines the scene the camera belongs to
  48002. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  48003. */
  48004. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  48005. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48006. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  48007. /**
  48008. * Define the current direction the camera is moving to
  48009. */
  48010. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  48011. /**
  48012. * Define the current rotation the camera is rotating to
  48013. */
  48014. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  48015. /**
  48016. * Define the current rotation of the camera
  48017. */
  48018. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  48019. /**
  48020. * Define the current speed of the camera
  48021. */
  48022. _this.speed = 2.0;
  48023. /**
  48024. * Add cconstraint to the camera to prevent it to move freely in all directions and
  48025. * around all axis.
  48026. */
  48027. _this.noRotationConstraint = false;
  48028. /**
  48029. * Define the current target of the camera as an object or a position.
  48030. */
  48031. _this.lockedTarget = null;
  48032. /** @hidden */
  48033. _this._currentTarget = BABYLON.Vector3.Zero();
  48034. /** @hidden */
  48035. _this._viewMatrix = BABYLON.Matrix.Zero();
  48036. /** @hidden */
  48037. _this._camMatrix = BABYLON.Matrix.Zero();
  48038. /** @hidden */
  48039. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  48040. /** @hidden */
  48041. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  48042. /** @hidden */
  48043. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  48044. /** @hidden */
  48045. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  48046. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  48047. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  48048. _this._defaultUp = BABYLON.Vector3.Up();
  48049. _this._cachedRotationZ = 0;
  48050. _this._cachedQuaternionRotationZ = 0;
  48051. return _this;
  48052. }
  48053. /**
  48054. * Gets the position in front of the camera at a given distance.
  48055. * @param distance The distance from the camera we want the position to be
  48056. * @returns the position
  48057. */
  48058. TargetCamera.prototype.getFrontPosition = function (distance) {
  48059. this.getWorldMatrix();
  48060. var direction = this.getTarget().subtract(this.position);
  48061. direction.normalize();
  48062. direction.scaleInPlace(distance);
  48063. return this.globalPosition.add(direction);
  48064. };
  48065. /** @hidden */
  48066. TargetCamera.prototype._getLockedTargetPosition = function () {
  48067. if (!this.lockedTarget) {
  48068. return null;
  48069. }
  48070. if (this.lockedTarget.absolutePosition) {
  48071. this.lockedTarget.computeWorldMatrix();
  48072. }
  48073. return this.lockedTarget.absolutePosition || this.lockedTarget;
  48074. };
  48075. /**
  48076. * Store current camera state of the camera (fov, position, rotation, etc..)
  48077. * @returns the camera
  48078. */
  48079. TargetCamera.prototype.storeState = function () {
  48080. this._storedPosition = this.position.clone();
  48081. this._storedRotation = this.rotation.clone();
  48082. if (this.rotationQuaternion) {
  48083. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  48084. }
  48085. return _super.prototype.storeState.call(this);
  48086. };
  48087. /**
  48088. * Restored camera state. You must call storeState() first
  48089. * @returns whether it was successful or not
  48090. * @hidden
  48091. */
  48092. TargetCamera.prototype._restoreStateValues = function () {
  48093. if (!_super.prototype._restoreStateValues.call(this)) {
  48094. return false;
  48095. }
  48096. this.position = this._storedPosition.clone();
  48097. this.rotation = this._storedRotation.clone();
  48098. if (this.rotationQuaternion) {
  48099. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  48100. }
  48101. this.cameraDirection.copyFromFloats(0, 0, 0);
  48102. this.cameraRotation.copyFromFloats(0, 0);
  48103. return true;
  48104. };
  48105. /** @hidden */
  48106. TargetCamera.prototype._initCache = function () {
  48107. _super.prototype._initCache.call(this);
  48108. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48109. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48110. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48111. };
  48112. /** @hidden */
  48113. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  48114. if (!ignoreParentClass) {
  48115. _super.prototype._updateCache.call(this);
  48116. }
  48117. var lockedTargetPosition = this._getLockedTargetPosition();
  48118. if (!lockedTargetPosition) {
  48119. this._cache.lockedTarget = null;
  48120. }
  48121. else {
  48122. if (!this._cache.lockedTarget) {
  48123. this._cache.lockedTarget = lockedTargetPosition.clone();
  48124. }
  48125. else {
  48126. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  48127. }
  48128. }
  48129. this._cache.rotation.copyFrom(this.rotation);
  48130. if (this.rotationQuaternion) {
  48131. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  48132. }
  48133. };
  48134. // Synchronized
  48135. /** @hidden */
  48136. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  48137. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  48138. return false;
  48139. }
  48140. var lockedTargetPosition = this._getLockedTargetPosition();
  48141. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  48142. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  48143. };
  48144. // Methods
  48145. /** @hidden */
  48146. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  48147. var engine = this.getEngine();
  48148. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  48149. };
  48150. // Target
  48151. /** @hidden */
  48152. TargetCamera.prototype.setTarget = function (target) {
  48153. this.upVector.normalize();
  48154. if (this.position.z === target.z) {
  48155. this.position.z += BABYLON.Epsilon;
  48156. }
  48157. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
  48158. this._camMatrix.invert();
  48159. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  48160. var vDir = target.subtract(this.position);
  48161. if (vDir.x >= 0.0) {
  48162. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  48163. }
  48164. else {
  48165. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  48166. }
  48167. this.rotation.z = 0;
  48168. if (isNaN(this.rotation.x)) {
  48169. this.rotation.x = 0;
  48170. }
  48171. if (isNaN(this.rotation.y)) {
  48172. this.rotation.y = 0;
  48173. }
  48174. if (isNaN(this.rotation.z)) {
  48175. this.rotation.z = 0;
  48176. }
  48177. if (this.rotationQuaternion) {
  48178. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  48179. }
  48180. };
  48181. /**
  48182. * Return the current target position of the camera. This value is expressed in local space.
  48183. * @returns the target position
  48184. */
  48185. TargetCamera.prototype.getTarget = function () {
  48186. return this._currentTarget;
  48187. };
  48188. /** @hidden */
  48189. TargetCamera.prototype._decideIfNeedsToMove = function () {
  48190. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  48191. };
  48192. /** @hidden */
  48193. TargetCamera.prototype._updatePosition = function () {
  48194. if (this.parent) {
  48195. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  48196. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  48197. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  48198. return;
  48199. }
  48200. this.position.addInPlace(this.cameraDirection);
  48201. };
  48202. /** @hidden */
  48203. TargetCamera.prototype._checkInputs = function () {
  48204. var needToMove = this._decideIfNeedsToMove();
  48205. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  48206. // Move
  48207. if (needToMove) {
  48208. this._updatePosition();
  48209. }
  48210. // Rotate
  48211. if (needToRotate) {
  48212. this.rotation.x += this.cameraRotation.x;
  48213. this.rotation.y += this.cameraRotation.y;
  48214. //rotate, if quaternion is set and rotation was used
  48215. if (this.rotationQuaternion) {
  48216. var len = this.rotation.lengthSquared();
  48217. if (len) {
  48218. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  48219. }
  48220. }
  48221. if (!this.noRotationConstraint) {
  48222. var limit = (Math.PI / 2) * 0.95;
  48223. if (this.rotation.x > limit) {
  48224. this.rotation.x = limit;
  48225. }
  48226. if (this.rotation.x < -limit) {
  48227. this.rotation.x = -limit;
  48228. }
  48229. }
  48230. }
  48231. // Inertia
  48232. if (needToMove) {
  48233. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  48234. this.cameraDirection.x = 0;
  48235. }
  48236. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  48237. this.cameraDirection.y = 0;
  48238. }
  48239. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  48240. this.cameraDirection.z = 0;
  48241. }
  48242. this.cameraDirection.scaleInPlace(this.inertia);
  48243. }
  48244. if (needToRotate) {
  48245. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  48246. this.cameraRotation.x = 0;
  48247. }
  48248. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  48249. this.cameraRotation.y = 0;
  48250. }
  48251. this.cameraRotation.scaleInPlace(this.inertia);
  48252. }
  48253. _super.prototype._checkInputs.call(this);
  48254. };
  48255. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  48256. if (this.rotationQuaternion) {
  48257. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  48258. }
  48259. else {
  48260. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  48261. }
  48262. };
  48263. /**
  48264. * 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)
  48265. * @returns the current camera
  48266. */
  48267. TargetCamera.prototype._rotateUpVectorWithCameraRotationMatrix = function () {
  48268. BABYLON.Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
  48269. return this;
  48270. };
  48271. /** @hidden */
  48272. TargetCamera.prototype._getViewMatrix = function () {
  48273. if (this.lockedTarget) {
  48274. this.setTarget(this._getLockedTargetPosition());
  48275. }
  48276. // Compute
  48277. this._updateCameraRotationMatrix();
  48278. // Apply the changed rotation to the upVector
  48279. if (this.rotationQuaternion && this._cachedQuaternionRotationZ != this.rotationQuaternion.z) {
  48280. this._rotateUpVectorWithCameraRotationMatrix();
  48281. this._cachedQuaternionRotationZ = this.rotationQuaternion.z;
  48282. }
  48283. else if (this._cachedRotationZ != this.rotation.z) {
  48284. this._rotateUpVectorWithCameraRotationMatrix();
  48285. this._cachedRotationZ = this.rotation.z;
  48286. }
  48287. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  48288. // Computing target and final matrix
  48289. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  48290. this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
  48291. return this._viewMatrix;
  48292. };
  48293. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  48294. if (this.parent) {
  48295. var parentWorldMatrix = this.parent.getWorldMatrix();
  48296. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  48297. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  48298. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  48299. this._markSyncedWithParent();
  48300. }
  48301. else {
  48302. this._globalPosition.copyFrom(position);
  48303. this._globalCurrentTarget.copyFrom(target);
  48304. this._globalCurrentUpVector.copyFrom(up);
  48305. }
  48306. if (this.getScene().useRightHandedSystem) {
  48307. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  48308. }
  48309. else {
  48310. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  48311. }
  48312. };
  48313. /**
  48314. * @hidden
  48315. */
  48316. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48317. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  48318. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  48319. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  48320. if (!this.rotationQuaternion) {
  48321. this.rotationQuaternion = new BABYLON.Quaternion();
  48322. }
  48323. rigCamera._cameraRigParams = {};
  48324. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  48325. }
  48326. return rigCamera;
  48327. }
  48328. return null;
  48329. };
  48330. /**
  48331. * @hidden
  48332. */
  48333. TargetCamera.prototype._updateRigCameras = function () {
  48334. var camLeft = this._rigCameras[0];
  48335. var camRight = this._rigCameras[1];
  48336. switch (this.cameraRigMode) {
  48337. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48338. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48339. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48340. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48341. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  48342. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  48343. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  48344. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  48345. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  48346. camLeft.setTarget(this.getTarget());
  48347. camRight.setTarget(this.getTarget());
  48348. break;
  48349. case BABYLON.Camera.RIG_MODE_VR:
  48350. if (camLeft.rotationQuaternion) {
  48351. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  48352. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  48353. }
  48354. else {
  48355. camLeft.rotation.copyFrom(this.rotation);
  48356. camRight.rotation.copyFrom(this.rotation);
  48357. }
  48358. camLeft.position.copyFrom(this.position);
  48359. camRight.position.copyFrom(this.position);
  48360. break;
  48361. }
  48362. _super.prototype._updateRigCameras.call(this);
  48363. };
  48364. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  48365. if (!this._rigCamTransformMatrix) {
  48366. this._rigCamTransformMatrix = new BABYLON.Matrix();
  48367. }
  48368. var target = this.getTarget();
  48369. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  48370. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  48371. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  48372. };
  48373. /**
  48374. * Gets the current object class name.
  48375. * @return the class name
  48376. */
  48377. TargetCamera.prototype.getClassName = function () {
  48378. return "TargetCamera";
  48379. };
  48380. __decorate([
  48381. BABYLON.serializeAsVector3()
  48382. ], TargetCamera.prototype, "rotation", void 0);
  48383. __decorate([
  48384. BABYLON.serialize()
  48385. ], TargetCamera.prototype, "speed", void 0);
  48386. __decorate([
  48387. BABYLON.serializeAsMeshReference("lockedTargetId")
  48388. ], TargetCamera.prototype, "lockedTarget", void 0);
  48389. return TargetCamera;
  48390. }(BABYLON.Camera));
  48391. BABYLON.TargetCamera = TargetCamera;
  48392. })(BABYLON || (BABYLON = {}));
  48393. //# sourceMappingURL=babylon.targetCamera.js.map
  48394. var BABYLON;
  48395. (function (BABYLON) {
  48396. /**
  48397. * Manage the mouse inputs to control the movement of a free camera.
  48398. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48399. */
  48400. var FreeCameraMouseInput = /** @class */ (function () {
  48401. /**
  48402. * Manage the mouse inputs to control the movement of a free camera.
  48403. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48404. * @param touchEnabled Defines if touch is enabled or not
  48405. */
  48406. function FreeCameraMouseInput(
  48407. /**
  48408. * Define if touch is enabled in the mouse input
  48409. */
  48410. touchEnabled) {
  48411. if (touchEnabled === void 0) { touchEnabled = true; }
  48412. this.touchEnabled = touchEnabled;
  48413. /**
  48414. * Defines the buttons associated with the input to handle camera move.
  48415. */
  48416. this.buttons = [0, 1, 2];
  48417. /**
  48418. * Defines the pointer angular sensibility along the X and Y axis or how fast is the camera rotating.
  48419. */
  48420. this.angularSensibility = 2000.0;
  48421. this.previousPosition = null;
  48422. }
  48423. /**
  48424. * Attach the input controls to a specific dom element to get the input from.
  48425. * @param element Defines the element the controls should be listened from
  48426. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48427. */
  48428. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  48429. var _this = this;
  48430. var engine = this.camera.getEngine();
  48431. if (!this._pointerInput) {
  48432. this._pointerInput = function (p, s) {
  48433. var evt = p.event;
  48434. if (engine.isInVRExclusivePointerMode) {
  48435. return;
  48436. }
  48437. if (!_this.touchEnabled && evt.pointerType === "touch") {
  48438. return;
  48439. }
  48440. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  48441. return;
  48442. }
  48443. var srcElement = (evt.srcElement || evt.target);
  48444. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  48445. try {
  48446. srcElement.setPointerCapture(evt.pointerId);
  48447. }
  48448. catch (e) {
  48449. //Nothing to do with the error. Execution will continue.
  48450. }
  48451. _this.previousPosition = {
  48452. x: evt.clientX,
  48453. y: evt.clientY
  48454. };
  48455. if (!noPreventDefault) {
  48456. evt.preventDefault();
  48457. element.focus();
  48458. }
  48459. }
  48460. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  48461. try {
  48462. srcElement.releasePointerCapture(evt.pointerId);
  48463. }
  48464. catch (e) {
  48465. //Nothing to do with the error.
  48466. }
  48467. _this.previousPosition = null;
  48468. if (!noPreventDefault) {
  48469. evt.preventDefault();
  48470. }
  48471. }
  48472. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48473. if (!_this.previousPosition || engine.isPointerLock) {
  48474. return;
  48475. }
  48476. var offsetX = evt.clientX - _this.previousPosition.x;
  48477. if (_this.camera.getScene().useRightHandedSystem) {
  48478. offsetX *= -1;
  48479. }
  48480. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0) {
  48481. offsetX *= -1;
  48482. }
  48483. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  48484. var offsetY = evt.clientY - _this.previousPosition.y;
  48485. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  48486. _this.previousPosition = {
  48487. x: evt.clientX,
  48488. y: evt.clientY
  48489. };
  48490. if (!noPreventDefault) {
  48491. evt.preventDefault();
  48492. }
  48493. }
  48494. };
  48495. }
  48496. this._onMouseMove = function (evt) {
  48497. if (!engine.isPointerLock) {
  48498. return;
  48499. }
  48500. if (engine.isInVRExclusivePointerMode) {
  48501. return;
  48502. }
  48503. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48504. if (_this.camera.getScene().useRightHandedSystem) {
  48505. offsetX *= -1;
  48506. }
  48507. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0) {
  48508. offsetX *= -1;
  48509. }
  48510. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  48511. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48512. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  48513. _this.previousPosition = null;
  48514. if (!noPreventDefault) {
  48515. evt.preventDefault();
  48516. }
  48517. };
  48518. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  48519. element.addEventListener("mousemove", this._onMouseMove, false);
  48520. };
  48521. /**
  48522. * Detach the current controls from the specified dom element.
  48523. * @param element Defines the element to stop listening the inputs from
  48524. */
  48525. FreeCameraMouseInput.prototype.detachControl = function (element) {
  48526. if (this._observer && element) {
  48527. this.camera.getScene().onPointerObservable.remove(this._observer);
  48528. if (this._onMouseMove) {
  48529. element.removeEventListener("mousemove", this._onMouseMove);
  48530. }
  48531. this._observer = null;
  48532. this._onMouseMove = null;
  48533. this.previousPosition = null;
  48534. }
  48535. };
  48536. /**
  48537. * Gets the class name of the current intput.
  48538. * @returns the class name
  48539. */
  48540. FreeCameraMouseInput.prototype.getClassName = function () {
  48541. return "FreeCameraMouseInput";
  48542. };
  48543. /**
  48544. * Get the friendly name associated with the input class.
  48545. * @returns the input friendly name
  48546. */
  48547. FreeCameraMouseInput.prototype.getSimpleName = function () {
  48548. return "mouse";
  48549. };
  48550. __decorate([
  48551. BABYLON.serialize()
  48552. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  48553. __decorate([
  48554. BABYLON.serialize()
  48555. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  48556. return FreeCameraMouseInput;
  48557. }());
  48558. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  48559. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  48560. })(BABYLON || (BABYLON = {}));
  48561. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  48562. var BABYLON;
  48563. (function (BABYLON) {
  48564. /**
  48565. * Manage the keyboard inputs to control the movement of a free camera.
  48566. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48567. */
  48568. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  48569. function FreeCameraKeyboardMoveInput() {
  48570. /**
  48571. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  48572. */
  48573. this.keysUp = [38];
  48574. /**
  48575. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  48576. */
  48577. this.keysDown = [40];
  48578. /**
  48579. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  48580. */
  48581. this.keysLeft = [37];
  48582. /**
  48583. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  48584. */
  48585. this.keysRight = [39];
  48586. this._keys = new Array();
  48587. }
  48588. /**
  48589. * Attach the input controls to a specific dom element to get the input from.
  48590. * @param element Defines the element the controls should be listened from
  48591. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48592. */
  48593. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  48594. var _this = this;
  48595. if (this._onCanvasBlurObserver) {
  48596. return;
  48597. }
  48598. this._scene = this.camera.getScene();
  48599. this._engine = this._scene.getEngine();
  48600. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  48601. _this._keys = [];
  48602. });
  48603. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  48604. var evt = info.event;
  48605. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  48606. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48607. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48608. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48609. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  48610. var index = _this._keys.indexOf(evt.keyCode);
  48611. if (index === -1) {
  48612. _this._keys.push(evt.keyCode);
  48613. }
  48614. if (!noPreventDefault) {
  48615. evt.preventDefault();
  48616. }
  48617. }
  48618. }
  48619. else {
  48620. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48621. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48622. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48623. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  48624. var index = _this._keys.indexOf(evt.keyCode);
  48625. if (index >= 0) {
  48626. _this._keys.splice(index, 1);
  48627. }
  48628. if (!noPreventDefault) {
  48629. evt.preventDefault();
  48630. }
  48631. }
  48632. }
  48633. });
  48634. };
  48635. /**
  48636. * Detach the current controls from the specified dom element.
  48637. * @param element Defines the element to stop listening the inputs from
  48638. */
  48639. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  48640. if (this._scene) {
  48641. if (this._onKeyboardObserver) {
  48642. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  48643. }
  48644. if (this._onCanvasBlurObserver) {
  48645. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  48646. }
  48647. this._onKeyboardObserver = null;
  48648. this._onCanvasBlurObserver = null;
  48649. }
  48650. this._keys = [];
  48651. };
  48652. /**
  48653. * Update the current camera state depending on the inputs that have been used this frame.
  48654. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  48655. */
  48656. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  48657. if (this._onKeyboardObserver) {
  48658. var camera = this.camera;
  48659. // Keyboard
  48660. for (var index = 0; index < this._keys.length; index++) {
  48661. var keyCode = this._keys[index];
  48662. var speed = camera._computeLocalCameraSpeed();
  48663. if (this.keysLeft.indexOf(keyCode) !== -1) {
  48664. camera._localDirection.copyFromFloats(-speed, 0, 0);
  48665. }
  48666. else if (this.keysUp.indexOf(keyCode) !== -1) {
  48667. camera._localDirection.copyFromFloats(0, 0, speed);
  48668. }
  48669. else if (this.keysRight.indexOf(keyCode) !== -1) {
  48670. camera._localDirection.copyFromFloats(speed, 0, 0);
  48671. }
  48672. else if (this.keysDown.indexOf(keyCode) !== -1) {
  48673. camera._localDirection.copyFromFloats(0, 0, -speed);
  48674. }
  48675. if (camera.getScene().useRightHandedSystem) {
  48676. camera._localDirection.z *= -1;
  48677. }
  48678. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  48679. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  48680. camera.cameraDirection.addInPlace(camera._transformedDirection);
  48681. }
  48682. }
  48683. };
  48684. /**
  48685. * Gets the class name of the current intput.
  48686. * @returns the class name
  48687. */
  48688. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  48689. return "FreeCameraKeyboardMoveInput";
  48690. };
  48691. /** @hidden */
  48692. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  48693. this._keys = [];
  48694. };
  48695. /**
  48696. * Get the friendly name associated with the input class.
  48697. * @returns the input friendly name
  48698. */
  48699. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  48700. return "keyboard";
  48701. };
  48702. __decorate([
  48703. BABYLON.serialize()
  48704. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  48705. __decorate([
  48706. BABYLON.serialize()
  48707. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  48708. __decorate([
  48709. BABYLON.serialize()
  48710. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  48711. __decorate([
  48712. BABYLON.serialize()
  48713. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  48714. return FreeCameraKeyboardMoveInput;
  48715. }());
  48716. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  48717. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  48718. })(BABYLON || (BABYLON = {}));
  48719. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  48720. var BABYLON;
  48721. (function (BABYLON) {
  48722. /**
  48723. * Default Inputs manager for the FreeCamera.
  48724. * It groups all the default supported inputs for ease of use.
  48725. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48726. */
  48727. var FreeCameraInputsManager = /** @class */ (function (_super) {
  48728. __extends(FreeCameraInputsManager, _super);
  48729. /**
  48730. * Instantiates a new FreeCameraInputsManager.
  48731. * @param camera Defines the camera the inputs belong to
  48732. */
  48733. function FreeCameraInputsManager(camera) {
  48734. return _super.call(this, camera) || this;
  48735. }
  48736. /**
  48737. * Add keyboard input support to the input manager.
  48738. * @returns the current input manager
  48739. */
  48740. FreeCameraInputsManager.prototype.addKeyboard = function () {
  48741. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  48742. return this;
  48743. };
  48744. /**
  48745. * Add mouse input support to the input manager.
  48746. * @param touchEnabled if the FreeCameraMouseInput should support touch (default: true)
  48747. * @returns the current input manager
  48748. */
  48749. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  48750. if (touchEnabled === void 0) { touchEnabled = true; }
  48751. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  48752. return this;
  48753. };
  48754. /**
  48755. * Add orientation input support to the input manager.
  48756. * @returns the current input manager
  48757. */
  48758. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  48759. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  48760. return this;
  48761. };
  48762. /**
  48763. * Add touch input support to the input manager.
  48764. * @returns the current input manager
  48765. */
  48766. FreeCameraInputsManager.prototype.addTouch = function () {
  48767. this.add(new BABYLON.FreeCameraTouchInput());
  48768. return this;
  48769. };
  48770. /**
  48771. * Add virtual joystick input support to the input manager.
  48772. * @returns the current input manager
  48773. */
  48774. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  48775. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  48776. return this;
  48777. };
  48778. return FreeCameraInputsManager;
  48779. }(BABYLON.CameraInputsManager));
  48780. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  48781. })(BABYLON || (BABYLON = {}));
  48782. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  48783. var BABYLON;
  48784. (function (BABYLON) {
  48785. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  48786. // Forcing to use the Universal camera
  48787. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  48788. });
  48789. /**
  48790. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  48791. * Please consider using the new UniversalCamera instead as it adds more functionality like the gamepad.
  48792. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  48793. */
  48794. var FreeCamera = /** @class */ (function (_super) {
  48795. __extends(FreeCamera, _super);
  48796. /**
  48797. * Instantiates a Free Camera.
  48798. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  48799. * Please consider using the new UniversalCamera instead as it adds more functionality like touch to this camera.
  48800. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  48801. * @param name Define the name of the camera in the scene
  48802. * @param position Define the start position of the camera in the scene
  48803. * @param scene Define the scene the camera belongs to
  48804. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  48805. */
  48806. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  48807. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48808. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  48809. /**
  48810. * Define the collision ellipsoid of the camera.
  48811. * This is helpful to simulate a camera body like the player body around the camera
  48812. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  48813. */
  48814. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  48815. /**
  48816. * Define an offset for the position of the ellipsoid around the camera.
  48817. * This can be helpful to determine the center of the body near the gravity center of the body
  48818. * instead of its head.
  48819. */
  48820. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  48821. /**
  48822. * Enable or disable collisions of the camera with the rest of the scene objects.
  48823. */
  48824. _this.checkCollisions = false;
  48825. /**
  48826. * Enable or disable gravity on the camera.
  48827. */
  48828. _this.applyGravity = false;
  48829. _this._needMoveForGravity = false;
  48830. _this._oldPosition = BABYLON.Vector3.Zero();
  48831. _this._diffPosition = BABYLON.Vector3.Zero();
  48832. _this._newPosition = BABYLON.Vector3.Zero();
  48833. // Collisions
  48834. _this._collisionMask = -1;
  48835. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48836. if (collidedMesh === void 0) { collidedMesh = null; }
  48837. //TODO move this to the collision coordinator!
  48838. if (_this.getScene().workerCollisions) {
  48839. newPosition.multiplyInPlace(_this._collider._radius);
  48840. }
  48841. var updatePosition = function (newPos) {
  48842. _this._newPosition.copyFrom(newPos);
  48843. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  48844. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  48845. _this.position.addInPlace(_this._diffPosition);
  48846. if (_this.onCollide && collidedMesh) {
  48847. _this.onCollide(collidedMesh);
  48848. }
  48849. }
  48850. };
  48851. updatePosition(newPosition);
  48852. };
  48853. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  48854. _this.inputs.addKeyboard().addMouse();
  48855. return _this;
  48856. }
  48857. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  48858. /**
  48859. * Gets the input sensibility for a mouse input. (default is 2000.0)
  48860. * Higher values reduce sensitivity.
  48861. */
  48862. get: function () {
  48863. var mouse = this.inputs.attached["mouse"];
  48864. if (mouse) {
  48865. return mouse.angularSensibility;
  48866. }
  48867. return 0;
  48868. },
  48869. /**
  48870. * Sets the input sensibility for a mouse input. (default is 2000.0)
  48871. * Higher values reduce sensitivity.
  48872. */
  48873. set: function (value) {
  48874. var mouse = this.inputs.attached["mouse"];
  48875. if (mouse) {
  48876. mouse.angularSensibility = value;
  48877. }
  48878. },
  48879. enumerable: true,
  48880. configurable: true
  48881. });
  48882. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  48883. /**
  48884. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  48885. */
  48886. get: function () {
  48887. var keyboard = this.inputs.attached["keyboard"];
  48888. if (keyboard) {
  48889. return keyboard.keysUp;
  48890. }
  48891. return [];
  48892. },
  48893. set: function (value) {
  48894. var keyboard = this.inputs.attached["keyboard"];
  48895. if (keyboard) {
  48896. keyboard.keysUp = value;
  48897. }
  48898. },
  48899. enumerable: true,
  48900. configurable: true
  48901. });
  48902. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  48903. /**
  48904. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  48905. */
  48906. get: function () {
  48907. var keyboard = this.inputs.attached["keyboard"];
  48908. if (keyboard) {
  48909. return keyboard.keysDown;
  48910. }
  48911. return [];
  48912. },
  48913. set: function (value) {
  48914. var keyboard = this.inputs.attached["keyboard"];
  48915. if (keyboard) {
  48916. keyboard.keysDown = value;
  48917. }
  48918. },
  48919. enumerable: true,
  48920. configurable: true
  48921. });
  48922. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  48923. /**
  48924. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  48925. */
  48926. get: function () {
  48927. var keyboard = this.inputs.attached["keyboard"];
  48928. if (keyboard) {
  48929. return keyboard.keysLeft;
  48930. }
  48931. return [];
  48932. },
  48933. set: function (value) {
  48934. var keyboard = this.inputs.attached["keyboard"];
  48935. if (keyboard) {
  48936. keyboard.keysLeft = value;
  48937. }
  48938. },
  48939. enumerable: true,
  48940. configurable: true
  48941. });
  48942. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  48943. /**
  48944. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  48945. */
  48946. get: function () {
  48947. var keyboard = this.inputs.attached["keyboard"];
  48948. if (keyboard) {
  48949. return keyboard.keysRight;
  48950. }
  48951. return [];
  48952. },
  48953. set: function (value) {
  48954. var keyboard = this.inputs.attached["keyboard"];
  48955. if (keyboard) {
  48956. keyboard.keysRight = value;
  48957. }
  48958. },
  48959. enumerable: true,
  48960. configurable: true
  48961. });
  48962. /**
  48963. * Attached controls to the current camera.
  48964. * @param element Defines the element the controls should be listened from
  48965. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48966. */
  48967. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  48968. this.inputs.attachElement(element, noPreventDefault);
  48969. };
  48970. /**
  48971. * Detach the current controls from the camera.
  48972. * The camera will stop reacting to inputs.
  48973. * @param element Defines the element to stop listening the inputs from
  48974. */
  48975. FreeCamera.prototype.detachControl = function (element) {
  48976. this.inputs.detachElement(element);
  48977. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  48978. this.cameraRotation = new BABYLON.Vector2(0, 0);
  48979. };
  48980. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  48981. /**
  48982. * Define a collision mask to limit the list of object the camera can collide with
  48983. */
  48984. get: function () {
  48985. return this._collisionMask;
  48986. },
  48987. set: function (mask) {
  48988. this._collisionMask = !isNaN(mask) ? mask : -1;
  48989. },
  48990. enumerable: true,
  48991. configurable: true
  48992. });
  48993. /** @hidden */
  48994. FreeCamera.prototype._collideWithWorld = function (displacement) {
  48995. var globalPosition;
  48996. if (this.parent) {
  48997. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  48998. }
  48999. else {
  49000. globalPosition = this.position;
  49001. }
  49002. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  49003. this._oldPosition.addInPlace(this.ellipsoidOffset);
  49004. if (!this._collider) {
  49005. this._collider = new BABYLON.Collider();
  49006. }
  49007. this._collider._radius = this.ellipsoid;
  49008. this._collider.collisionMask = this._collisionMask;
  49009. //no need for clone, as long as gravity is not on.
  49010. var actualDisplacement = displacement;
  49011. //add gravity to the direction to prevent the dual-collision checking
  49012. if (this.applyGravity) {
  49013. //this prevents mending with cameraDirection, a global variable of the free camera class.
  49014. actualDisplacement = displacement.add(this.getScene().gravity);
  49015. }
  49016. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  49017. };
  49018. /** @hidden */
  49019. FreeCamera.prototype._checkInputs = function () {
  49020. if (!this._localDirection) {
  49021. this._localDirection = BABYLON.Vector3.Zero();
  49022. this._transformedDirection = BABYLON.Vector3.Zero();
  49023. }
  49024. this.inputs.checkInputs();
  49025. _super.prototype._checkInputs.call(this);
  49026. };
  49027. /** @hidden */
  49028. FreeCamera.prototype._decideIfNeedsToMove = function () {
  49029. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  49030. };
  49031. /** @hidden */
  49032. FreeCamera.prototype._updatePosition = function () {
  49033. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  49034. this._collideWithWorld(this.cameraDirection);
  49035. }
  49036. else {
  49037. _super.prototype._updatePosition.call(this);
  49038. }
  49039. };
  49040. /**
  49041. * Destroy the camera and release the current resources hold by it.
  49042. */
  49043. FreeCamera.prototype.dispose = function () {
  49044. this.inputs.clear();
  49045. _super.prototype.dispose.call(this);
  49046. };
  49047. /**
  49048. * Gets the current object class name.
  49049. * @return the class name
  49050. */
  49051. FreeCamera.prototype.getClassName = function () {
  49052. return "FreeCamera";
  49053. };
  49054. __decorate([
  49055. BABYLON.serializeAsVector3()
  49056. ], FreeCamera.prototype, "ellipsoid", void 0);
  49057. __decorate([
  49058. BABYLON.serializeAsVector3()
  49059. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  49060. __decorate([
  49061. BABYLON.serialize()
  49062. ], FreeCamera.prototype, "checkCollisions", void 0);
  49063. __decorate([
  49064. BABYLON.serialize()
  49065. ], FreeCamera.prototype, "applyGravity", void 0);
  49066. return FreeCamera;
  49067. }(BABYLON.TargetCamera));
  49068. BABYLON.FreeCamera = FreeCamera;
  49069. })(BABYLON || (BABYLON = {}));
  49070. //# sourceMappingURL=babylon.freeCamera.js.map
  49071. var BABYLON;
  49072. (function (BABYLON) {
  49073. /**
  49074. * Manage the keyboard inputs to control the movement of an arc rotate camera.
  49075. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49076. */
  49077. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  49078. function ArcRotateCameraKeyboardMoveInput() {
  49079. /**
  49080. * Defines the list of key codes associated with the up action (increase alpha)
  49081. */
  49082. this.keysUp = [38];
  49083. /**
  49084. * Defines the list of key codes associated with the down action (decrease alpha)
  49085. */
  49086. this.keysDown = [40];
  49087. /**
  49088. * Defines the list of key codes associated with the left action (increase beta)
  49089. */
  49090. this.keysLeft = [37];
  49091. /**
  49092. * Defines the list of key codes associated with the right action (decrease beta)
  49093. */
  49094. this.keysRight = [39];
  49095. /**
  49096. * Defines the list of key codes associated with the reset action.
  49097. * Those keys reset the camera to its last stored state (with the method camera.storeState())
  49098. */
  49099. this.keysReset = [220];
  49100. /**
  49101. * Defines the panning sensibility of the inputs.
  49102. * (How fast is the camera paning)
  49103. */
  49104. this.panningSensibility = 50.0;
  49105. /**
  49106. * Defines the zooming sensibility of the inputs.
  49107. * (How fast is the camera zooming)
  49108. */
  49109. this.zoomingSensibility = 25.0;
  49110. /**
  49111. * Defines wether maintaining the alt key down switch the movement mode from
  49112. * orientation to zoom.
  49113. */
  49114. this.useAltToZoom = true;
  49115. /**
  49116. * Rotation speed of the camera
  49117. */
  49118. this.angularSpeed = 0.01;
  49119. this._keys = new Array();
  49120. }
  49121. /**
  49122. * Attach the input controls to a specific dom element to get the input from.
  49123. * @param element Defines the element the controls should be listened from
  49124. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  49125. */
  49126. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  49127. var _this = this;
  49128. if (this._onCanvasBlurObserver) {
  49129. return;
  49130. }
  49131. this._scene = this.camera.getScene();
  49132. this._engine = this._scene.getEngine();
  49133. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  49134. _this._keys = [];
  49135. });
  49136. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  49137. var evt = info.event;
  49138. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  49139. _this._ctrlPressed = evt.ctrlKey;
  49140. _this._altPressed = evt.altKey;
  49141. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  49142. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  49143. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  49144. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  49145. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  49146. var index = _this._keys.indexOf(evt.keyCode);
  49147. if (index === -1) {
  49148. _this._keys.push(evt.keyCode);
  49149. }
  49150. if (evt.preventDefault) {
  49151. if (!noPreventDefault) {
  49152. evt.preventDefault();
  49153. }
  49154. }
  49155. }
  49156. }
  49157. else {
  49158. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  49159. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  49160. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  49161. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  49162. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  49163. var index = _this._keys.indexOf(evt.keyCode);
  49164. if (index >= 0) {
  49165. _this._keys.splice(index, 1);
  49166. }
  49167. if (evt.preventDefault) {
  49168. if (!noPreventDefault) {
  49169. evt.preventDefault();
  49170. }
  49171. }
  49172. }
  49173. }
  49174. });
  49175. };
  49176. /**
  49177. * Detach the current controls from the specified dom element.
  49178. * @param element Defines the element to stop listening the inputs from
  49179. */
  49180. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  49181. if (this._scene) {
  49182. if (this._onKeyboardObserver) {
  49183. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  49184. }
  49185. if (this._onCanvasBlurObserver) {
  49186. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  49187. }
  49188. this._onKeyboardObserver = null;
  49189. this._onCanvasBlurObserver = null;
  49190. }
  49191. this._keys = [];
  49192. };
  49193. /**
  49194. * Update the current camera state depending on the inputs that have been used this frame.
  49195. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  49196. */
  49197. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  49198. if (this._onKeyboardObserver) {
  49199. var camera = this.camera;
  49200. for (var index = 0; index < this._keys.length; index++) {
  49201. var keyCode = this._keys[index];
  49202. if (this.keysLeft.indexOf(keyCode) !== -1) {
  49203. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  49204. camera.inertialPanningX -= 1 / this.panningSensibility;
  49205. }
  49206. else {
  49207. camera.inertialAlphaOffset -= this.angularSpeed;
  49208. }
  49209. }
  49210. else if (this.keysUp.indexOf(keyCode) !== -1) {
  49211. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  49212. camera.inertialPanningY += 1 / this.panningSensibility;
  49213. }
  49214. else if (this._altPressed && this.useAltToZoom) {
  49215. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  49216. }
  49217. else {
  49218. camera.inertialBetaOffset -= this.angularSpeed;
  49219. }
  49220. }
  49221. else if (this.keysRight.indexOf(keyCode) !== -1) {
  49222. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  49223. camera.inertialPanningX += 1 / this.panningSensibility;
  49224. }
  49225. else {
  49226. camera.inertialAlphaOffset += this.angularSpeed;
  49227. }
  49228. }
  49229. else if (this.keysDown.indexOf(keyCode) !== -1) {
  49230. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  49231. camera.inertialPanningY -= 1 / this.panningSensibility;
  49232. }
  49233. else if (this._altPressed && this.useAltToZoom) {
  49234. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  49235. }
  49236. else {
  49237. camera.inertialBetaOffset += this.angularSpeed;
  49238. }
  49239. }
  49240. else if (this.keysReset.indexOf(keyCode) !== -1) {
  49241. if (camera.useInputToRestoreState) {
  49242. camera.restoreState();
  49243. }
  49244. }
  49245. }
  49246. }
  49247. };
  49248. /**
  49249. * Gets the class name of the current intput.
  49250. * @returns the class name
  49251. */
  49252. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  49253. return "ArcRotateCameraKeyboardMoveInput";
  49254. };
  49255. /**
  49256. * Get the friendly name associated with the input class.
  49257. * @returns the input friendly name
  49258. */
  49259. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  49260. return "keyboard";
  49261. };
  49262. __decorate([
  49263. BABYLON.serialize()
  49264. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  49265. __decorate([
  49266. BABYLON.serialize()
  49267. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  49268. __decorate([
  49269. BABYLON.serialize()
  49270. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  49271. __decorate([
  49272. BABYLON.serialize()
  49273. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  49274. __decorate([
  49275. BABYLON.serialize()
  49276. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  49277. __decorate([
  49278. BABYLON.serialize()
  49279. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  49280. __decorate([
  49281. BABYLON.serialize()
  49282. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  49283. __decorate([
  49284. BABYLON.serialize()
  49285. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  49286. __decorate([
  49287. BABYLON.serialize()
  49288. ], ArcRotateCameraKeyboardMoveInput.prototype, "angularSpeed", void 0);
  49289. return ArcRotateCameraKeyboardMoveInput;
  49290. }());
  49291. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  49292. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  49293. })(BABYLON || (BABYLON = {}));
  49294. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  49295. var BABYLON;
  49296. (function (BABYLON) {
  49297. /**
  49298. * Manage the mouse wheel inputs to control an arc rotate camera.
  49299. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49300. */
  49301. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  49302. function ArcRotateCameraMouseWheelInput() {
  49303. /**
  49304. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  49305. */
  49306. this.wheelPrecision = 3.0;
  49307. /**
  49308. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  49309. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  49310. */
  49311. this.wheelDeltaPercentage = 0;
  49312. }
  49313. /**
  49314. * Attach the input controls to a specific dom element to get the input from.
  49315. * @param element Defines the element the controls should be listened from
  49316. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  49317. */
  49318. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  49319. var _this = this;
  49320. this._wheel = function (p, s) {
  49321. //sanity check - this should be a PointerWheel event.
  49322. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL) {
  49323. return;
  49324. }
  49325. var event = p.event;
  49326. var delta = 0;
  49327. if (event.wheelDelta) {
  49328. if (_this.wheelDeltaPercentage) {
  49329. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  49330. if (event.wheelDelta > 0) {
  49331. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  49332. }
  49333. else {
  49334. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  49335. }
  49336. }
  49337. else {
  49338. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  49339. }
  49340. }
  49341. else if (event.detail) {
  49342. delta = -event.detail / _this.wheelPrecision;
  49343. }
  49344. if (delta) {
  49345. _this.camera.inertialRadiusOffset += delta;
  49346. }
  49347. if (event.preventDefault) {
  49348. if (!noPreventDefault) {
  49349. event.preventDefault();
  49350. }
  49351. }
  49352. };
  49353. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  49354. };
  49355. /**
  49356. * Detach the current controls from the specified dom element.
  49357. * @param element Defines the element to stop listening the inputs from
  49358. */
  49359. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  49360. if (this._observer && element) {
  49361. this.camera.getScene().onPointerObservable.remove(this._observer);
  49362. this._observer = null;
  49363. this._wheel = null;
  49364. }
  49365. };
  49366. /**
  49367. * Gets the class name of the current intput.
  49368. * @returns the class name
  49369. */
  49370. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  49371. return "ArcRotateCameraMouseWheelInput";
  49372. };
  49373. /**
  49374. * Get the friendly name associated with the input class.
  49375. * @returns the input friendly name
  49376. */
  49377. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  49378. return "mousewheel";
  49379. };
  49380. __decorate([
  49381. BABYLON.serialize()
  49382. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  49383. __decorate([
  49384. BABYLON.serialize()
  49385. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  49386. return ArcRotateCameraMouseWheelInput;
  49387. }());
  49388. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  49389. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  49390. })(BABYLON || (BABYLON = {}));
  49391. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  49392. var BABYLON;
  49393. (function (BABYLON) {
  49394. /**
  49395. * Manage the pointers inputs to control an arc rotate camera.
  49396. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49397. */
  49398. var ArcRotateCameraPointersInput = /** @class */ (function () {
  49399. function ArcRotateCameraPointersInput() {
  49400. /**
  49401. * Defines the buttons associated with the input to handle camera move.
  49402. */
  49403. this.buttons = [0, 1, 2];
  49404. /**
  49405. * Defines the pointer angular sensibility along the X axis or how fast is the camera rotating.
  49406. */
  49407. this.angularSensibilityX = 1000.0;
  49408. /**
  49409. * Defines the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  49410. */
  49411. this.angularSensibilityY = 1000.0;
  49412. /**
  49413. * Defines the pointer pinch precision or how fast is the camera zooming.
  49414. */
  49415. this.pinchPrecision = 12.0;
  49416. /**
  49417. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  49418. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  49419. */
  49420. this.pinchDeltaPercentage = 0;
  49421. /**
  49422. * Defines the pointer panning sensibility or how fast is the camera moving.
  49423. */
  49424. this.panningSensibility = 1000.0;
  49425. /**
  49426. * Defines whether panning (2 fingers swipe) is enabled through multitouch.
  49427. */
  49428. this.multiTouchPanning = true;
  49429. /**
  49430. * Defines whether panning is enabled for both pan (2 fingers swipe) and zoom (pinch) through multitouch.
  49431. */
  49432. this.multiTouchPanAndZoom = true;
  49433. /**
  49434. * Revers pinch action direction.
  49435. */
  49436. this.pinchInwards = true;
  49437. this._isPanClick = false;
  49438. }
  49439. /**
  49440. * Attach the input controls to a specific dom element to get the input from.
  49441. * @param element Defines the element the controls should be listened from
  49442. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  49443. */
  49444. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  49445. var _this = this;
  49446. var engine = this.camera.getEngine();
  49447. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  49448. var pointA = null;
  49449. var pointB = null;
  49450. var previousPinchSquaredDistance = 0;
  49451. var initialDistance = 0;
  49452. var twoFingerActivityCount = 0;
  49453. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  49454. this._pointerInput = function (p, s) {
  49455. var evt = p.event;
  49456. var isTouch = p.event.pointerType === "touch";
  49457. if (engine.isInVRExclusivePointerMode) {
  49458. return;
  49459. }
  49460. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  49461. return;
  49462. }
  49463. var srcElement = (evt.srcElement || evt.target);
  49464. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  49465. try {
  49466. srcElement.setPointerCapture(evt.pointerId);
  49467. }
  49468. catch (e) {
  49469. //Nothing to do with the error. Execution will continue.
  49470. }
  49471. // Manage panning with pan button click
  49472. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  49473. // manage pointers
  49474. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  49475. if (pointA === null) {
  49476. pointA = cacheSoloPointer;
  49477. }
  49478. else if (pointB === null) {
  49479. pointB = cacheSoloPointer;
  49480. }
  49481. if (!noPreventDefault) {
  49482. evt.preventDefault();
  49483. element.focus();
  49484. }
  49485. }
  49486. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  49487. if (_this.camera.useInputToRestoreState) {
  49488. _this.camera.restoreState();
  49489. }
  49490. }
  49491. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  49492. try {
  49493. srcElement.releasePointerCapture(evt.pointerId);
  49494. }
  49495. catch (e) {
  49496. //Nothing to do with the error.
  49497. }
  49498. cacheSoloPointer = null;
  49499. previousPinchSquaredDistance = 0;
  49500. previousMultiTouchPanPosition.isPaning = false;
  49501. previousMultiTouchPanPosition.isPinching = false;
  49502. twoFingerActivityCount = 0;
  49503. initialDistance = 0;
  49504. if (!isTouch) {
  49505. pointB = null; // Mouse and pen are mono pointer
  49506. }
  49507. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  49508. //but emptying completly pointers collection is required to fix a bug on iPhone :
  49509. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  49510. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  49511. if (engine._badOS) {
  49512. pointA = pointB = null;
  49513. }
  49514. else {
  49515. //only remove the impacted pointer in case of multitouch allowing on most
  49516. //platforms switching from rotate to zoom and pan seamlessly.
  49517. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  49518. pointA = pointB;
  49519. pointB = null;
  49520. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  49521. }
  49522. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  49523. pointB = null;
  49524. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  49525. }
  49526. else {
  49527. pointA = pointB = null;
  49528. }
  49529. }
  49530. if (!noPreventDefault) {
  49531. evt.preventDefault();
  49532. }
  49533. }
  49534. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  49535. if (!noPreventDefault) {
  49536. evt.preventDefault();
  49537. }
  49538. // One button down
  49539. if (pointA && pointB === null && cacheSoloPointer) {
  49540. if (_this.panningSensibility !== 0 &&
  49541. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  49542. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  49543. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  49544. }
  49545. else {
  49546. var offsetX = evt.clientX - cacheSoloPointer.x;
  49547. var offsetY = evt.clientY - cacheSoloPointer.y;
  49548. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  49549. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  49550. }
  49551. cacheSoloPointer.x = evt.clientX;
  49552. cacheSoloPointer.y = evt.clientY;
  49553. }
  49554. // Two buttons down: pinch/pan
  49555. else if (pointA && pointB) {
  49556. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  49557. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  49558. ed.x = evt.clientX;
  49559. ed.y = evt.clientY;
  49560. var direction = _this.pinchInwards ? 1 : -1;
  49561. var distX = pointA.x - pointB.x;
  49562. var distY = pointA.y - pointB.y;
  49563. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  49564. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  49565. if (previousPinchSquaredDistance === 0) {
  49566. initialDistance = pinchDistance;
  49567. previousPinchSquaredDistance = pinchSquaredDistance;
  49568. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  49569. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  49570. return;
  49571. }
  49572. if (_this.multiTouchPanAndZoom) {
  49573. if (_this.pinchDeltaPercentage) {
  49574. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  49575. }
  49576. else {
  49577. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  49578. (_this.pinchPrecision *
  49579. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  49580. direction);
  49581. }
  49582. if (_this.panningSensibility !== 0) {
  49583. var pointersCenterX = (pointA.x + pointB.x) / 2;
  49584. var pointersCenterY = (pointA.y + pointB.y) / 2;
  49585. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  49586. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  49587. previousMultiTouchPanPosition.x = pointersCenterX;
  49588. previousMultiTouchPanPosition.y = pointersCenterY;
  49589. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  49590. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  49591. }
  49592. }
  49593. else {
  49594. twoFingerActivityCount++;
  49595. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  49596. if (_this.pinchDeltaPercentage) {
  49597. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  49598. }
  49599. else {
  49600. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  49601. (_this.pinchPrecision *
  49602. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  49603. direction);
  49604. }
  49605. previousMultiTouchPanPosition.isPaning = false;
  49606. previousMultiTouchPanPosition.isPinching = true;
  49607. }
  49608. else {
  49609. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  49610. if (!previousMultiTouchPanPosition.isPaning) {
  49611. previousMultiTouchPanPosition.isPaning = true;
  49612. previousMultiTouchPanPosition.isPinching = false;
  49613. previousMultiTouchPanPosition.x = ed.x;
  49614. previousMultiTouchPanPosition.y = ed.y;
  49615. return;
  49616. }
  49617. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  49618. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  49619. }
  49620. }
  49621. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  49622. previousMultiTouchPanPosition.x = ed.x;
  49623. previousMultiTouchPanPosition.y = ed.y;
  49624. }
  49625. }
  49626. previousPinchSquaredDistance = pinchSquaredDistance;
  49627. }
  49628. }
  49629. };
  49630. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  49631. this._onContextMenu = function (evt) {
  49632. evt.preventDefault();
  49633. };
  49634. if (!this.camera._useCtrlForPanning) {
  49635. element.addEventListener("contextmenu", this._onContextMenu, false);
  49636. }
  49637. this._onLostFocus = function () {
  49638. //this._keys = [];
  49639. pointA = pointB = null;
  49640. previousPinchSquaredDistance = 0;
  49641. previousMultiTouchPanPosition.isPaning = false;
  49642. previousMultiTouchPanPosition.isPinching = false;
  49643. twoFingerActivityCount = 0;
  49644. cacheSoloPointer = null;
  49645. initialDistance = 0;
  49646. };
  49647. this._onMouseMove = function (evt) {
  49648. if (!engine.isPointerLock) {
  49649. return;
  49650. }
  49651. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  49652. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  49653. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  49654. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  49655. if (!noPreventDefault) {
  49656. evt.preventDefault();
  49657. }
  49658. };
  49659. this._onGestureStart = function (e) {
  49660. if (window.MSGesture === undefined) {
  49661. return;
  49662. }
  49663. if (!_this._MSGestureHandler) {
  49664. _this._MSGestureHandler = new MSGesture();
  49665. _this._MSGestureHandler.target = element;
  49666. }
  49667. _this._MSGestureHandler.addPointer(e.pointerId);
  49668. };
  49669. this._onGesture = function (e) {
  49670. _this.camera.radius *= e.scale;
  49671. if (e.preventDefault) {
  49672. if (!noPreventDefault) {
  49673. e.stopPropagation();
  49674. e.preventDefault();
  49675. }
  49676. }
  49677. };
  49678. element.addEventListener("mousemove", this._onMouseMove, false);
  49679. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  49680. element.addEventListener("MSGestureChange", this._onGesture, false);
  49681. BABYLON.Tools.RegisterTopRootEvents([
  49682. { name: "blur", handler: this._onLostFocus }
  49683. ]);
  49684. };
  49685. /**
  49686. * Detach the current controls from the specified dom element.
  49687. * @param element Defines the element to stop listening the inputs from
  49688. */
  49689. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  49690. if (this._onLostFocus) {
  49691. BABYLON.Tools.UnregisterTopRootEvents([
  49692. { name: "blur", handler: this._onLostFocus }
  49693. ]);
  49694. }
  49695. if (element && this._observer) {
  49696. this.camera.getScene().onPointerObservable.remove(this._observer);
  49697. this._observer = null;
  49698. if (this._onContextMenu) {
  49699. element.removeEventListener("contextmenu", this._onContextMenu);
  49700. }
  49701. if (this._onMouseMove) {
  49702. element.removeEventListener("mousemove", this._onMouseMove);
  49703. }
  49704. if (this._onGestureStart) {
  49705. element.removeEventListener("MSPointerDown", this._onGestureStart);
  49706. }
  49707. if (this._onGesture) {
  49708. element.removeEventListener("MSGestureChange", this._onGesture);
  49709. }
  49710. this._isPanClick = false;
  49711. this.pinchInwards = true;
  49712. this._onMouseMove = null;
  49713. this._onGestureStart = null;
  49714. this._onGesture = null;
  49715. this._MSGestureHandler = null;
  49716. this._onLostFocus = null;
  49717. this._onContextMenu = null;
  49718. }
  49719. };
  49720. /**
  49721. * Gets the class name of the current intput.
  49722. * @returns the class name
  49723. */
  49724. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  49725. return "ArcRotateCameraPointersInput";
  49726. };
  49727. /**
  49728. * Get the friendly name associated with the input class.
  49729. * @returns the input friendly name
  49730. */
  49731. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  49732. return "pointers";
  49733. };
  49734. __decorate([
  49735. BABYLON.serialize()
  49736. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  49737. __decorate([
  49738. BABYLON.serialize()
  49739. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  49740. __decorate([
  49741. BABYLON.serialize()
  49742. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  49743. __decorate([
  49744. BABYLON.serialize()
  49745. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  49746. __decorate([
  49747. BABYLON.serialize()
  49748. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  49749. __decorate([
  49750. BABYLON.serialize()
  49751. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  49752. __decorate([
  49753. BABYLON.serialize()
  49754. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  49755. __decorate([
  49756. BABYLON.serialize()
  49757. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  49758. return ArcRotateCameraPointersInput;
  49759. }());
  49760. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  49761. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  49762. })(BABYLON || (BABYLON = {}));
  49763. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  49764. var BABYLON;
  49765. (function (BABYLON) {
  49766. /**
  49767. * Default Inputs manager for the ArcRotateCamera.
  49768. * It groups all the default supported inputs for ease of use.
  49769. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49770. */
  49771. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  49772. __extends(ArcRotateCameraInputsManager, _super);
  49773. /**
  49774. * Instantiates a new ArcRotateCameraInputsManager.
  49775. * @param camera Defines the camera the inputs belong to
  49776. */
  49777. function ArcRotateCameraInputsManager(camera) {
  49778. return _super.call(this, camera) || this;
  49779. }
  49780. /**
  49781. * Add mouse wheel input support to the input manager.
  49782. * @returns the current input manager
  49783. */
  49784. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  49785. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  49786. return this;
  49787. };
  49788. /**
  49789. * Add pointers input support to the input manager.
  49790. * @returns the current input manager
  49791. */
  49792. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  49793. this.add(new BABYLON.ArcRotateCameraPointersInput());
  49794. return this;
  49795. };
  49796. /**
  49797. * Add keyboard input support to the input manager.
  49798. * @returns the current input manager
  49799. */
  49800. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  49801. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  49802. return this;
  49803. };
  49804. /**
  49805. * Add orientation input support to the input manager.
  49806. * @returns the current input manager
  49807. */
  49808. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  49809. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  49810. return this;
  49811. };
  49812. return ArcRotateCameraInputsManager;
  49813. }(BABYLON.CameraInputsManager));
  49814. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  49815. })(BABYLON || (BABYLON = {}));
  49816. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  49817. var BABYLON;
  49818. (function (BABYLON) {
  49819. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  49820. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  49821. });
  49822. /**
  49823. * This represents an orbital type of camera.
  49824. *
  49825. * 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.
  49826. * 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.
  49827. * @see http://doc.babylonjs.com/babylon101/cameras#arc-rotate-camera
  49828. */
  49829. var ArcRotateCamera = /** @class */ (function (_super) {
  49830. __extends(ArcRotateCamera, _super);
  49831. /**
  49832. * Instantiates a new ArcRotateCamera in a given scene
  49833. * @param name Defines the name of the camera
  49834. * @param alpha Defines the camera rotation along the logitudinal axis
  49835. * @param beta Defines the camera rotation along the latitudinal axis
  49836. * @param radius Defines the camera distance from its target
  49837. * @param target Defines the camera target
  49838. * @param scene Defines the scene the camera belongs to
  49839. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  49840. */
  49841. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  49842. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  49843. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  49844. /**
  49845. * Current inertia value on the longitudinal axis.
  49846. * The bigger this number the longer it will take for the camera to stop.
  49847. */
  49848. _this.inertialAlphaOffset = 0;
  49849. /**
  49850. * Current inertia value on the latitudinal axis.
  49851. * The bigger this number the longer it will take for the camera to stop.
  49852. */
  49853. _this.inertialBetaOffset = 0;
  49854. /**
  49855. * Current inertia value on the radius axis.
  49856. * The bigger this number the longer it will take for the camera to stop.
  49857. */
  49858. _this.inertialRadiusOffset = 0;
  49859. /**
  49860. * Minimum allowed angle on the longitudinal axis.
  49861. * This can help limiting how the Camera is able to move in the scene.
  49862. */
  49863. _this.lowerAlphaLimit = null;
  49864. /**
  49865. * Maximum allowed angle on the longitudinal axis.
  49866. * This can help limiting how the Camera is able to move in the scene.
  49867. */
  49868. _this.upperAlphaLimit = null;
  49869. /**
  49870. * Minimum allowed angle on the latitudinal axis.
  49871. * This can help limiting how the Camera is able to move in the scene.
  49872. */
  49873. _this.lowerBetaLimit = 0.01;
  49874. /**
  49875. * Maximum allowed angle on the latitudinal axis.
  49876. * This can help limiting how the Camera is able to move in the scene.
  49877. */
  49878. _this.upperBetaLimit = Math.PI;
  49879. /**
  49880. * Minimum allowed distance of the camera to the target (The camera can not get closer).
  49881. * This can help limiting how the Camera is able to move in the scene.
  49882. */
  49883. _this.lowerRadiusLimit = null;
  49884. /**
  49885. * Maximum allowed distance of the camera to the target (The camera can not get further).
  49886. * This can help limiting how the Camera is able to move in the scene.
  49887. */
  49888. _this.upperRadiusLimit = null;
  49889. /**
  49890. * Defines the current inertia value used during panning of the camera along the X axis.
  49891. */
  49892. _this.inertialPanningX = 0;
  49893. /**
  49894. * Defines the current inertia value used during panning of the camera along the Y axis.
  49895. */
  49896. _this.inertialPanningY = 0;
  49897. /**
  49898. * Defines the distance used to consider the camera in pan mode vs pinch/zoom.
  49899. * Basically if your fingers moves away from more than this distance you will be considered
  49900. * in pinch mode.
  49901. */
  49902. _this.pinchToPanMaxDistance = 20;
  49903. /**
  49904. * Defines the maximum distance the camera can pan.
  49905. * This could help keeping the cammera always in your scene.
  49906. */
  49907. _this.panningDistanceLimit = null;
  49908. /**
  49909. * Defines the target of the camera before paning.
  49910. */
  49911. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  49912. /**
  49913. * Defines the value of the inertia used during panning.
  49914. * 0 would mean stop inertia and one would mean no decelleration at all.
  49915. */
  49916. _this.panningInertia = 0.9;
  49917. //-- end properties for backward compatibility for inputs
  49918. /**
  49919. * Defines how much the radius should be scaled while zomming on a particular mesh (through the zoomOn function)
  49920. */
  49921. _this.zoomOnFactor = 1;
  49922. /**
  49923. * Defines a screen offset for the camera position.
  49924. */
  49925. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  49926. /**
  49927. * Allows the camera to be completely reversed.
  49928. * If false the camera can not arrive upside down.
  49929. */
  49930. _this.allowUpsideDown = true;
  49931. /**
  49932. * Define if double tap/click is used to restore the previously saved state of the camera.
  49933. */
  49934. _this.useInputToRestoreState = true;
  49935. /** @hidden */
  49936. _this._viewMatrix = new BABYLON.Matrix();
  49937. /**
  49938. * Defines the allowed panning axis.
  49939. */
  49940. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  49941. /**
  49942. * Observable triggered when the mesh target has been changed on the camera.
  49943. */
  49944. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  49945. /**
  49946. * Defines whether the camera should check collision with the objects oh the scene.
  49947. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#how-can-i-do-this
  49948. */
  49949. _this.checkCollisions = false;
  49950. /**
  49951. * Defines the collision radius of the camera.
  49952. * This simulates a sphere around the camera.
  49953. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  49954. */
  49955. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  49956. _this._previousPosition = BABYLON.Vector3.Zero();
  49957. _this._collisionVelocity = BABYLON.Vector3.Zero();
  49958. _this._newPosition = BABYLON.Vector3.Zero();
  49959. _this._computationVector = BABYLON.Vector3.Zero();
  49960. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  49961. if (collidedMesh === void 0) { collidedMesh = null; }
  49962. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  49963. newPosition.multiplyInPlace(_this._collider._radius);
  49964. }
  49965. if (!collidedMesh) {
  49966. _this._previousPosition.copyFrom(_this.position);
  49967. }
  49968. else {
  49969. _this.setPosition(newPosition);
  49970. if (_this.onCollide) {
  49971. _this.onCollide(collidedMesh);
  49972. }
  49973. }
  49974. // Recompute because of constraints
  49975. var cosa = Math.cos(_this.alpha);
  49976. var sina = Math.sin(_this.alpha);
  49977. var cosb = Math.cos(_this.beta);
  49978. var sinb = Math.sin(_this.beta);
  49979. if (sinb === 0) {
  49980. sinb = 0.0001;
  49981. }
  49982. var target = _this._getTargetPosition();
  49983. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  49984. target.addToRef(_this._computationVector, _this._newPosition);
  49985. _this.position.copyFrom(_this._newPosition);
  49986. var up = _this.upVector;
  49987. if (_this.allowUpsideDown && _this.beta < 0) {
  49988. up = up.clone();
  49989. up = up.negate();
  49990. }
  49991. _this._computeViewMatrix(_this.position, target, up);
  49992. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  49993. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  49994. _this._collisionTriggered = false;
  49995. };
  49996. _this._target = BABYLON.Vector3.Zero();
  49997. if (target) {
  49998. _this.setTarget(target);
  49999. }
  50000. _this.alpha = alpha;
  50001. _this.beta = beta;
  50002. _this.radius = radius;
  50003. _this.getViewMatrix();
  50004. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  50005. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  50006. return _this;
  50007. }
  50008. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  50009. /**
  50010. * Defines the target point of the camera.
  50011. * The camera looks towards it form the radius distance.
  50012. */
  50013. get: function () {
  50014. return this._target;
  50015. },
  50016. set: function (value) {
  50017. this.setTarget(value);
  50018. },
  50019. enumerable: true,
  50020. configurable: true
  50021. });
  50022. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  50023. //-- begin properties for backward compatibility for inputs
  50024. /**
  50025. * Gets or Set the pointer angular sensibility along the X axis or how fast is the camera rotating.
  50026. */
  50027. get: function () {
  50028. var pointers = this.inputs.attached["pointers"];
  50029. if (pointers) {
  50030. return pointers.angularSensibilityX;
  50031. }
  50032. return 0;
  50033. },
  50034. set: function (value) {
  50035. var pointers = this.inputs.attached["pointers"];
  50036. if (pointers) {
  50037. pointers.angularSensibilityX = value;
  50038. }
  50039. },
  50040. enumerable: true,
  50041. configurable: true
  50042. });
  50043. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  50044. /**
  50045. * Gets or Set the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  50046. */
  50047. get: function () {
  50048. var pointers = this.inputs.attached["pointers"];
  50049. if (pointers) {
  50050. return pointers.angularSensibilityY;
  50051. }
  50052. return 0;
  50053. },
  50054. set: function (value) {
  50055. var pointers = this.inputs.attached["pointers"];
  50056. if (pointers) {
  50057. pointers.angularSensibilityY = value;
  50058. }
  50059. },
  50060. enumerable: true,
  50061. configurable: true
  50062. });
  50063. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  50064. /**
  50065. * Gets or Set the pointer pinch precision or how fast is the camera zooming.
  50066. */
  50067. get: function () {
  50068. var pointers = this.inputs.attached["pointers"];
  50069. if (pointers) {
  50070. return pointers.pinchPrecision;
  50071. }
  50072. return 0;
  50073. },
  50074. set: function (value) {
  50075. var pointers = this.inputs.attached["pointers"];
  50076. if (pointers) {
  50077. pointers.pinchPrecision = value;
  50078. }
  50079. },
  50080. enumerable: true,
  50081. configurable: true
  50082. });
  50083. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  50084. /**
  50085. * Gets or Set the pointer pinch delta percentage or how fast is the camera zooming.
  50086. * It will be used instead of pinchDeltaPrecision if different from 0.
  50087. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  50088. */
  50089. get: function () {
  50090. var pointers = this.inputs.attached["pointers"];
  50091. if (pointers) {
  50092. return pointers.pinchDeltaPercentage;
  50093. }
  50094. return 0;
  50095. },
  50096. set: function (value) {
  50097. var pointers = this.inputs.attached["pointers"];
  50098. if (pointers) {
  50099. pointers.pinchDeltaPercentage = value;
  50100. }
  50101. },
  50102. enumerable: true,
  50103. configurable: true
  50104. });
  50105. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  50106. /**
  50107. * Gets or Set the pointer panning sensibility or how fast is the camera moving.
  50108. */
  50109. get: function () {
  50110. var pointers = this.inputs.attached["pointers"];
  50111. if (pointers) {
  50112. return pointers.panningSensibility;
  50113. }
  50114. return 0;
  50115. },
  50116. set: function (value) {
  50117. var pointers = this.inputs.attached["pointers"];
  50118. if (pointers) {
  50119. pointers.panningSensibility = value;
  50120. }
  50121. },
  50122. enumerable: true,
  50123. configurable: true
  50124. });
  50125. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  50126. /**
  50127. * Gets or Set the list of keyboard keys used to control beta angle in a positive direction.
  50128. */
  50129. get: function () {
  50130. var keyboard = this.inputs.attached["keyboard"];
  50131. if (keyboard) {
  50132. return keyboard.keysUp;
  50133. }
  50134. return [];
  50135. },
  50136. set: function (value) {
  50137. var keyboard = this.inputs.attached["keyboard"];
  50138. if (keyboard) {
  50139. keyboard.keysUp = value;
  50140. }
  50141. },
  50142. enumerable: true,
  50143. configurable: true
  50144. });
  50145. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  50146. /**
  50147. * Gets or Set the list of keyboard keys used to control beta angle in a negative direction.
  50148. */
  50149. get: function () {
  50150. var keyboard = this.inputs.attached["keyboard"];
  50151. if (keyboard) {
  50152. return keyboard.keysDown;
  50153. }
  50154. return [];
  50155. },
  50156. set: function (value) {
  50157. var keyboard = this.inputs.attached["keyboard"];
  50158. if (keyboard) {
  50159. keyboard.keysDown = value;
  50160. }
  50161. },
  50162. enumerable: true,
  50163. configurable: true
  50164. });
  50165. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  50166. /**
  50167. * Gets or Set the list of keyboard keys used to control alpha angle in a negative direction.
  50168. */
  50169. get: function () {
  50170. var keyboard = this.inputs.attached["keyboard"];
  50171. if (keyboard) {
  50172. return keyboard.keysLeft;
  50173. }
  50174. return [];
  50175. },
  50176. set: function (value) {
  50177. var keyboard = this.inputs.attached["keyboard"];
  50178. if (keyboard) {
  50179. keyboard.keysLeft = value;
  50180. }
  50181. },
  50182. enumerable: true,
  50183. configurable: true
  50184. });
  50185. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  50186. /**
  50187. * Gets or Set the list of keyboard keys used to control alpha angle in a positive direction.
  50188. */
  50189. get: function () {
  50190. var keyboard = this.inputs.attached["keyboard"];
  50191. if (keyboard) {
  50192. return keyboard.keysRight;
  50193. }
  50194. return [];
  50195. },
  50196. set: function (value) {
  50197. var keyboard = this.inputs.attached["keyboard"];
  50198. if (keyboard) {
  50199. keyboard.keysRight = value;
  50200. }
  50201. },
  50202. enumerable: true,
  50203. configurable: true
  50204. });
  50205. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  50206. /**
  50207. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  50208. */
  50209. get: function () {
  50210. var mousewheel = this.inputs.attached["mousewheel"];
  50211. if (mousewheel) {
  50212. return mousewheel.wheelPrecision;
  50213. }
  50214. return 0;
  50215. },
  50216. set: function (value) {
  50217. var mousewheel = this.inputs.attached["mousewheel"];
  50218. if (mousewheel) {
  50219. mousewheel.wheelPrecision = value;
  50220. }
  50221. },
  50222. enumerable: true,
  50223. configurable: true
  50224. });
  50225. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  50226. /**
  50227. * Gets or Set the mouse wheel delta percentage or how fast is the camera zooming.
  50228. * It will be used instead of pinchDeltaPrecision if different from 0.
  50229. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  50230. */
  50231. get: function () {
  50232. var mousewheel = this.inputs.attached["mousewheel"];
  50233. if (mousewheel) {
  50234. return mousewheel.wheelDeltaPercentage;
  50235. }
  50236. return 0;
  50237. },
  50238. set: function (value) {
  50239. var mousewheel = this.inputs.attached["mousewheel"];
  50240. if (mousewheel) {
  50241. mousewheel.wheelDeltaPercentage = value;
  50242. }
  50243. },
  50244. enumerable: true,
  50245. configurable: true
  50246. });
  50247. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  50248. /**
  50249. * Gets the bouncing behavior of the camera if it has been enabled.
  50250. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  50251. */
  50252. get: function () {
  50253. return this._bouncingBehavior;
  50254. },
  50255. enumerable: true,
  50256. configurable: true
  50257. });
  50258. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  50259. /**
  50260. * Defines if the bouncing behavior of the camera is enabled on the camera.
  50261. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  50262. */
  50263. get: function () {
  50264. return this._bouncingBehavior != null;
  50265. },
  50266. set: function (value) {
  50267. if (value === this.useBouncingBehavior) {
  50268. return;
  50269. }
  50270. if (value) {
  50271. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  50272. this.addBehavior(this._bouncingBehavior);
  50273. }
  50274. else if (this._bouncingBehavior) {
  50275. this.removeBehavior(this._bouncingBehavior);
  50276. this._bouncingBehavior = null;
  50277. }
  50278. },
  50279. enumerable: true,
  50280. configurable: true
  50281. });
  50282. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  50283. /**
  50284. * Gets the framing behavior of the camera if it has been enabled.
  50285. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  50286. */
  50287. get: function () {
  50288. return this._framingBehavior;
  50289. },
  50290. enumerable: true,
  50291. configurable: true
  50292. });
  50293. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  50294. /**
  50295. * Defines if the framing behavior of the camera is enabled on the camera.
  50296. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  50297. */
  50298. get: function () {
  50299. return this._framingBehavior != null;
  50300. },
  50301. set: function (value) {
  50302. if (value === this.useFramingBehavior) {
  50303. return;
  50304. }
  50305. if (value) {
  50306. this._framingBehavior = new BABYLON.FramingBehavior();
  50307. this.addBehavior(this._framingBehavior);
  50308. }
  50309. else if (this._framingBehavior) {
  50310. this.removeBehavior(this._framingBehavior);
  50311. this._framingBehavior = null;
  50312. }
  50313. },
  50314. enumerable: true,
  50315. configurable: true
  50316. });
  50317. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  50318. /**
  50319. * Gets the auto rotation behavior of the camera if it has been enabled.
  50320. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  50321. */
  50322. get: function () {
  50323. return this._autoRotationBehavior;
  50324. },
  50325. enumerable: true,
  50326. configurable: true
  50327. });
  50328. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  50329. /**
  50330. * Defines if the auto rotation behavior of the camera is enabled on the camera.
  50331. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  50332. */
  50333. get: function () {
  50334. return this._autoRotationBehavior != null;
  50335. },
  50336. set: function (value) {
  50337. if (value === this.useAutoRotationBehavior) {
  50338. return;
  50339. }
  50340. if (value) {
  50341. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  50342. this.addBehavior(this._autoRotationBehavior);
  50343. }
  50344. else if (this._autoRotationBehavior) {
  50345. this.removeBehavior(this._autoRotationBehavior);
  50346. this._autoRotationBehavior = null;
  50347. }
  50348. },
  50349. enumerable: true,
  50350. configurable: true
  50351. });
  50352. // Cache
  50353. /** @hidden */
  50354. ArcRotateCamera.prototype._initCache = function () {
  50355. _super.prototype._initCache.call(this);
  50356. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  50357. this._cache.alpha = undefined;
  50358. this._cache.beta = undefined;
  50359. this._cache.radius = undefined;
  50360. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  50361. };
  50362. /** @hidden */
  50363. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  50364. if (!ignoreParentClass) {
  50365. _super.prototype._updateCache.call(this);
  50366. }
  50367. this._cache._target.copyFrom(this._getTargetPosition());
  50368. this._cache.alpha = this.alpha;
  50369. this._cache.beta = this.beta;
  50370. this._cache.radius = this.radius;
  50371. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  50372. };
  50373. ArcRotateCamera.prototype._getTargetPosition = function () {
  50374. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  50375. var pos = this._targetHost.getAbsolutePosition();
  50376. if (this._targetBoundingCenter) {
  50377. pos.addToRef(this._targetBoundingCenter, this._target);
  50378. }
  50379. else {
  50380. this._target.copyFrom(pos);
  50381. }
  50382. }
  50383. var lockedTargetPosition = this._getLockedTargetPosition();
  50384. if (lockedTargetPosition) {
  50385. return lockedTargetPosition;
  50386. }
  50387. return this._target;
  50388. };
  50389. /**
  50390. * Stores the current state of the camera (alpha, beta, radius and target)
  50391. * @returns the camera itself
  50392. */
  50393. ArcRotateCamera.prototype.storeState = function () {
  50394. this._storedAlpha = this.alpha;
  50395. this._storedBeta = this.beta;
  50396. this._storedRadius = this.radius;
  50397. this._storedTarget = this._getTargetPosition().clone();
  50398. return _super.prototype.storeState.call(this);
  50399. };
  50400. /**
  50401. * @hidden
  50402. * Restored camera state. You must call storeState() first
  50403. */
  50404. ArcRotateCamera.prototype._restoreStateValues = function () {
  50405. if (!_super.prototype._restoreStateValues.call(this)) {
  50406. return false;
  50407. }
  50408. this.alpha = this._storedAlpha;
  50409. this.beta = this._storedBeta;
  50410. this.radius = this._storedRadius;
  50411. this.setTarget(this._storedTarget.clone());
  50412. this.inertialAlphaOffset = 0;
  50413. this.inertialBetaOffset = 0;
  50414. this.inertialRadiusOffset = 0;
  50415. this.inertialPanningX = 0;
  50416. this.inertialPanningY = 0;
  50417. return true;
  50418. };
  50419. // Synchronized
  50420. /** @hidden */
  50421. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  50422. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  50423. return false;
  50424. }
  50425. return this._cache._target.equals(this._getTargetPosition())
  50426. && this._cache.alpha === this.alpha
  50427. && this._cache.beta === this.beta
  50428. && this._cache.radius === this.radius
  50429. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  50430. };
  50431. /**
  50432. * Attached controls to the current camera.
  50433. * @param element Defines the element the controls should be listened from
  50434. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  50435. * @param useCtrlForPanning Defines whether ctrl is used for paning within the controls
  50436. * @param panningMouseButton Defines whether panning is allowed through mouse click button
  50437. */
  50438. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  50439. var _this = this;
  50440. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  50441. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  50442. this._useCtrlForPanning = useCtrlForPanning;
  50443. this._panningMouseButton = panningMouseButton;
  50444. this.inputs.attachElement(element, noPreventDefault);
  50445. this._reset = function () {
  50446. _this.inertialAlphaOffset = 0;
  50447. _this.inertialBetaOffset = 0;
  50448. _this.inertialRadiusOffset = 0;
  50449. _this.inertialPanningX = 0;
  50450. _this.inertialPanningY = 0;
  50451. };
  50452. };
  50453. /**
  50454. * Detach the current controls from the camera.
  50455. * The camera will stop reacting to inputs.
  50456. * @param element Defines the element to stop listening the inputs from
  50457. */
  50458. ArcRotateCamera.prototype.detachControl = function (element) {
  50459. this.inputs.detachElement(element);
  50460. if (this._reset) {
  50461. this._reset();
  50462. }
  50463. };
  50464. /** @hidden */
  50465. ArcRotateCamera.prototype._checkInputs = function () {
  50466. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  50467. if (this._collisionTriggered) {
  50468. return;
  50469. }
  50470. this.inputs.checkInputs();
  50471. // Inertia
  50472. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  50473. var inertialAlphaOffset = this.inertialAlphaOffset;
  50474. if (this.beta <= 0) {
  50475. inertialAlphaOffset *= -1;
  50476. }
  50477. if (this.getScene().useRightHandedSystem) {
  50478. inertialAlphaOffset *= -1;
  50479. }
  50480. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0) {
  50481. inertialAlphaOffset *= -1;
  50482. }
  50483. this.alpha += inertialAlphaOffset;
  50484. this.beta += this.inertialBetaOffset;
  50485. this.radius -= this.inertialRadiusOffset;
  50486. this.inertialAlphaOffset *= this.inertia;
  50487. this.inertialBetaOffset *= this.inertia;
  50488. this.inertialRadiusOffset *= this.inertia;
  50489. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon) {
  50490. this.inertialAlphaOffset = 0;
  50491. }
  50492. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon) {
  50493. this.inertialBetaOffset = 0;
  50494. }
  50495. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon) {
  50496. this.inertialRadiusOffset = 0;
  50497. }
  50498. }
  50499. // Panning inertia
  50500. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  50501. if (!this._localDirection) {
  50502. this._localDirection = BABYLON.Vector3.Zero();
  50503. this._transformedDirection = BABYLON.Vector3.Zero();
  50504. }
  50505. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  50506. this._localDirection.multiplyInPlace(this.panningAxis);
  50507. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  50508. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  50509. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  50510. if (!this.panningAxis.y) {
  50511. this._transformedDirection.y = 0;
  50512. }
  50513. if (!this._targetHost) {
  50514. if (this.panningDistanceLimit) {
  50515. this._transformedDirection.addInPlace(this._target);
  50516. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  50517. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  50518. this._target.copyFrom(this._transformedDirection);
  50519. }
  50520. }
  50521. else {
  50522. this._target.addInPlace(this._transformedDirection);
  50523. }
  50524. }
  50525. this.inertialPanningX *= this.panningInertia;
  50526. this.inertialPanningY *= this.panningInertia;
  50527. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon) {
  50528. this.inertialPanningX = 0;
  50529. }
  50530. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon) {
  50531. this.inertialPanningY = 0;
  50532. }
  50533. }
  50534. // Limits
  50535. this._checkLimits();
  50536. _super.prototype._checkInputs.call(this);
  50537. };
  50538. ArcRotateCamera.prototype._checkLimits = function () {
  50539. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  50540. if (this.allowUpsideDown && this.beta > Math.PI) {
  50541. this.beta = this.beta - (2 * Math.PI);
  50542. }
  50543. }
  50544. else {
  50545. if (this.beta < this.lowerBetaLimit) {
  50546. this.beta = this.lowerBetaLimit;
  50547. }
  50548. }
  50549. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  50550. if (this.allowUpsideDown && this.beta < -Math.PI) {
  50551. this.beta = this.beta + (2 * Math.PI);
  50552. }
  50553. }
  50554. else {
  50555. if (this.beta > this.upperBetaLimit) {
  50556. this.beta = this.upperBetaLimit;
  50557. }
  50558. }
  50559. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  50560. this.alpha = this.lowerAlphaLimit;
  50561. }
  50562. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  50563. this.alpha = this.upperAlphaLimit;
  50564. }
  50565. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  50566. this.radius = this.lowerRadiusLimit;
  50567. }
  50568. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  50569. this.radius = this.upperRadiusLimit;
  50570. }
  50571. };
  50572. /**
  50573. * Rebuilds angles (alpha, beta) and radius from the give position and target.
  50574. */
  50575. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  50576. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  50577. this.radius = this._computationVector.length();
  50578. if (this.radius === 0) {
  50579. this.radius = 0.0001; // Just to avoid division by zero
  50580. }
  50581. // Alpha
  50582. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  50583. if (this._computationVector.z < 0) {
  50584. this.alpha = 2 * Math.PI - this.alpha;
  50585. }
  50586. // Beta
  50587. this.beta = Math.acos(this._computationVector.y / this.radius);
  50588. this._checkLimits();
  50589. };
  50590. /**
  50591. * Use a position to define the current camera related information like aplha, beta and radius
  50592. * @param position Defines the position to set the camera at
  50593. */
  50594. ArcRotateCamera.prototype.setPosition = function (position) {
  50595. if (this.position.equals(position)) {
  50596. return;
  50597. }
  50598. this.position.copyFrom(position);
  50599. this.rebuildAnglesAndRadius();
  50600. };
  50601. /**
  50602. * Defines the target the camera should look at.
  50603. * This will automatically adapt alpha beta and radius to fit within the new target.
  50604. * @param target Defines the new target as a Vector or a mesh
  50605. * @param toBoundingCenter In case of a mesh target, defines wether to target the mesh position or its bounding information center
  50606. * @param allowSamePosition If false, prevents reapplying the new computed position if it is identical to the current one (optim)
  50607. */
  50608. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  50609. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  50610. if (allowSamePosition === void 0) { allowSamePosition = false; }
  50611. if (target.getBoundingInfo) {
  50612. if (toBoundingCenter) {
  50613. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  50614. }
  50615. else {
  50616. this._targetBoundingCenter = null;
  50617. }
  50618. this._targetHost = target;
  50619. this._target = this._getTargetPosition();
  50620. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  50621. }
  50622. else {
  50623. var newTarget = target;
  50624. var currentTarget = this._getTargetPosition();
  50625. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  50626. return;
  50627. }
  50628. this._targetHost = null;
  50629. this._target = newTarget;
  50630. this._targetBoundingCenter = null;
  50631. this.onMeshTargetChangedObservable.notifyObservers(null);
  50632. }
  50633. this.rebuildAnglesAndRadius();
  50634. };
  50635. /** @hidden */
  50636. ArcRotateCamera.prototype._getViewMatrix = function () {
  50637. // Compute
  50638. var cosa = Math.cos(this.alpha);
  50639. var sina = Math.sin(this.alpha);
  50640. var cosb = Math.cos(this.beta);
  50641. var sinb = Math.sin(this.beta);
  50642. if (sinb === 0) {
  50643. sinb = 0.0001;
  50644. }
  50645. var target = this._getTargetPosition();
  50646. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  50647. target.addToRef(this._computationVector, this._newPosition);
  50648. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  50649. if (!this._collider) {
  50650. this._collider = new BABYLON.Collider();
  50651. }
  50652. this._collider._radius = this.collisionRadius;
  50653. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  50654. this._collisionTriggered = true;
  50655. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  50656. }
  50657. else {
  50658. this.position.copyFrom(this._newPosition);
  50659. var up = this.upVector;
  50660. if (this.allowUpsideDown && sinb < 0) {
  50661. up = up.clone();
  50662. up = up.negate();
  50663. }
  50664. this._computeViewMatrix(this.position, target, up);
  50665. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  50666. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  50667. }
  50668. this._currentTarget = target;
  50669. return this._viewMatrix;
  50670. };
  50671. /**
  50672. * Zooms on a mesh to be at the min distance where we could see it fully in the current viewport.
  50673. * @param meshes Defines the mesh to zoom on
  50674. * @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)
  50675. */
  50676. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  50677. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  50678. meshes = meshes || this.getScene().meshes;
  50679. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  50680. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  50681. this.radius = distance * this.zoomOnFactor;
  50682. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  50683. };
  50684. /**
  50685. * Focus on a mesh or a bounding box. This adapts the target and maxRadius if necessary but does not update the current radius.
  50686. * The target will be changed but the radius
  50687. * @param meshesOrMinMaxVectorAndDistance Defines the mesh or bounding info to focus on
  50688. * @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)
  50689. */
  50690. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  50691. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  50692. var meshesOrMinMaxVector;
  50693. var distance;
  50694. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  50695. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  50696. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  50697. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  50698. }
  50699. else { //minMaxVector and distance
  50700. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  50701. meshesOrMinMaxVector = minMaxVectorAndDistance;
  50702. distance = minMaxVectorAndDistance.distance;
  50703. }
  50704. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  50705. if (!doNotUpdateMaxZ) {
  50706. this.maxZ = distance * 2;
  50707. }
  50708. };
  50709. /**
  50710. * @override
  50711. * Override Camera.createRigCamera
  50712. */
  50713. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  50714. var alphaShift = 0;
  50715. switch (this.cameraRigMode) {
  50716. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  50717. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  50718. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  50719. case BABYLON.Camera.RIG_MODE_VR:
  50720. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  50721. break;
  50722. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  50723. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  50724. break;
  50725. }
  50726. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  50727. rigCam._cameraRigParams = {};
  50728. return rigCam;
  50729. };
  50730. /**
  50731. * @hidden
  50732. * @override
  50733. * Override Camera._updateRigCameras
  50734. */
  50735. ArcRotateCamera.prototype._updateRigCameras = function () {
  50736. var camLeft = this._rigCameras[0];
  50737. var camRight = this._rigCameras[1];
  50738. camLeft.beta = camRight.beta = this.beta;
  50739. camLeft.radius = camRight.radius = this.radius;
  50740. switch (this.cameraRigMode) {
  50741. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  50742. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  50743. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  50744. case BABYLON.Camera.RIG_MODE_VR:
  50745. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  50746. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  50747. break;
  50748. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  50749. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  50750. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  50751. break;
  50752. }
  50753. _super.prototype._updateRigCameras.call(this);
  50754. };
  50755. /**
  50756. * Destroy the camera and release the current resources hold by it.
  50757. */
  50758. ArcRotateCamera.prototype.dispose = function () {
  50759. this.inputs.clear();
  50760. _super.prototype.dispose.call(this);
  50761. };
  50762. /**
  50763. * Gets the current object class name.
  50764. * @return the class name
  50765. */
  50766. ArcRotateCamera.prototype.getClassName = function () {
  50767. return "ArcRotateCamera";
  50768. };
  50769. __decorate([
  50770. BABYLON.serialize()
  50771. ], ArcRotateCamera.prototype, "alpha", void 0);
  50772. __decorate([
  50773. BABYLON.serialize()
  50774. ], ArcRotateCamera.prototype, "beta", void 0);
  50775. __decorate([
  50776. BABYLON.serialize()
  50777. ], ArcRotateCamera.prototype, "radius", void 0);
  50778. __decorate([
  50779. BABYLON.serializeAsVector3("target")
  50780. ], ArcRotateCamera.prototype, "_target", void 0);
  50781. __decorate([
  50782. BABYLON.serialize()
  50783. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  50784. __decorate([
  50785. BABYLON.serialize()
  50786. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  50787. __decorate([
  50788. BABYLON.serialize()
  50789. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  50790. __decorate([
  50791. BABYLON.serialize()
  50792. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  50793. __decorate([
  50794. BABYLON.serialize()
  50795. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  50796. __decorate([
  50797. BABYLON.serialize()
  50798. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  50799. __decorate([
  50800. BABYLON.serialize()
  50801. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  50802. __decorate([
  50803. BABYLON.serialize()
  50804. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  50805. __decorate([
  50806. BABYLON.serialize()
  50807. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  50808. __decorate([
  50809. BABYLON.serialize()
  50810. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  50811. __decorate([
  50812. BABYLON.serialize()
  50813. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  50814. __decorate([
  50815. BABYLON.serialize()
  50816. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  50817. __decorate([
  50818. BABYLON.serialize()
  50819. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  50820. __decorate([
  50821. BABYLON.serializeAsVector3()
  50822. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  50823. __decorate([
  50824. BABYLON.serialize()
  50825. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  50826. __decorate([
  50827. BABYLON.serialize()
  50828. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  50829. __decorate([
  50830. BABYLON.serialize()
  50831. ], ArcRotateCamera.prototype, "targetScreenOffset", void 0);
  50832. __decorate([
  50833. BABYLON.serialize()
  50834. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  50835. __decorate([
  50836. BABYLON.serialize()
  50837. ], ArcRotateCamera.prototype, "useInputToRestoreState", void 0);
  50838. return ArcRotateCamera;
  50839. }(BABYLON.TargetCamera));
  50840. BABYLON.ArcRotateCamera = ArcRotateCamera;
  50841. })(BABYLON || (BABYLON = {}));
  50842. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  50843. var BABYLON;
  50844. (function (BABYLON) {
  50845. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  50846. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  50847. });
  50848. /**
  50849. * The HemisphericLight simulates the ambient environment light,
  50850. * so the passed direction is the light reflection direction, not the incoming direction.
  50851. */
  50852. var HemisphericLight = /** @class */ (function (_super) {
  50853. __extends(HemisphericLight, _super);
  50854. /**
  50855. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  50856. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  50857. * The HemisphericLight can't cast shadows.
  50858. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50859. * @param name The friendly name of the light
  50860. * @param direction The direction of the light reflection
  50861. * @param scene The scene the light belongs to
  50862. */
  50863. function HemisphericLight(name, direction, scene) {
  50864. var _this = _super.call(this, name, scene) || this;
  50865. /**
  50866. * The groundColor is the light in the opposite direction to the one specified during creation.
  50867. * 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.
  50868. */
  50869. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  50870. _this.direction = direction || BABYLON.Vector3.Up();
  50871. return _this;
  50872. }
  50873. HemisphericLight.prototype._buildUniformLayout = function () {
  50874. this._uniformBuffer.addUniform("vLightData", 4);
  50875. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50876. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50877. this._uniformBuffer.addUniform("vLightGround", 3);
  50878. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50879. this._uniformBuffer.addUniform("depthValues", 2);
  50880. this._uniformBuffer.create();
  50881. };
  50882. /**
  50883. * Returns the string "HemisphericLight".
  50884. * @return The class name
  50885. */
  50886. HemisphericLight.prototype.getClassName = function () {
  50887. return "HemisphericLight";
  50888. };
  50889. /**
  50890. * Sets the HemisphericLight direction towards the passed target (Vector3).
  50891. * Returns the updated direction.
  50892. * @param target The target the direction should point to
  50893. * @return The computed direction
  50894. */
  50895. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  50896. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  50897. return this.direction;
  50898. };
  50899. /**
  50900. * Returns the shadow generator associated to the light.
  50901. * @returns Always null for hemispheric lights because it does not support shadows.
  50902. */
  50903. HemisphericLight.prototype.getShadowGenerator = function () {
  50904. return null;
  50905. };
  50906. /**
  50907. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  50908. * @param effect The effect to update
  50909. * @param lightIndex The index of the light in the effect to update
  50910. * @returns The hemispheric light
  50911. */
  50912. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  50913. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50914. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  50915. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  50916. return this;
  50917. };
  50918. /**
  50919. * Computes the world matrix of the node
  50920. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  50921. * @param useWasUpdatedFlag defines a reserved property
  50922. * @returns the world matrix
  50923. */
  50924. HemisphericLight.prototype.computeWorldMatrix = function (force, useWasUpdatedFlag) {
  50925. if (!this._worldMatrix) {
  50926. this._worldMatrix = BABYLON.Matrix.Identity();
  50927. }
  50928. return this._worldMatrix;
  50929. };
  50930. /**
  50931. * Returns the integer 3.
  50932. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50933. */
  50934. HemisphericLight.prototype.getTypeID = function () {
  50935. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  50936. };
  50937. /**
  50938. * Prepares the list of defines specific to the light type.
  50939. * @param defines the list of defines
  50940. * @param lightIndex defines the index of the light for the effect
  50941. */
  50942. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  50943. defines["HEMILIGHT" + lightIndex] = true;
  50944. };
  50945. __decorate([
  50946. BABYLON.serializeAsColor3()
  50947. ], HemisphericLight.prototype, "groundColor", void 0);
  50948. __decorate([
  50949. BABYLON.serializeAsVector3()
  50950. ], HemisphericLight.prototype, "direction", void 0);
  50951. return HemisphericLight;
  50952. }(BABYLON.Light));
  50953. BABYLON.HemisphericLight = HemisphericLight;
  50954. })(BABYLON || (BABYLON = {}));
  50955. //# sourceMappingURL=babylon.hemisphericLight.js.map
  50956. var BABYLON;
  50957. (function (BABYLON) {
  50958. /**
  50959. * Base implementation IShadowLight
  50960. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  50961. */
  50962. var ShadowLight = /** @class */ (function (_super) {
  50963. __extends(ShadowLight, _super);
  50964. function ShadowLight() {
  50965. var _this = _super !== null && _super.apply(this, arguments) || this;
  50966. _this._needProjectionMatrixCompute = true;
  50967. return _this;
  50968. }
  50969. ShadowLight.prototype._setPosition = function (value) {
  50970. this._position = value;
  50971. };
  50972. Object.defineProperty(ShadowLight.prototype, "position", {
  50973. /**
  50974. * Sets the position the shadow will be casted from. Also use as the light position for both
  50975. * point and spot lights.
  50976. */
  50977. get: function () {
  50978. return this._position;
  50979. },
  50980. /**
  50981. * Sets the position the shadow will be casted from. Also use as the light position for both
  50982. * point and spot lights.
  50983. */
  50984. set: function (value) {
  50985. this._setPosition(value);
  50986. },
  50987. enumerable: true,
  50988. configurable: true
  50989. });
  50990. ShadowLight.prototype._setDirection = function (value) {
  50991. this._direction = value;
  50992. };
  50993. Object.defineProperty(ShadowLight.prototype, "direction", {
  50994. /**
  50995. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  50996. * Also use as the light direction on spot and directional lights.
  50997. */
  50998. get: function () {
  50999. return this._direction;
  51000. },
  51001. /**
  51002. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  51003. * Also use as the light direction on spot and directional lights.
  51004. */
  51005. set: function (value) {
  51006. this._setDirection(value);
  51007. },
  51008. enumerable: true,
  51009. configurable: true
  51010. });
  51011. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  51012. /**
  51013. * Gets the shadow projection clipping minimum z value.
  51014. */
  51015. get: function () {
  51016. return this._shadowMinZ;
  51017. },
  51018. /**
  51019. * Sets the shadow projection clipping minimum z value.
  51020. */
  51021. set: function (value) {
  51022. this._shadowMinZ = value;
  51023. this.forceProjectionMatrixCompute();
  51024. },
  51025. enumerable: true,
  51026. configurable: true
  51027. });
  51028. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  51029. /**
  51030. * Sets the shadow projection clipping maximum z value.
  51031. */
  51032. get: function () {
  51033. return this._shadowMaxZ;
  51034. },
  51035. /**
  51036. * Gets the shadow projection clipping maximum z value.
  51037. */
  51038. set: function (value) {
  51039. this._shadowMaxZ = value;
  51040. this.forceProjectionMatrixCompute();
  51041. },
  51042. enumerable: true,
  51043. configurable: true
  51044. });
  51045. /**
  51046. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  51047. * @returns true if the information has been computed, false if it does not need to (no parenting)
  51048. */
  51049. ShadowLight.prototype.computeTransformedInformation = function () {
  51050. if (this.parent && this.parent.getWorldMatrix) {
  51051. if (!this.transformedPosition) {
  51052. this.transformedPosition = BABYLON.Vector3.Zero();
  51053. }
  51054. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  51055. // In case the direction is present.
  51056. if (this.direction) {
  51057. if (!this.transformedDirection) {
  51058. this.transformedDirection = BABYLON.Vector3.Zero();
  51059. }
  51060. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  51061. }
  51062. return true;
  51063. }
  51064. return false;
  51065. };
  51066. /**
  51067. * Return the depth scale used for the shadow map.
  51068. * @returns the depth scale.
  51069. */
  51070. ShadowLight.prototype.getDepthScale = function () {
  51071. return 50.0;
  51072. };
  51073. /**
  51074. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  51075. * @param faceIndex The index of the face we are computed the direction to generate shadow
  51076. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  51077. */
  51078. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  51079. return this.transformedDirection ? this.transformedDirection : this.direction;
  51080. };
  51081. /**
  51082. * Returns the ShadowLight absolute position in the World.
  51083. * @returns the position vector in world space
  51084. */
  51085. ShadowLight.prototype.getAbsolutePosition = function () {
  51086. return this.transformedPosition ? this.transformedPosition : this.position;
  51087. };
  51088. /**
  51089. * Sets the ShadowLight direction toward the passed target.
  51090. * @param target The point tot target in local space
  51091. * @returns the updated ShadowLight direction
  51092. */
  51093. ShadowLight.prototype.setDirectionToTarget = function (target) {
  51094. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  51095. return this.direction;
  51096. };
  51097. /**
  51098. * Returns the light rotation in euler definition.
  51099. * @returns the x y z rotation in local space.
  51100. */
  51101. ShadowLight.prototype.getRotation = function () {
  51102. this.direction.normalize();
  51103. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  51104. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  51105. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  51106. };
  51107. /**
  51108. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  51109. * @returns true if a cube texture needs to be use
  51110. */
  51111. ShadowLight.prototype.needCube = function () {
  51112. return false;
  51113. };
  51114. /**
  51115. * Detects if the projection matrix requires to be recomputed this frame.
  51116. * @returns true if it requires to be recomputed otherwise, false.
  51117. */
  51118. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  51119. return this._needProjectionMatrixCompute;
  51120. };
  51121. /**
  51122. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  51123. */
  51124. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  51125. this._needProjectionMatrixCompute = true;
  51126. };
  51127. /** @hidden */
  51128. ShadowLight.prototype._initCache = function () {
  51129. _super.prototype._initCache.call(this);
  51130. this._cache.position = BABYLON.Vector3.Zero();
  51131. };
  51132. /** @hidden */
  51133. ShadowLight.prototype._isSynchronized = function () {
  51134. if (!this._cache.position.equals(this.position)) {
  51135. return false;
  51136. }
  51137. return true;
  51138. };
  51139. /**
  51140. * Computes the world matrix of the node
  51141. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  51142. * @returns the world matrix
  51143. */
  51144. ShadowLight.prototype.computeWorldMatrix = function (force) {
  51145. if (!force && this.isSynchronized()) {
  51146. this._currentRenderId = this.getScene().getRenderId();
  51147. return this._worldMatrix;
  51148. }
  51149. this._updateCache();
  51150. this._cache.position.copyFrom(this.position);
  51151. if (!this._worldMatrix) {
  51152. this._worldMatrix = BABYLON.Matrix.Identity();
  51153. }
  51154. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  51155. if (this.parent && this.parent.getWorldMatrix) {
  51156. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  51157. this._markSyncedWithParent();
  51158. }
  51159. // Cache the determinant
  51160. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  51161. return this._worldMatrix;
  51162. };
  51163. /**
  51164. * Gets the minZ used for shadow according to both the scene and the light.
  51165. * @param activeCamera The camera we are returning the min for
  51166. * @returns the depth min z
  51167. */
  51168. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  51169. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  51170. };
  51171. /**
  51172. * Gets the maxZ used for shadow according to both the scene and the light.
  51173. * @param activeCamera The camera we are returning the max for
  51174. * @returns the depth max z
  51175. */
  51176. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  51177. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  51178. };
  51179. /**
  51180. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  51181. * @param matrix The materix to updated with the projection information
  51182. * @param viewMatrix The transform matrix of the light
  51183. * @param renderList The list of mesh to render in the map
  51184. * @returns The current light
  51185. */
  51186. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  51187. if (this.customProjectionMatrixBuilder) {
  51188. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  51189. }
  51190. else {
  51191. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  51192. }
  51193. return this;
  51194. };
  51195. __decorate([
  51196. BABYLON.serializeAsVector3()
  51197. ], ShadowLight.prototype, "position", null);
  51198. __decorate([
  51199. BABYLON.serializeAsVector3()
  51200. ], ShadowLight.prototype, "direction", null);
  51201. __decorate([
  51202. BABYLON.serialize()
  51203. ], ShadowLight.prototype, "shadowMinZ", null);
  51204. __decorate([
  51205. BABYLON.serialize()
  51206. ], ShadowLight.prototype, "shadowMaxZ", null);
  51207. return ShadowLight;
  51208. }(BABYLON.Light));
  51209. BABYLON.ShadowLight = ShadowLight;
  51210. })(BABYLON || (BABYLON = {}));
  51211. //# sourceMappingURL=babylon.shadowLight.js.map
  51212. var BABYLON;
  51213. (function (BABYLON) {
  51214. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  51215. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  51216. });
  51217. /**
  51218. * A point light is a light defined by an unique point in world space.
  51219. * The light is emitted in every direction from this point.
  51220. * A good example of a point light is a standard light bulb.
  51221. * Documentation: https://doc.babylonjs.com/babylon101/lights
  51222. */
  51223. var PointLight = /** @class */ (function (_super) {
  51224. __extends(PointLight, _super);
  51225. /**
  51226. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  51227. * A PointLight emits the light in every direction.
  51228. * It can cast shadows.
  51229. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  51230. * ```javascript
  51231. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  51232. * ```
  51233. * Documentation : http://doc.babylonjs.com/tutorials/lights
  51234. * @param name The light friendly name
  51235. * @param position The position of the point light in the scene
  51236. * @param scene The scene the lights belongs to
  51237. */
  51238. function PointLight(name, position, scene) {
  51239. var _this = _super.call(this, name, scene) || this;
  51240. _this._shadowAngle = Math.PI / 2;
  51241. _this.position = position;
  51242. return _this;
  51243. }
  51244. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  51245. /**
  51246. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  51247. * This specifies what angle the shadow will use to be created.
  51248. *
  51249. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  51250. */
  51251. get: function () {
  51252. return this._shadowAngle;
  51253. },
  51254. /**
  51255. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  51256. * This specifies what angle the shadow will use to be created.
  51257. *
  51258. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  51259. */
  51260. set: function (value) {
  51261. this._shadowAngle = value;
  51262. this.forceProjectionMatrixCompute();
  51263. },
  51264. enumerable: true,
  51265. configurable: true
  51266. });
  51267. Object.defineProperty(PointLight.prototype, "direction", {
  51268. /**
  51269. * Gets the direction if it has been set.
  51270. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  51271. */
  51272. get: function () {
  51273. return this._direction;
  51274. },
  51275. /**
  51276. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  51277. */
  51278. set: function (value) {
  51279. var previousNeedCube = this.needCube();
  51280. this._direction = value;
  51281. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  51282. this._shadowGenerator.recreateShadowMap();
  51283. }
  51284. },
  51285. enumerable: true,
  51286. configurable: true
  51287. });
  51288. /**
  51289. * Returns the string "PointLight"
  51290. * @returns the class name
  51291. */
  51292. PointLight.prototype.getClassName = function () {
  51293. return "PointLight";
  51294. };
  51295. /**
  51296. * Returns the integer 0.
  51297. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  51298. */
  51299. PointLight.prototype.getTypeID = function () {
  51300. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  51301. };
  51302. /**
  51303. * Specifies wether or not the shadowmap should be a cube texture.
  51304. * @returns true if the shadowmap needs to be a cube texture.
  51305. */
  51306. PointLight.prototype.needCube = function () {
  51307. return !this.direction;
  51308. };
  51309. /**
  51310. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  51311. * @param faceIndex The index of the face we are computed the direction to generate shadow
  51312. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  51313. */
  51314. PointLight.prototype.getShadowDirection = function (faceIndex) {
  51315. if (this.direction) {
  51316. return _super.prototype.getShadowDirection.call(this, faceIndex);
  51317. }
  51318. else {
  51319. switch (faceIndex) {
  51320. case 0:
  51321. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  51322. case 1:
  51323. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  51324. case 2:
  51325. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  51326. case 3:
  51327. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  51328. case 4:
  51329. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  51330. case 5:
  51331. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  51332. }
  51333. }
  51334. return BABYLON.Vector3.Zero();
  51335. };
  51336. /**
  51337. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  51338. * - fov = PI / 2
  51339. * - aspect ratio : 1.0
  51340. * - z-near and far equal to the active camera minZ and maxZ.
  51341. * Returns the PointLight.
  51342. */
  51343. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  51344. var activeCamera = this.getScene().activeCamera;
  51345. if (!activeCamera) {
  51346. return;
  51347. }
  51348. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  51349. };
  51350. PointLight.prototype._buildUniformLayout = function () {
  51351. this._uniformBuffer.addUniform("vLightData", 4);
  51352. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  51353. this._uniformBuffer.addUniform("vLightSpecular", 3);
  51354. this._uniformBuffer.addUniform("vLightFalloff", 4);
  51355. this._uniformBuffer.addUniform("shadowsInfo", 3);
  51356. this._uniformBuffer.addUniform("depthValues", 2);
  51357. this._uniformBuffer.create();
  51358. };
  51359. /**
  51360. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  51361. * @param effect The effect to update
  51362. * @param lightIndex The index of the light in the effect to update
  51363. * @returns The point light
  51364. */
  51365. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  51366. if (this.computeTransformedInformation()) {
  51367. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  51368. }
  51369. else {
  51370. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  51371. }
  51372. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
  51373. return this;
  51374. };
  51375. /**
  51376. * Prepares the list of defines specific to the light type.
  51377. * @param defines the list of defines
  51378. * @param lightIndex defines the index of the light for the effect
  51379. */
  51380. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  51381. defines["POINTLIGHT" + lightIndex] = true;
  51382. };
  51383. __decorate([
  51384. BABYLON.serialize()
  51385. ], PointLight.prototype, "shadowAngle", null);
  51386. return PointLight;
  51387. }(BABYLON.ShadowLight));
  51388. BABYLON.PointLight = PointLight;
  51389. })(BABYLON || (BABYLON = {}));
  51390. //# sourceMappingURL=babylon.pointLight.js.map
  51391. var BABYLON;
  51392. (function (BABYLON) {
  51393. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  51394. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  51395. });
  51396. /**
  51397. * A directional light is defined by a direction (what a surprise!).
  51398. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  51399. * 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.
  51400. * Documentation: https://doc.babylonjs.com/babylon101/lights
  51401. */
  51402. var DirectionalLight = /** @class */ (function (_super) {
  51403. __extends(DirectionalLight, _super);
  51404. /**
  51405. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  51406. * The directional light is emitted from everywhere in the given direction.
  51407. * It can cast shadows.
  51408. * Documentation : http://doc.babylonjs.com/tutorials/lights
  51409. * @param name The friendly name of the light
  51410. * @param direction The direction of the light
  51411. * @param scene The scene the light belongs to
  51412. */
  51413. function DirectionalLight(name, direction, scene) {
  51414. var _this = _super.call(this, name, scene) || this;
  51415. _this._shadowFrustumSize = 0;
  51416. _this._shadowOrthoScale = 0.1;
  51417. /**
  51418. * Automatically compute the projection matrix to best fit (including all the casters)
  51419. * on each frame.
  51420. */
  51421. _this.autoUpdateExtends = true;
  51422. // Cache
  51423. _this._orthoLeft = Number.MAX_VALUE;
  51424. _this._orthoRight = Number.MIN_VALUE;
  51425. _this._orthoTop = Number.MIN_VALUE;
  51426. _this._orthoBottom = Number.MAX_VALUE;
  51427. _this.position = direction.scale(-1.0);
  51428. _this.direction = direction;
  51429. return _this;
  51430. }
  51431. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  51432. /**
  51433. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  51434. */
  51435. get: function () {
  51436. return this._shadowFrustumSize;
  51437. },
  51438. /**
  51439. * Specifies a fix frustum size for the shadow generation.
  51440. */
  51441. set: function (value) {
  51442. this._shadowFrustumSize = value;
  51443. this.forceProjectionMatrixCompute();
  51444. },
  51445. enumerable: true,
  51446. configurable: true
  51447. });
  51448. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  51449. /**
  51450. * Gets the shadow projection scale against the optimal computed one.
  51451. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  51452. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  51453. */
  51454. get: function () {
  51455. return this._shadowOrthoScale;
  51456. },
  51457. /**
  51458. * Sets the shadow projection scale against the optimal computed one.
  51459. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  51460. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  51461. */
  51462. set: function (value) {
  51463. this._shadowOrthoScale = value;
  51464. this.forceProjectionMatrixCompute();
  51465. },
  51466. enumerable: true,
  51467. configurable: true
  51468. });
  51469. /**
  51470. * Returns the string "DirectionalLight".
  51471. * @return The class name
  51472. */
  51473. DirectionalLight.prototype.getClassName = function () {
  51474. return "DirectionalLight";
  51475. };
  51476. /**
  51477. * Returns the integer 1.
  51478. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  51479. */
  51480. DirectionalLight.prototype.getTypeID = function () {
  51481. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  51482. };
  51483. /**
  51484. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  51485. * Returns the DirectionalLight Shadow projection matrix.
  51486. */
  51487. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  51488. if (this.shadowFrustumSize > 0) {
  51489. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  51490. }
  51491. else {
  51492. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  51493. }
  51494. };
  51495. /**
  51496. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  51497. * Returns the DirectionalLight Shadow projection matrix.
  51498. */
  51499. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  51500. var activeCamera = this.getScene().activeCamera;
  51501. if (!activeCamera) {
  51502. return;
  51503. }
  51504. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  51505. };
  51506. /**
  51507. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  51508. * Returns the DirectionalLight Shadow projection matrix.
  51509. */
  51510. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  51511. var activeCamera = this.getScene().activeCamera;
  51512. if (!activeCamera) {
  51513. return;
  51514. }
  51515. // Check extends
  51516. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  51517. var tempVector3 = BABYLON.Vector3.Zero();
  51518. this._orthoLeft = Number.MAX_VALUE;
  51519. this._orthoRight = Number.MIN_VALUE;
  51520. this._orthoTop = Number.MIN_VALUE;
  51521. this._orthoBottom = Number.MAX_VALUE;
  51522. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  51523. var mesh = renderList[meshIndex];
  51524. if (!mesh) {
  51525. continue;
  51526. }
  51527. var boundingInfo = mesh.getBoundingInfo();
  51528. var boundingBox = boundingInfo.boundingBox;
  51529. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  51530. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  51531. if (tempVector3.x < this._orthoLeft) {
  51532. this._orthoLeft = tempVector3.x;
  51533. }
  51534. if (tempVector3.y < this._orthoBottom) {
  51535. this._orthoBottom = tempVector3.y;
  51536. }
  51537. if (tempVector3.x > this._orthoRight) {
  51538. this._orthoRight = tempVector3.x;
  51539. }
  51540. if (tempVector3.y > this._orthoTop) {
  51541. this._orthoTop = tempVector3.y;
  51542. }
  51543. }
  51544. }
  51545. }
  51546. var xOffset = this._orthoRight - this._orthoLeft;
  51547. var yOffset = this._orthoTop - this._orthoBottom;
  51548. 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);
  51549. };
  51550. DirectionalLight.prototype._buildUniformLayout = function () {
  51551. this._uniformBuffer.addUniform("vLightData", 4);
  51552. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  51553. this._uniformBuffer.addUniform("vLightSpecular", 3);
  51554. this._uniformBuffer.addUniform("shadowsInfo", 3);
  51555. this._uniformBuffer.addUniform("depthValues", 2);
  51556. this._uniformBuffer.create();
  51557. };
  51558. /**
  51559. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  51560. * @param effect The effect to update
  51561. * @param lightIndex The index of the light in the effect to update
  51562. * @returns The directional light
  51563. */
  51564. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  51565. if (this.computeTransformedInformation()) {
  51566. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  51567. return this;
  51568. }
  51569. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  51570. return this;
  51571. };
  51572. /**
  51573. * Gets the minZ used for shadow according to both the scene and the light.
  51574. *
  51575. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  51576. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  51577. * @param activeCamera The camera we are returning the min for
  51578. * @returns the depth min z
  51579. */
  51580. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  51581. return 1;
  51582. };
  51583. /**
  51584. * Gets the maxZ used for shadow according to both the scene and the light.
  51585. *
  51586. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  51587. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  51588. * @param activeCamera The camera we are returning the max for
  51589. * @returns the depth max z
  51590. */
  51591. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  51592. return 1;
  51593. };
  51594. /**
  51595. * Prepares the list of defines specific to the light type.
  51596. * @param defines the list of defines
  51597. * @param lightIndex defines the index of the light for the effect
  51598. */
  51599. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  51600. defines["DIRLIGHT" + lightIndex] = true;
  51601. };
  51602. __decorate([
  51603. BABYLON.serialize()
  51604. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  51605. __decorate([
  51606. BABYLON.serialize()
  51607. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  51608. __decorate([
  51609. BABYLON.serialize()
  51610. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  51611. return DirectionalLight;
  51612. }(BABYLON.ShadowLight));
  51613. BABYLON.DirectionalLight = DirectionalLight;
  51614. })(BABYLON || (BABYLON = {}));
  51615. //# sourceMappingURL=babylon.directionalLight.js.map
  51616. var BABYLON;
  51617. (function (BABYLON) {
  51618. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  51619. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  51620. });
  51621. /**
  51622. * A spot light is defined by a position, a direction, an angle, and an exponent.
  51623. * These values define a cone of light starting from the position, emitting toward the direction.
  51624. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  51625. * and the exponent defines the speed of the decay of the light with distance (reach).
  51626. * Documentation: https://doc.babylonjs.com/babylon101/lights
  51627. */
  51628. var SpotLight = /** @class */ (function (_super) {
  51629. __extends(SpotLight, _super);
  51630. /**
  51631. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  51632. * It can cast shadows.
  51633. * Documentation : http://doc.babylonjs.com/tutorials/lights
  51634. * @param name The light friendly name
  51635. * @param position The position of the spot light in the scene
  51636. * @param direction The direction of the light in the scene
  51637. * @param angle The cone angle of the light in Radians
  51638. * @param exponent The light decay speed with the distance from the emission spot
  51639. * @param scene The scene the lights belongs to
  51640. */
  51641. function SpotLight(name, position, direction, angle, exponent, scene) {
  51642. var _this = _super.call(this, name, scene) || this;
  51643. _this._innerAngle = 0;
  51644. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  51645. _this._projectionTextureLightNear = 1e-6;
  51646. _this._projectionTextureLightFar = 1000.0;
  51647. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  51648. _this._projectionTextureViewLightDirty = true;
  51649. _this._projectionTextureProjectionLightDirty = true;
  51650. _this._projectionTextureDirty = true;
  51651. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  51652. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  51653. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  51654. _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);
  51655. _this.position = position;
  51656. _this.direction = direction;
  51657. _this.angle = angle;
  51658. _this.exponent = exponent;
  51659. return _this;
  51660. }
  51661. Object.defineProperty(SpotLight.prototype, "angle", {
  51662. /**
  51663. * Gets the cone angle of the spot light in Radians.
  51664. */
  51665. get: function () {
  51666. return this._angle;
  51667. },
  51668. /**
  51669. * Sets the cone angle of the spot light in Radians.
  51670. */
  51671. set: function (value) {
  51672. this._angle = value;
  51673. this._cosHalfAngle = Math.cos(value * 0.5);
  51674. this._projectionTextureProjectionLightDirty = true;
  51675. this.forceProjectionMatrixCompute();
  51676. this._computeAngleValues();
  51677. },
  51678. enumerable: true,
  51679. configurable: true
  51680. });
  51681. Object.defineProperty(SpotLight.prototype, "innerAngle", {
  51682. /**
  51683. * Only used in gltf falloff mode, this defines the angle where
  51684. * the directional falloff will start before cutting at angle which could be seen
  51685. * as outer angle.
  51686. */
  51687. get: function () {
  51688. return this._innerAngle;
  51689. },
  51690. /**
  51691. * Only used in gltf falloff mode, this defines the angle where
  51692. * the directional falloff will start before cutting at angle which could be seen
  51693. * as outer angle.
  51694. */
  51695. set: function (value) {
  51696. this._innerAngle = value;
  51697. this._computeAngleValues();
  51698. },
  51699. enumerable: true,
  51700. configurable: true
  51701. });
  51702. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  51703. /**
  51704. * Allows scaling the angle of the light for shadow generation only.
  51705. */
  51706. get: function () {
  51707. return this._shadowAngleScale;
  51708. },
  51709. /**
  51710. * Allows scaling the angle of the light for shadow generation only.
  51711. */
  51712. set: function (value) {
  51713. this._shadowAngleScale = value;
  51714. this.forceProjectionMatrixCompute();
  51715. },
  51716. enumerable: true,
  51717. configurable: true
  51718. });
  51719. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  51720. /**
  51721. * Allows reading the projecton texture
  51722. */
  51723. get: function () {
  51724. return this._projectionTextureMatrix;
  51725. },
  51726. enumerable: true,
  51727. configurable: true
  51728. });
  51729. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  51730. /**
  51731. * Gets the near clip of the Spotlight for texture projection.
  51732. */
  51733. get: function () {
  51734. return this._projectionTextureLightNear;
  51735. },
  51736. /**
  51737. * Sets the near clip of the Spotlight for texture projection.
  51738. */
  51739. set: function (value) {
  51740. this._projectionTextureLightNear = value;
  51741. this._projectionTextureProjectionLightDirty = true;
  51742. },
  51743. enumerable: true,
  51744. configurable: true
  51745. });
  51746. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  51747. /**
  51748. * Gets the far clip of the Spotlight for texture projection.
  51749. */
  51750. get: function () {
  51751. return this._projectionTextureLightFar;
  51752. },
  51753. /**
  51754. * Sets the far clip of the Spotlight for texture projection.
  51755. */
  51756. set: function (value) {
  51757. this._projectionTextureLightFar = value;
  51758. this._projectionTextureProjectionLightDirty = true;
  51759. },
  51760. enumerable: true,
  51761. configurable: true
  51762. });
  51763. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  51764. /**
  51765. * Gets the Up vector of the Spotlight for texture projection.
  51766. */
  51767. get: function () {
  51768. return this._projectionTextureUpDirection;
  51769. },
  51770. /**
  51771. * Sets the Up vector of the Spotlight for texture projection.
  51772. */
  51773. set: function (value) {
  51774. this._projectionTextureUpDirection = value;
  51775. this._projectionTextureProjectionLightDirty = true;
  51776. },
  51777. enumerable: true,
  51778. configurable: true
  51779. });
  51780. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  51781. /**
  51782. * Gets the projection texture of the light.
  51783. */
  51784. get: function () {
  51785. return this._projectionTexture;
  51786. },
  51787. /**
  51788. * Sets the projection texture of the light.
  51789. */
  51790. set: function (value) {
  51791. this._projectionTexture = value;
  51792. this._projectionTextureDirty = true;
  51793. },
  51794. enumerable: true,
  51795. configurable: true
  51796. });
  51797. /**
  51798. * Returns the string "SpotLight".
  51799. * @returns the class name
  51800. */
  51801. SpotLight.prototype.getClassName = function () {
  51802. return "SpotLight";
  51803. };
  51804. /**
  51805. * Returns the integer 2.
  51806. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  51807. */
  51808. SpotLight.prototype.getTypeID = function () {
  51809. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  51810. };
  51811. /**
  51812. * Overrides the direction setter to recompute the projection texture view light Matrix.
  51813. */
  51814. SpotLight.prototype._setDirection = function (value) {
  51815. _super.prototype._setDirection.call(this, value);
  51816. this._projectionTextureViewLightDirty = true;
  51817. };
  51818. /**
  51819. * Overrides the position setter to recompute the projection texture view light Matrix.
  51820. */
  51821. SpotLight.prototype._setPosition = function (value) {
  51822. _super.prototype._setPosition.call(this, value);
  51823. this._projectionTextureViewLightDirty = true;
  51824. };
  51825. /**
  51826. * 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.
  51827. * Returns the SpotLight.
  51828. */
  51829. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  51830. var activeCamera = this.getScene().activeCamera;
  51831. if (!activeCamera) {
  51832. return;
  51833. }
  51834. this._shadowAngleScale = this._shadowAngleScale || 1;
  51835. var angle = this._shadowAngleScale * this._angle;
  51836. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  51837. };
  51838. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  51839. this._projectionTextureViewLightDirty = false;
  51840. this._projectionTextureDirty = true;
  51841. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  51842. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  51843. };
  51844. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  51845. this._projectionTextureProjectionLightDirty = false;
  51846. this._projectionTextureDirty = true;
  51847. var light_far = this.projectionTextureLightFar;
  51848. var light_near = this.projectionTextureLightNear;
  51849. var P = light_far / (light_far - light_near);
  51850. var Q = -P * light_near;
  51851. var S = 1.0 / Math.tan(this._angle / 2.0);
  51852. var A = 1.0;
  51853. 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);
  51854. };
  51855. /**
  51856. * Main function for light texture projection matrix computing.
  51857. */
  51858. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  51859. this._projectionTextureDirty = false;
  51860. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  51861. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  51862. };
  51863. SpotLight.prototype._buildUniformLayout = function () {
  51864. this._uniformBuffer.addUniform("vLightData", 4);
  51865. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  51866. this._uniformBuffer.addUniform("vLightSpecular", 3);
  51867. this._uniformBuffer.addUniform("vLightDirection", 3);
  51868. this._uniformBuffer.addUniform("vLightFalloff", 4);
  51869. this._uniformBuffer.addUniform("shadowsInfo", 3);
  51870. this._uniformBuffer.addUniform("depthValues", 2);
  51871. this._uniformBuffer.create();
  51872. };
  51873. SpotLight.prototype._computeAngleValues = function () {
  51874. this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
  51875. this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  51876. };
  51877. /**
  51878. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  51879. * @param effect The effect to update
  51880. * @param lightIndex The index of the light in the effect to update
  51881. * @returns The spot light
  51882. */
  51883. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  51884. var normalizeDirection;
  51885. if (this.computeTransformedInformation()) {
  51886. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  51887. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  51888. }
  51889. else {
  51890. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  51891. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  51892. }
  51893. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
  51894. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
  51895. if (this.projectionTexture && this.projectionTexture.isReady()) {
  51896. if (this._projectionTextureViewLightDirty) {
  51897. this._computeProjectionTextureViewLightMatrix();
  51898. }
  51899. if (this._projectionTextureProjectionLightDirty) {
  51900. this._computeProjectionTextureProjectionLightMatrix();
  51901. }
  51902. if (this._projectionTextureDirty) {
  51903. this._computeProjectionTextureMatrix();
  51904. }
  51905. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  51906. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  51907. }
  51908. return this;
  51909. };
  51910. /**
  51911. * Disposes the light and the associated resources.
  51912. */
  51913. SpotLight.prototype.dispose = function () {
  51914. _super.prototype.dispose.call(this);
  51915. if (this._projectionTexture) {
  51916. this._projectionTexture.dispose();
  51917. }
  51918. };
  51919. /**
  51920. * Prepares the list of defines specific to the light type.
  51921. * @param defines the list of defines
  51922. * @param lightIndex defines the index of the light for the effect
  51923. */
  51924. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  51925. defines["SPOTLIGHT" + lightIndex] = true;
  51926. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  51927. };
  51928. __decorate([
  51929. BABYLON.serialize()
  51930. ], SpotLight.prototype, "angle", null);
  51931. __decorate([
  51932. BABYLON.serialize()
  51933. ], SpotLight.prototype, "innerAngle", null);
  51934. __decorate([
  51935. BABYLON.serialize()
  51936. ], SpotLight.prototype, "shadowAngleScale", null);
  51937. __decorate([
  51938. BABYLON.serialize()
  51939. ], SpotLight.prototype, "exponent", void 0);
  51940. __decorate([
  51941. BABYLON.serialize()
  51942. ], SpotLight.prototype, "projectionTextureLightNear", null);
  51943. __decorate([
  51944. BABYLON.serialize()
  51945. ], SpotLight.prototype, "projectionTextureLightFar", null);
  51946. __decorate([
  51947. BABYLON.serialize()
  51948. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  51949. __decorate([
  51950. BABYLON.serializeAsTexture("projectedLightTexture")
  51951. ], SpotLight.prototype, "_projectionTexture", void 0);
  51952. return SpotLight;
  51953. }(BABYLON.ShadowLight));
  51954. BABYLON.SpotLight = SpotLight;
  51955. })(BABYLON || (BABYLON = {}));
  51956. //# sourceMappingURL=babylon.spotLight.js.map
  51957. var BABYLON;
  51958. (function (BABYLON) {
  51959. /**
  51960. * Class used to override all child animations of a given target
  51961. */
  51962. var AnimationPropertiesOverride = /** @class */ (function () {
  51963. function AnimationPropertiesOverride() {
  51964. /**
  51965. * Gets or sets a value indicating if animation blending must be used
  51966. */
  51967. this.enableBlending = false;
  51968. /**
  51969. * Gets or sets the blending speed to use when enableBlending is true
  51970. */
  51971. this.blendingSpeed = 0.01;
  51972. /**
  51973. * Gets or sets the default loop mode to use
  51974. */
  51975. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  51976. }
  51977. return AnimationPropertiesOverride;
  51978. }());
  51979. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  51980. })(BABYLON || (BABYLON = {}));
  51981. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  51982. var BABYLON;
  51983. (function (BABYLON) {
  51984. /**
  51985. * Represents the range of an animation
  51986. */
  51987. var AnimationRange = /** @class */ (function () {
  51988. /**
  51989. * Initializes the range of an animation
  51990. * @param name The name of the animation range
  51991. * @param from The starting frame of the animation
  51992. * @param to The ending frame of the animation
  51993. */
  51994. function AnimationRange(
  51995. /**The name of the animation range**/
  51996. name,
  51997. /**The starting frame of the animation */
  51998. from,
  51999. /**The ending frame of the animation*/
  52000. to) {
  52001. this.name = name;
  52002. this.from = from;
  52003. this.to = to;
  52004. }
  52005. /**
  52006. * Makes a copy of the animation range
  52007. * @returns A copy of the animation range
  52008. */
  52009. AnimationRange.prototype.clone = function () {
  52010. return new AnimationRange(this.name, this.from, this.to);
  52011. };
  52012. return AnimationRange;
  52013. }());
  52014. BABYLON.AnimationRange = AnimationRange;
  52015. /**
  52016. * Composed of a frame, and an action function
  52017. */
  52018. var AnimationEvent = /** @class */ (function () {
  52019. /**
  52020. * Initializes the animation event
  52021. * @param frame The frame for which the event is triggered
  52022. * @param action The event to perform when triggered
  52023. * @param onlyOnce Specifies if the event should be triggered only once
  52024. */
  52025. function AnimationEvent(
  52026. /** The frame for which the event is triggered **/
  52027. frame,
  52028. /** The event to perform when triggered **/
  52029. action,
  52030. /** Specifies if the event should be triggered only once**/
  52031. onlyOnce) {
  52032. this.frame = frame;
  52033. this.action = action;
  52034. this.onlyOnce = onlyOnce;
  52035. /**
  52036. * Specifies if the animation event is done
  52037. */
  52038. this.isDone = false;
  52039. }
  52040. /** @hidden */
  52041. AnimationEvent.prototype._clone = function () {
  52042. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  52043. };
  52044. return AnimationEvent;
  52045. }());
  52046. BABYLON.AnimationEvent = AnimationEvent;
  52047. /**
  52048. * A cursor which tracks a point on a path
  52049. */
  52050. var PathCursor = /** @class */ (function () {
  52051. /**
  52052. * Initializes the path cursor
  52053. * @param path The path to track
  52054. */
  52055. function PathCursor(path) {
  52056. this.path = path;
  52057. /**
  52058. * Stores path cursor callbacks for when an onchange event is triggered
  52059. */
  52060. this._onchange = new Array();
  52061. /**
  52062. * The value of the path cursor
  52063. */
  52064. this.value = 0;
  52065. /**
  52066. * The animation array of the path cursor
  52067. */
  52068. this.animations = new Array();
  52069. }
  52070. /**
  52071. * Gets the cursor point on the path
  52072. * @returns A point on the path cursor at the cursor location
  52073. */
  52074. PathCursor.prototype.getPoint = function () {
  52075. var point = this.path.getPointAtLengthPosition(this.value);
  52076. return new BABYLON.Vector3(point.x, 0, point.y);
  52077. };
  52078. /**
  52079. * Moves the cursor ahead by the step amount
  52080. * @param step The amount to move the cursor forward
  52081. * @returns This path cursor
  52082. */
  52083. PathCursor.prototype.moveAhead = function (step) {
  52084. if (step === void 0) { step = 0.002; }
  52085. this.move(step);
  52086. return this;
  52087. };
  52088. /**
  52089. * Moves the cursor behind by the step amount
  52090. * @param step The amount to move the cursor back
  52091. * @returns This path cursor
  52092. */
  52093. PathCursor.prototype.moveBack = function (step) {
  52094. if (step === void 0) { step = 0.002; }
  52095. this.move(-step);
  52096. return this;
  52097. };
  52098. /**
  52099. * Moves the cursor by the step amount
  52100. * If the step amount is greater than one, an exception is thrown
  52101. * @param step The amount to move the cursor
  52102. * @returns This path cursor
  52103. */
  52104. PathCursor.prototype.move = function (step) {
  52105. if (Math.abs(step) > 1) {
  52106. throw "step size should be less than 1.";
  52107. }
  52108. this.value += step;
  52109. this.ensureLimits();
  52110. this.raiseOnChange();
  52111. return this;
  52112. };
  52113. /**
  52114. * Ensures that the value is limited between zero and one
  52115. * @returns This path cursor
  52116. */
  52117. PathCursor.prototype.ensureLimits = function () {
  52118. while (this.value > 1) {
  52119. this.value -= 1;
  52120. }
  52121. while (this.value < 0) {
  52122. this.value += 1;
  52123. }
  52124. return this;
  52125. };
  52126. /**
  52127. * Runs onchange callbacks on change (used by the animation engine)
  52128. * @returns This path cursor
  52129. */
  52130. PathCursor.prototype.raiseOnChange = function () {
  52131. var _this = this;
  52132. this._onchange.forEach(function (f) { return f(_this); });
  52133. return this;
  52134. };
  52135. /**
  52136. * Executes a function on change
  52137. * @param f A path cursor onchange callback
  52138. * @returns This path cursor
  52139. */
  52140. PathCursor.prototype.onchange = function (f) {
  52141. this._onchange.push(f);
  52142. return this;
  52143. };
  52144. return PathCursor;
  52145. }());
  52146. BABYLON.PathCursor = PathCursor;
  52147. /**
  52148. * Enum for the animation key frame interpolation type
  52149. */
  52150. var AnimationKeyInterpolation;
  52151. (function (AnimationKeyInterpolation) {
  52152. /**
  52153. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  52154. */
  52155. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  52156. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  52157. /**
  52158. * Class used to store any kind of animation
  52159. */
  52160. var Animation = /** @class */ (function () {
  52161. /**
  52162. * Initializes the animation
  52163. * @param name Name of the animation
  52164. * @param targetProperty Property to animate
  52165. * @param framePerSecond The frames per second of the animation
  52166. * @param dataType The data type of the animation
  52167. * @param loopMode The loop mode of the animation
  52168. * @param enableBlendings Specifies if blending should be enabled
  52169. */
  52170. function Animation(
  52171. /**Name of the animation */
  52172. name,
  52173. /**Property to animate */
  52174. targetProperty,
  52175. /**The frames per second of the animation */
  52176. framePerSecond,
  52177. /**The data type of the animation */
  52178. dataType,
  52179. /**The loop mode of the animation */
  52180. loopMode,
  52181. /**Specifies if blending should be enabled */
  52182. enableBlending) {
  52183. this.name = name;
  52184. this.targetProperty = targetProperty;
  52185. this.framePerSecond = framePerSecond;
  52186. this.dataType = dataType;
  52187. this.loopMode = loopMode;
  52188. this.enableBlending = enableBlending;
  52189. /**
  52190. * @hidden Internal use only
  52191. */
  52192. this._runtimeAnimations = new Array();
  52193. /**
  52194. * The set of event that will be linked to this animation
  52195. */
  52196. this._events = new Array();
  52197. /**
  52198. * Stores the blending speed of the animation
  52199. */
  52200. this.blendingSpeed = 0.01;
  52201. /**
  52202. * Stores the animation ranges for the animation
  52203. */
  52204. this._ranges = {};
  52205. this.targetPropertyPath = targetProperty.split(".");
  52206. this.dataType = dataType;
  52207. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  52208. }
  52209. /**
  52210. * @hidden Internal use
  52211. */
  52212. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  52213. var dataType = undefined;
  52214. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  52215. dataType = Animation.ANIMATIONTYPE_FLOAT;
  52216. }
  52217. else if (from instanceof BABYLON.Quaternion) {
  52218. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  52219. }
  52220. else if (from instanceof BABYLON.Vector3) {
  52221. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  52222. }
  52223. else if (from instanceof BABYLON.Vector2) {
  52224. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  52225. }
  52226. else if (from instanceof BABYLON.Color3) {
  52227. dataType = Animation.ANIMATIONTYPE_COLOR3;
  52228. }
  52229. else if (from instanceof BABYLON.Size) {
  52230. dataType = Animation.ANIMATIONTYPE_SIZE;
  52231. }
  52232. if (dataType == undefined) {
  52233. return null;
  52234. }
  52235. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  52236. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  52237. animation.setKeys(keys);
  52238. if (easingFunction !== undefined) {
  52239. animation.setEasingFunction(easingFunction);
  52240. }
  52241. return animation;
  52242. };
  52243. /**
  52244. * Sets up an animation
  52245. * @param property The property to animate
  52246. * @param animationType The animation type to apply
  52247. * @param framePerSecond The frames per second of the animation
  52248. * @param easingFunction The easing function used in the animation
  52249. * @returns The created animation
  52250. */
  52251. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  52252. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  52253. animation.setEasingFunction(easingFunction);
  52254. return animation;
  52255. };
  52256. /**
  52257. * Create and start an animation on a node
  52258. * @param name defines the name of the global animation that will be run on all nodes
  52259. * @param node defines the root node where the animation will take place
  52260. * @param targetProperty defines property to animate
  52261. * @param framePerSecond defines the number of frame per second yo use
  52262. * @param totalFrame defines the number of frames in total
  52263. * @param from defines the initial value
  52264. * @param to defines the final value
  52265. * @param loopMode defines which loop mode you want to use (off by default)
  52266. * @param easingFunction defines the easing function to use (linear by default)
  52267. * @param onAnimationEnd defines the callback to call when animation end
  52268. * @returns the animatable created for this animation
  52269. */
  52270. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  52271. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  52272. if (!animation) {
  52273. return null;
  52274. }
  52275. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  52276. };
  52277. /**
  52278. * Create and start an animation on a node and its descendants
  52279. * @param name defines the name of the global animation that will be run on all nodes
  52280. * @param node defines the root node where the animation will take place
  52281. * @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
  52282. * @param targetProperty defines property to animate
  52283. * @param framePerSecond defines the number of frame per second to use
  52284. * @param totalFrame defines the number of frames in total
  52285. * @param from defines the initial value
  52286. * @param to defines the final value
  52287. * @param loopMode defines which loop mode you want to use (off by default)
  52288. * @param easingFunction defines the easing function to use (linear by default)
  52289. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  52290. * @returns the list of animatables created for all nodes
  52291. * @example https://www.babylonjs-playground.com/#MH0VLI
  52292. */
  52293. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  52294. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  52295. if (!animation) {
  52296. return null;
  52297. }
  52298. var scene = node.getScene();
  52299. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  52300. };
  52301. /**
  52302. * Creates a new animation, merges it with the existing animations and starts it
  52303. * @param name Name of the animation
  52304. * @param node Node which contains the scene that begins the animations
  52305. * @param targetProperty Specifies which property to animate
  52306. * @param framePerSecond The frames per second of the animation
  52307. * @param totalFrame The total number of frames
  52308. * @param from The frame at the beginning of the animation
  52309. * @param to The frame at the end of the animation
  52310. * @param loopMode Specifies the loop mode of the animation
  52311. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  52312. * @param onAnimationEnd Callback to run once the animation is complete
  52313. * @returns Nullable animation
  52314. */
  52315. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  52316. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  52317. if (!animation) {
  52318. return null;
  52319. }
  52320. node.animations.push(animation);
  52321. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  52322. };
  52323. /**
  52324. * Transition property of an host to the target Value
  52325. * @param property The property to transition
  52326. * @param targetValue The target Value of the property
  52327. * @param host The object where the property to animate belongs
  52328. * @param scene Scene used to run the animation
  52329. * @param frameRate Framerate (in frame/s) to use
  52330. * @param transition The transition type we want to use
  52331. * @param duration The duration of the animation, in milliseconds
  52332. * @param onAnimationEnd Callback trigger at the end of the animation
  52333. * @returns Nullable animation
  52334. */
  52335. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  52336. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  52337. if (duration <= 0) {
  52338. host[property] = targetValue;
  52339. if (onAnimationEnd) {
  52340. onAnimationEnd();
  52341. }
  52342. return null;
  52343. }
  52344. var endFrame = frameRate * (duration / 1000);
  52345. transition.setKeys([{
  52346. frame: 0,
  52347. value: host[property].clone ? host[property].clone() : host[property]
  52348. },
  52349. {
  52350. frame: endFrame,
  52351. value: targetValue
  52352. }]);
  52353. if (!host.animations) {
  52354. host.animations = [];
  52355. }
  52356. host.animations.push(transition);
  52357. var animation = scene.beginAnimation(host, 0, endFrame, false);
  52358. animation.onAnimationEnd = onAnimationEnd;
  52359. return animation;
  52360. };
  52361. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  52362. /**
  52363. * Return the array of runtime animations currently using this animation
  52364. */
  52365. get: function () {
  52366. return this._runtimeAnimations;
  52367. },
  52368. enumerable: true,
  52369. configurable: true
  52370. });
  52371. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  52372. /**
  52373. * Specifies if any of the runtime animations are currently running
  52374. */
  52375. get: function () {
  52376. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  52377. var runtimeAnimation = _a[_i];
  52378. if (!runtimeAnimation.isStopped) {
  52379. return true;
  52380. }
  52381. }
  52382. return false;
  52383. },
  52384. enumerable: true,
  52385. configurable: true
  52386. });
  52387. // Methods
  52388. /**
  52389. * Converts the animation to a string
  52390. * @param fullDetails support for multiple levels of logging within scene loading
  52391. * @returns String form of the animation
  52392. */
  52393. Animation.prototype.toString = function (fullDetails) {
  52394. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  52395. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  52396. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  52397. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  52398. if (fullDetails) {
  52399. ret += ", Ranges: {";
  52400. var first = true;
  52401. for (var name in this._ranges) {
  52402. if (first) {
  52403. ret += ", ";
  52404. first = false;
  52405. }
  52406. ret += name;
  52407. }
  52408. ret += "}";
  52409. }
  52410. return ret;
  52411. };
  52412. /**
  52413. * Add an event to this animation
  52414. * @param event Event to add
  52415. */
  52416. Animation.prototype.addEvent = function (event) {
  52417. this._events.push(event);
  52418. };
  52419. /**
  52420. * Remove all events found at the given frame
  52421. * @param frame The frame to remove events from
  52422. */
  52423. Animation.prototype.removeEvents = function (frame) {
  52424. for (var index = 0; index < this._events.length; index++) {
  52425. if (this._events[index].frame === frame) {
  52426. this._events.splice(index, 1);
  52427. index--;
  52428. }
  52429. }
  52430. };
  52431. /**
  52432. * Retrieves all the events from the animation
  52433. * @returns Events from the animation
  52434. */
  52435. Animation.prototype.getEvents = function () {
  52436. return this._events;
  52437. };
  52438. /**
  52439. * Creates an animation range
  52440. * @param name Name of the animation range
  52441. * @param from Starting frame of the animation range
  52442. * @param to Ending frame of the animation
  52443. */
  52444. Animation.prototype.createRange = function (name, from, to) {
  52445. // check name not already in use; could happen for bones after serialized
  52446. if (!this._ranges[name]) {
  52447. this._ranges[name] = new AnimationRange(name, from, to);
  52448. }
  52449. };
  52450. /**
  52451. * Deletes an animation range by name
  52452. * @param name Name of the animation range to delete
  52453. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  52454. */
  52455. Animation.prototype.deleteRange = function (name, deleteFrames) {
  52456. if (deleteFrames === void 0) { deleteFrames = true; }
  52457. var range = this._ranges[name];
  52458. if (!range) {
  52459. return;
  52460. }
  52461. if (deleteFrames) {
  52462. var from = range.from;
  52463. var to = range.to;
  52464. // this loop MUST go high to low for multiple splices to work
  52465. for (var key = this._keys.length - 1; key >= 0; key--) {
  52466. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  52467. this._keys.splice(key, 1);
  52468. }
  52469. }
  52470. }
  52471. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  52472. };
  52473. /**
  52474. * Gets the animation range by name, or null if not defined
  52475. * @param name Name of the animation range
  52476. * @returns Nullable animation range
  52477. */
  52478. Animation.prototype.getRange = function (name) {
  52479. return this._ranges[name];
  52480. };
  52481. /**
  52482. * Gets the key frames from the animation
  52483. * @returns The key frames of the animation
  52484. */
  52485. Animation.prototype.getKeys = function () {
  52486. return this._keys;
  52487. };
  52488. /**
  52489. * Gets the highest frame rate of the animation
  52490. * @returns Highest frame rate of the animation
  52491. */
  52492. Animation.prototype.getHighestFrame = function () {
  52493. var ret = 0;
  52494. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  52495. if (ret < this._keys[key].frame) {
  52496. ret = this._keys[key].frame;
  52497. }
  52498. }
  52499. return ret;
  52500. };
  52501. /**
  52502. * Gets the easing function of the animation
  52503. * @returns Easing function of the animation
  52504. */
  52505. Animation.prototype.getEasingFunction = function () {
  52506. return this._easingFunction;
  52507. };
  52508. /**
  52509. * Sets the easing function of the animation
  52510. * @param easingFunction A custom mathematical formula for animation
  52511. */
  52512. Animation.prototype.setEasingFunction = function (easingFunction) {
  52513. this._easingFunction = easingFunction;
  52514. };
  52515. /**
  52516. * Interpolates a scalar linearly
  52517. * @param startValue Start value of the animation curve
  52518. * @param endValue End value of the animation curve
  52519. * @param gradient Scalar amount to interpolate
  52520. * @returns Interpolated scalar value
  52521. */
  52522. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  52523. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  52524. };
  52525. /**
  52526. * Interpolates a scalar cubically
  52527. * @param startValue Start value of the animation curve
  52528. * @param outTangent End tangent of the animation
  52529. * @param endValue End value of the animation curve
  52530. * @param inTangent Start tangent of the animation curve
  52531. * @param gradient Scalar amount to interpolate
  52532. * @returns Interpolated scalar value
  52533. */
  52534. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  52535. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  52536. };
  52537. /**
  52538. * Interpolates a quaternion using a spherical linear interpolation
  52539. * @param startValue Start value of the animation curve
  52540. * @param endValue End value of the animation curve
  52541. * @param gradient Scalar amount to interpolate
  52542. * @returns Interpolated quaternion value
  52543. */
  52544. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  52545. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  52546. };
  52547. /**
  52548. * Interpolates a quaternion cubically
  52549. * @param startValue Start value of the animation curve
  52550. * @param outTangent End tangent of the animation curve
  52551. * @param endValue End value of the animation curve
  52552. * @param inTangent Start tangent of the animation curve
  52553. * @param gradient Scalar amount to interpolate
  52554. * @returns Interpolated quaternion value
  52555. */
  52556. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  52557. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  52558. };
  52559. /**
  52560. * Interpolates a Vector3 linearl
  52561. * @param startValue Start value of the animation curve
  52562. * @param endValue End value of the animation curve
  52563. * @param gradient Scalar amount to interpolate
  52564. * @returns Interpolated scalar value
  52565. */
  52566. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  52567. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  52568. };
  52569. /**
  52570. * Interpolates a Vector3 cubically
  52571. * @param startValue Start value of the animation curve
  52572. * @param outTangent End tangent of the animation
  52573. * @param endValue End value of the animation curve
  52574. * @param inTangent Start tangent of the animation curve
  52575. * @param gradient Scalar amount to interpolate
  52576. * @returns InterpolatedVector3 value
  52577. */
  52578. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  52579. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  52580. };
  52581. /**
  52582. * Interpolates a Vector2 linearly
  52583. * @param startValue Start value of the animation curve
  52584. * @param endValue End value of the animation curve
  52585. * @param gradient Scalar amount to interpolate
  52586. * @returns Interpolated Vector2 value
  52587. */
  52588. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  52589. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  52590. };
  52591. /**
  52592. * Interpolates a Vector2 cubically
  52593. * @param startValue Start value of the animation curve
  52594. * @param outTangent End tangent of the animation
  52595. * @param endValue End value of the animation curve
  52596. * @param inTangent Start tangent of the animation curve
  52597. * @param gradient Scalar amount to interpolate
  52598. * @returns Interpolated Vector2 value
  52599. */
  52600. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  52601. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  52602. };
  52603. /**
  52604. * Interpolates a size linearly
  52605. * @param startValue Start value of the animation curve
  52606. * @param endValue End value of the animation curve
  52607. * @param gradient Scalar amount to interpolate
  52608. * @returns Interpolated Size value
  52609. */
  52610. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  52611. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  52612. };
  52613. /**
  52614. * Interpolates a Color3 linearly
  52615. * @param startValue Start value of the animation curve
  52616. * @param endValue End value of the animation curve
  52617. * @param gradient Scalar amount to interpolate
  52618. * @returns Interpolated Color3 value
  52619. */
  52620. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  52621. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  52622. };
  52623. /**
  52624. * @hidden Internal use only
  52625. */
  52626. Animation.prototype._getKeyValue = function (value) {
  52627. if (typeof value === "function") {
  52628. return value();
  52629. }
  52630. return value;
  52631. };
  52632. /**
  52633. * @hidden Internal use only
  52634. */
  52635. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  52636. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  52637. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  52638. }
  52639. var keys = this.getKeys();
  52640. // Try to get a hash to find the right key
  52641. 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));
  52642. if (keys[startKeyIndex].frame >= currentFrame) {
  52643. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  52644. startKeyIndex--;
  52645. }
  52646. }
  52647. for (var key = startKeyIndex; key < keys.length; key++) {
  52648. var endKey = keys[key + 1];
  52649. if (endKey.frame >= currentFrame) {
  52650. var startKey = keys[key];
  52651. var startValue = this._getKeyValue(startKey.value);
  52652. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  52653. return startValue;
  52654. }
  52655. var endValue = this._getKeyValue(endKey.value);
  52656. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  52657. var frameDelta = endKey.frame - startKey.frame;
  52658. // gradient : percent of currentFrame between the frame inf and the frame sup
  52659. var gradient = (currentFrame - startKey.frame) / frameDelta;
  52660. // check for easingFunction and correction of gradient
  52661. var easingFunction = this.getEasingFunction();
  52662. if (easingFunction != null) {
  52663. gradient = easingFunction.ease(gradient);
  52664. }
  52665. switch (this.dataType) {
  52666. // Float
  52667. case Animation.ANIMATIONTYPE_FLOAT:
  52668. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  52669. switch (loopMode) {
  52670. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52671. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52672. return floatValue;
  52673. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52674. return offsetValue * repeatCount + floatValue;
  52675. }
  52676. break;
  52677. // Quaternion
  52678. case Animation.ANIMATIONTYPE_QUATERNION:
  52679. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  52680. switch (loopMode) {
  52681. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52682. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52683. return quatValue;
  52684. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52685. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  52686. }
  52687. return quatValue;
  52688. // Vector3
  52689. case Animation.ANIMATIONTYPE_VECTOR3:
  52690. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  52691. switch (loopMode) {
  52692. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52693. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52694. return vec3Value;
  52695. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52696. return vec3Value.add(offsetValue.scale(repeatCount));
  52697. }
  52698. // Vector2
  52699. case Animation.ANIMATIONTYPE_VECTOR2:
  52700. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  52701. switch (loopMode) {
  52702. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52703. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52704. return vec2Value;
  52705. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52706. return vec2Value.add(offsetValue.scale(repeatCount));
  52707. }
  52708. // Size
  52709. case Animation.ANIMATIONTYPE_SIZE:
  52710. switch (loopMode) {
  52711. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52712. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52713. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  52714. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52715. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  52716. }
  52717. // Color3
  52718. case Animation.ANIMATIONTYPE_COLOR3:
  52719. switch (loopMode) {
  52720. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52721. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52722. return this.color3InterpolateFunction(startValue, endValue, gradient);
  52723. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52724. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  52725. }
  52726. // Matrix
  52727. case Animation.ANIMATIONTYPE_MATRIX:
  52728. switch (loopMode) {
  52729. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52730. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52731. if (Animation.AllowMatricesInterpolation) {
  52732. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  52733. }
  52734. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52735. return startValue;
  52736. }
  52737. default:
  52738. break;
  52739. }
  52740. break;
  52741. }
  52742. }
  52743. return this._getKeyValue(keys[keys.length - 1].value);
  52744. };
  52745. /**
  52746. * Defines the function to use to interpolate matrices
  52747. * @param startValue defines the start matrix
  52748. * @param endValue defines the end matrix
  52749. * @param gradient defines the gradient between both matrices
  52750. * @param result defines an optional target matrix where to store the interpolation
  52751. * @returns the interpolated matrix
  52752. */
  52753. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  52754. if (Animation.AllowMatrixDecomposeForInterpolation) {
  52755. if (result) {
  52756. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  52757. return result;
  52758. }
  52759. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  52760. }
  52761. if (result) {
  52762. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  52763. return result;
  52764. }
  52765. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  52766. };
  52767. /**
  52768. * Makes a copy of the animation
  52769. * @returns Cloned animation
  52770. */
  52771. Animation.prototype.clone = function () {
  52772. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  52773. clone.enableBlending = this.enableBlending;
  52774. clone.blendingSpeed = this.blendingSpeed;
  52775. if (this._keys) {
  52776. clone.setKeys(this._keys);
  52777. }
  52778. if (this._ranges) {
  52779. clone._ranges = {};
  52780. for (var name in this._ranges) {
  52781. var range = this._ranges[name];
  52782. if (!range) {
  52783. continue;
  52784. }
  52785. clone._ranges[name] = range.clone();
  52786. }
  52787. }
  52788. return clone;
  52789. };
  52790. /**
  52791. * Sets the key frames of the animation
  52792. * @param values The animation key frames to set
  52793. */
  52794. Animation.prototype.setKeys = function (values) {
  52795. this._keys = values.slice(0);
  52796. };
  52797. /**
  52798. * Serializes the animation to an object
  52799. * @returns Serialized object
  52800. */
  52801. Animation.prototype.serialize = function () {
  52802. var serializationObject = {};
  52803. serializationObject.name = this.name;
  52804. serializationObject.property = this.targetProperty;
  52805. serializationObject.framePerSecond = this.framePerSecond;
  52806. serializationObject.dataType = this.dataType;
  52807. serializationObject.loopBehavior = this.loopMode;
  52808. serializationObject.enableBlending = this.enableBlending;
  52809. serializationObject.blendingSpeed = this.blendingSpeed;
  52810. var dataType = this.dataType;
  52811. serializationObject.keys = [];
  52812. var keys = this.getKeys();
  52813. for (var index = 0; index < keys.length; index++) {
  52814. var animationKey = keys[index];
  52815. var key = {};
  52816. key.frame = animationKey.frame;
  52817. switch (dataType) {
  52818. case Animation.ANIMATIONTYPE_FLOAT:
  52819. key.values = [animationKey.value];
  52820. break;
  52821. case Animation.ANIMATIONTYPE_QUATERNION:
  52822. case Animation.ANIMATIONTYPE_MATRIX:
  52823. case Animation.ANIMATIONTYPE_VECTOR3:
  52824. case Animation.ANIMATIONTYPE_COLOR3:
  52825. key.values = animationKey.value.asArray();
  52826. break;
  52827. }
  52828. serializationObject.keys.push(key);
  52829. }
  52830. serializationObject.ranges = [];
  52831. for (var name in this._ranges) {
  52832. var source = this._ranges[name];
  52833. if (!source) {
  52834. continue;
  52835. }
  52836. var range = {};
  52837. range.name = name;
  52838. range.from = source.from;
  52839. range.to = source.to;
  52840. serializationObject.ranges.push(range);
  52841. }
  52842. return serializationObject;
  52843. };
  52844. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  52845. /**
  52846. * Get the float animation type
  52847. */
  52848. get: function () {
  52849. return Animation._ANIMATIONTYPE_FLOAT;
  52850. },
  52851. enumerable: true,
  52852. configurable: true
  52853. });
  52854. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  52855. /**
  52856. * Get the Vector3 animation type
  52857. */
  52858. get: function () {
  52859. return Animation._ANIMATIONTYPE_VECTOR3;
  52860. },
  52861. enumerable: true,
  52862. configurable: true
  52863. });
  52864. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  52865. /**
  52866. * Get the Vector2 animation type
  52867. */
  52868. get: function () {
  52869. return Animation._ANIMATIONTYPE_VECTOR2;
  52870. },
  52871. enumerable: true,
  52872. configurable: true
  52873. });
  52874. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  52875. /**
  52876. * Get the Size animation type
  52877. */
  52878. get: function () {
  52879. return Animation._ANIMATIONTYPE_SIZE;
  52880. },
  52881. enumerable: true,
  52882. configurable: true
  52883. });
  52884. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  52885. /**
  52886. * Get the Quaternion animation type
  52887. */
  52888. get: function () {
  52889. return Animation._ANIMATIONTYPE_QUATERNION;
  52890. },
  52891. enumerable: true,
  52892. configurable: true
  52893. });
  52894. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  52895. /**
  52896. * Get the Matrix animation type
  52897. */
  52898. get: function () {
  52899. return Animation._ANIMATIONTYPE_MATRIX;
  52900. },
  52901. enumerable: true,
  52902. configurable: true
  52903. });
  52904. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  52905. /**
  52906. * Get the Color3 animation type
  52907. */
  52908. get: function () {
  52909. return Animation._ANIMATIONTYPE_COLOR3;
  52910. },
  52911. enumerable: true,
  52912. configurable: true
  52913. });
  52914. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  52915. /**
  52916. * Get the Relative Loop Mode
  52917. */
  52918. get: function () {
  52919. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  52920. },
  52921. enumerable: true,
  52922. configurable: true
  52923. });
  52924. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  52925. /**
  52926. * Get the Cycle Loop Mode
  52927. */
  52928. get: function () {
  52929. return Animation._ANIMATIONLOOPMODE_CYCLE;
  52930. },
  52931. enumerable: true,
  52932. configurable: true
  52933. });
  52934. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  52935. /**
  52936. * Get the Constant Loop Mode
  52937. */
  52938. get: function () {
  52939. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  52940. },
  52941. enumerable: true,
  52942. configurable: true
  52943. });
  52944. /** @hidden */
  52945. Animation._UniversalLerp = function (left, right, amount) {
  52946. var constructor = left.constructor;
  52947. if (constructor.Lerp) { // Lerp supported
  52948. return constructor.Lerp(left, right, amount);
  52949. }
  52950. else if (constructor.Slerp) { // Slerp supported
  52951. return constructor.Slerp(left, right, amount);
  52952. }
  52953. else if (left.toFixed) { // Number
  52954. return left * (1.0 - amount) + amount * right;
  52955. }
  52956. else { // Blending not supported
  52957. return right;
  52958. }
  52959. };
  52960. /**
  52961. * Parses an animation object and creates an animation
  52962. * @param parsedAnimation Parsed animation object
  52963. * @returns Animation object
  52964. */
  52965. Animation.Parse = function (parsedAnimation) {
  52966. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  52967. var dataType = parsedAnimation.dataType;
  52968. var keys = [];
  52969. var data;
  52970. var index;
  52971. if (parsedAnimation.enableBlending) {
  52972. animation.enableBlending = parsedAnimation.enableBlending;
  52973. }
  52974. if (parsedAnimation.blendingSpeed) {
  52975. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  52976. }
  52977. for (index = 0; index < parsedAnimation.keys.length; index++) {
  52978. var key = parsedAnimation.keys[index];
  52979. var inTangent;
  52980. var outTangent;
  52981. switch (dataType) {
  52982. case Animation.ANIMATIONTYPE_FLOAT:
  52983. data = key.values[0];
  52984. if (key.values.length >= 1) {
  52985. inTangent = key.values[1];
  52986. }
  52987. if (key.values.length >= 2) {
  52988. outTangent = key.values[2];
  52989. }
  52990. break;
  52991. case Animation.ANIMATIONTYPE_QUATERNION:
  52992. data = BABYLON.Quaternion.FromArray(key.values);
  52993. if (key.values.length >= 8) {
  52994. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  52995. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  52996. inTangent = _inTangent;
  52997. }
  52998. }
  52999. if (key.values.length >= 12) {
  53000. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  53001. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  53002. outTangent = _outTangent;
  53003. }
  53004. }
  53005. break;
  53006. case Animation.ANIMATIONTYPE_MATRIX:
  53007. data = BABYLON.Matrix.FromArray(key.values);
  53008. break;
  53009. case Animation.ANIMATIONTYPE_COLOR3:
  53010. data = BABYLON.Color3.FromArray(key.values);
  53011. break;
  53012. case Animation.ANIMATIONTYPE_VECTOR3:
  53013. default:
  53014. data = BABYLON.Vector3.FromArray(key.values);
  53015. break;
  53016. }
  53017. var keyData = {};
  53018. keyData.frame = key.frame;
  53019. keyData.value = data;
  53020. if (inTangent != undefined) {
  53021. keyData.inTangent = inTangent;
  53022. }
  53023. if (outTangent != undefined) {
  53024. keyData.outTangent = outTangent;
  53025. }
  53026. keys.push(keyData);
  53027. }
  53028. animation.setKeys(keys);
  53029. if (parsedAnimation.ranges) {
  53030. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  53031. data = parsedAnimation.ranges[index];
  53032. animation.createRange(data.name, data.from, data.to);
  53033. }
  53034. }
  53035. return animation;
  53036. };
  53037. /**
  53038. * Appends the serialized animations from the source animations
  53039. * @param source Source containing the animations
  53040. * @param destination Target to store the animations
  53041. */
  53042. Animation.AppendSerializedAnimations = function (source, destination) {
  53043. if (source.animations) {
  53044. destination.animations = [];
  53045. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  53046. var animation = source.animations[animationIndex];
  53047. destination.animations.push(animation.serialize());
  53048. }
  53049. }
  53050. };
  53051. /**
  53052. * Use matrix interpolation instead of using direct key value when animating matrices
  53053. */
  53054. Animation.AllowMatricesInterpolation = false;
  53055. /**
  53056. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  53057. */
  53058. Animation.AllowMatrixDecomposeForInterpolation = true;
  53059. // Statics
  53060. /**
  53061. * Float animation type
  53062. */
  53063. Animation._ANIMATIONTYPE_FLOAT = 0;
  53064. /**
  53065. * Vector3 animation type
  53066. */
  53067. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  53068. /**
  53069. * Quaternion animation type
  53070. */
  53071. Animation._ANIMATIONTYPE_QUATERNION = 2;
  53072. /**
  53073. * Matrix animation type
  53074. */
  53075. Animation._ANIMATIONTYPE_MATRIX = 3;
  53076. /**
  53077. * Color3 animation type
  53078. */
  53079. Animation._ANIMATIONTYPE_COLOR3 = 4;
  53080. /**
  53081. * Vector2 animation type
  53082. */
  53083. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  53084. /**
  53085. * Size animation type
  53086. */
  53087. Animation._ANIMATIONTYPE_SIZE = 6;
  53088. /**
  53089. * Relative Loop Mode
  53090. */
  53091. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  53092. /**
  53093. * Cycle Loop Mode
  53094. */
  53095. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  53096. /**
  53097. * Constant Loop Mode
  53098. */
  53099. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  53100. return Animation;
  53101. }());
  53102. BABYLON.Animation = Animation;
  53103. })(BABYLON || (BABYLON = {}));
  53104. //# sourceMappingURL=babylon.animation.js.map
  53105. var BABYLON;
  53106. (function (BABYLON) {
  53107. /**
  53108. * This class defines the direct association between an animation and a target
  53109. */
  53110. var TargetedAnimation = /** @class */ (function () {
  53111. function TargetedAnimation() {
  53112. }
  53113. return TargetedAnimation;
  53114. }());
  53115. BABYLON.TargetedAnimation = TargetedAnimation;
  53116. /**
  53117. * Use this class to create coordinated animations on multiple targets
  53118. */
  53119. var AnimationGroup = /** @class */ (function () {
  53120. /**
  53121. * Instantiates a new Animation Group.
  53122. * This helps managing several animations at once.
  53123. * @see http://doc.babylonjs.com/how_to/group
  53124. * @param name Defines the name of the group
  53125. * @param scene Defines the scene the group belongs to
  53126. */
  53127. function AnimationGroup(
  53128. /** The name of the animation group */
  53129. name, scene) {
  53130. if (scene === void 0) { scene = null; }
  53131. this.name = name;
  53132. this._targetedAnimations = new Array();
  53133. this._animatables = new Array();
  53134. this._from = Number.MAX_VALUE;
  53135. this._to = -Number.MAX_VALUE;
  53136. this._speedRatio = 1;
  53137. /**
  53138. * This observable will notify when one animation have ended.
  53139. */
  53140. this.onAnimationEndObservable = new BABYLON.Observable();
  53141. /**
  53142. * This observable will notify when all animations have ended.
  53143. */
  53144. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  53145. /**
  53146. * This observable will notify when all animations have paused.
  53147. */
  53148. this.onAnimationGroupPauseObservable = new BABYLON.Observable();
  53149. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53150. this._scene.animationGroups.push(this);
  53151. }
  53152. Object.defineProperty(AnimationGroup.prototype, "from", {
  53153. /**
  53154. * Gets the first frame
  53155. */
  53156. get: function () {
  53157. return this._from;
  53158. },
  53159. enumerable: true,
  53160. configurable: true
  53161. });
  53162. Object.defineProperty(AnimationGroup.prototype, "to", {
  53163. /**
  53164. * Gets the last frame
  53165. */
  53166. get: function () {
  53167. return this._to;
  53168. },
  53169. enumerable: true,
  53170. configurable: true
  53171. });
  53172. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  53173. /**
  53174. * Define if the animations are started
  53175. */
  53176. get: function () {
  53177. return this._isStarted;
  53178. },
  53179. enumerable: true,
  53180. configurable: true
  53181. });
  53182. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  53183. /**
  53184. * Gets or sets the speed ratio to use for all animations
  53185. */
  53186. get: function () {
  53187. return this._speedRatio;
  53188. },
  53189. /**
  53190. * Gets or sets the speed ratio to use for all animations
  53191. */
  53192. set: function (value) {
  53193. if (this._speedRatio === value) {
  53194. return;
  53195. }
  53196. this._speedRatio = value;
  53197. for (var index = 0; index < this._animatables.length; index++) {
  53198. var animatable = this._animatables[index];
  53199. animatable.speedRatio = this._speedRatio;
  53200. }
  53201. },
  53202. enumerable: true,
  53203. configurable: true
  53204. });
  53205. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  53206. /**
  53207. * Gets the targeted animations for this animation group
  53208. */
  53209. get: function () {
  53210. return this._targetedAnimations;
  53211. },
  53212. enumerable: true,
  53213. configurable: true
  53214. });
  53215. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  53216. /**
  53217. * returning the list of animatables controlled by this animation group.
  53218. */
  53219. get: function () {
  53220. return this._animatables;
  53221. },
  53222. enumerable: true,
  53223. configurable: true
  53224. });
  53225. /**
  53226. * Add an animation (with its target) in the group
  53227. * @param animation defines the animation we want to add
  53228. * @param target defines the target of the animation
  53229. * @returns the TargetedAnimation object
  53230. */
  53231. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  53232. var targetedAnimation = {
  53233. animation: animation,
  53234. target: target
  53235. };
  53236. var keys = animation.getKeys();
  53237. if (this._from > keys[0].frame) {
  53238. this._from = keys[0].frame;
  53239. }
  53240. if (this._to < keys[keys.length - 1].frame) {
  53241. this._to = keys[keys.length - 1].frame;
  53242. }
  53243. this._targetedAnimations.push(targetedAnimation);
  53244. return targetedAnimation;
  53245. };
  53246. /**
  53247. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  53248. * It can add constant keys at begin or end
  53249. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  53250. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  53251. * @returns the animation group
  53252. */
  53253. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  53254. if (beginFrame === void 0) { beginFrame = null; }
  53255. if (endFrame === void 0) { endFrame = null; }
  53256. if (beginFrame == null) {
  53257. beginFrame = this._from;
  53258. }
  53259. if (endFrame == null) {
  53260. endFrame = this._to;
  53261. }
  53262. for (var index = 0; index < this._targetedAnimations.length; index++) {
  53263. var targetedAnimation = this._targetedAnimations[index];
  53264. var keys = targetedAnimation.animation.getKeys();
  53265. var startKey = keys[0];
  53266. var endKey = keys[keys.length - 1];
  53267. if (startKey.frame > beginFrame) {
  53268. var newKey = {
  53269. frame: beginFrame,
  53270. value: startKey.value,
  53271. inTangent: startKey.inTangent,
  53272. outTangent: startKey.outTangent,
  53273. interpolation: startKey.interpolation
  53274. };
  53275. keys.splice(0, 0, newKey);
  53276. }
  53277. if (endKey.frame < endFrame) {
  53278. var newKey = {
  53279. frame: endFrame,
  53280. value: endKey.value,
  53281. inTangent: endKey.outTangent,
  53282. outTangent: endKey.outTangent,
  53283. interpolation: endKey.interpolation
  53284. };
  53285. keys.push(newKey);
  53286. }
  53287. }
  53288. this._from = beginFrame;
  53289. this._to = endFrame;
  53290. return this;
  53291. };
  53292. /**
  53293. * Start all animations on given targets
  53294. * @param loop defines if animations must loop
  53295. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  53296. * @param from defines the from key (optional)
  53297. * @param to defines the to key (optional)
  53298. * @returns the current animation group
  53299. */
  53300. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  53301. var _this = this;
  53302. if (loop === void 0) { loop = false; }
  53303. if (speedRatio === void 0) { speedRatio = 1; }
  53304. if (this._isStarted || this._targetedAnimations.length === 0) {
  53305. return this;
  53306. }
  53307. var _loop_1 = function (targetedAnimation) {
  53308. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  53309. animatable.onAnimationEnd = function () {
  53310. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  53311. _this._checkAnimationGroupEnded(animatable);
  53312. };
  53313. this_1._animatables.push(animatable);
  53314. };
  53315. var this_1 = this;
  53316. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  53317. var targetedAnimation = _a[_i];
  53318. _loop_1(targetedAnimation);
  53319. }
  53320. this._speedRatio = speedRatio;
  53321. this._isStarted = true;
  53322. return this;
  53323. };
  53324. /**
  53325. * Pause all animations
  53326. * @returns the animation group
  53327. */
  53328. AnimationGroup.prototype.pause = function () {
  53329. if (!this._isStarted) {
  53330. return this;
  53331. }
  53332. for (var index = 0; index < this._animatables.length; index++) {
  53333. var animatable = this._animatables[index];
  53334. animatable.pause();
  53335. }
  53336. this.onAnimationGroupPauseObservable.notifyObservers(this);
  53337. return this;
  53338. };
  53339. /**
  53340. * Play all animations to initial state
  53341. * This function will start() the animations if they were not started or will restart() them if they were paused
  53342. * @param loop defines if animations must loop
  53343. * @returns the animation group
  53344. */
  53345. AnimationGroup.prototype.play = function (loop) {
  53346. // only if all animatables are ready and exist
  53347. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  53348. if (loop !== undefined) {
  53349. for (var index = 0; index < this._animatables.length; index++) {
  53350. var animatable = this._animatables[index];
  53351. animatable.loopAnimation = loop;
  53352. }
  53353. }
  53354. this.restart();
  53355. }
  53356. else {
  53357. this.stop();
  53358. this.start(loop, this._speedRatio);
  53359. }
  53360. return this;
  53361. };
  53362. /**
  53363. * Reset all animations to initial state
  53364. * @returns the animation group
  53365. */
  53366. AnimationGroup.prototype.reset = function () {
  53367. if (!this._isStarted) {
  53368. return this;
  53369. }
  53370. for (var index = 0; index < this._animatables.length; index++) {
  53371. var animatable = this._animatables[index];
  53372. animatable.reset();
  53373. }
  53374. return this;
  53375. };
  53376. /**
  53377. * Restart animations from key 0
  53378. * @returns the animation group
  53379. */
  53380. AnimationGroup.prototype.restart = function () {
  53381. if (!this._isStarted) {
  53382. return this;
  53383. }
  53384. for (var index = 0; index < this._animatables.length; index++) {
  53385. var animatable = this._animatables[index];
  53386. animatable.restart();
  53387. }
  53388. return this;
  53389. };
  53390. /**
  53391. * Stop all animations
  53392. * @returns the animation group
  53393. */
  53394. AnimationGroup.prototype.stop = function () {
  53395. if (!this._isStarted) {
  53396. return this;
  53397. }
  53398. var list = this._animatables.slice();
  53399. for (var index = 0; index < list.length; index++) {
  53400. list[index].stop();
  53401. }
  53402. this._isStarted = false;
  53403. return this;
  53404. };
  53405. /**
  53406. * Set animation weight for all animatables
  53407. * @param weight defines the weight to use
  53408. * @return the animationGroup
  53409. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  53410. */
  53411. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  53412. for (var index = 0; index < this._animatables.length; index++) {
  53413. var animatable = this._animatables[index];
  53414. animatable.weight = weight;
  53415. }
  53416. return this;
  53417. };
  53418. /**
  53419. * Synchronize and normalize all animatables with a source animatable
  53420. * @param root defines the root animatable to synchronize with
  53421. * @return the animationGroup
  53422. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  53423. */
  53424. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  53425. for (var index = 0; index < this._animatables.length; index++) {
  53426. var animatable = this._animatables[index];
  53427. animatable.syncWith(root);
  53428. }
  53429. return this;
  53430. };
  53431. /**
  53432. * Goes to a specific frame in this animation group
  53433. * @param frame the frame number to go to
  53434. * @return the animationGroup
  53435. */
  53436. AnimationGroup.prototype.goToFrame = function (frame) {
  53437. if (!this._isStarted) {
  53438. return this;
  53439. }
  53440. for (var index = 0; index < this._animatables.length; index++) {
  53441. var animatable = this._animatables[index];
  53442. animatable.goToFrame(frame);
  53443. }
  53444. return this;
  53445. };
  53446. /**
  53447. * Dispose all associated resources
  53448. */
  53449. AnimationGroup.prototype.dispose = function () {
  53450. this._targetedAnimations = [];
  53451. this._animatables = [];
  53452. var index = this._scene.animationGroups.indexOf(this);
  53453. if (index > -1) {
  53454. this._scene.animationGroups.splice(index, 1);
  53455. }
  53456. };
  53457. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  53458. // animatable should be taken out of the array
  53459. var idx = this._animatables.indexOf(animatable);
  53460. if (idx > -1) {
  53461. this._animatables.splice(idx, 1);
  53462. }
  53463. // all animatables were removed? animation group ended!
  53464. if (this._animatables.length === 0) {
  53465. this._isStarted = false;
  53466. this.onAnimationGroupEndObservable.notifyObservers(this);
  53467. }
  53468. };
  53469. // Statics
  53470. /**
  53471. * Returns a new AnimationGroup object parsed from the source provided.
  53472. * @param parsedAnimationGroup defines the source
  53473. * @param scene defines the scene that will receive the animationGroup
  53474. * @returns a new AnimationGroup
  53475. */
  53476. AnimationGroup.Parse = function (parsedAnimationGroup, scene) {
  53477. var animationGroup = new BABYLON.AnimationGroup(parsedAnimationGroup.name, scene);
  53478. for (var i = 0; i < parsedAnimationGroup.targetedAnimations.length; i++) {
  53479. var targetedAnimation = parsedAnimationGroup.targetedAnimations[i];
  53480. var animation = BABYLON.Animation.Parse(targetedAnimation.animation);
  53481. var id = targetedAnimation.targetId;
  53482. var targetNode = scene.getNodeByID(id);
  53483. if (targetNode != null) {
  53484. animationGroup.addTargetedAnimation(animation, targetNode);
  53485. }
  53486. }
  53487. if (parsedAnimationGroup.from !== null && parsedAnimationGroup.from !== null) {
  53488. animationGroup.normalize(parsedAnimationGroup.from, parsedAnimationGroup.to);
  53489. }
  53490. return animationGroup;
  53491. };
  53492. /**
  53493. * Returns the string "AnimationGroup"
  53494. * @returns "AnimationGroup"
  53495. */
  53496. AnimationGroup.prototype.getClassName = function () {
  53497. return "AnimationGroup";
  53498. };
  53499. /**
  53500. * Creates a detailled string about the object
  53501. * @param fullDetails defines if the output string will support multiple levels of logging within scene loading
  53502. * @returns a string representing the object
  53503. */
  53504. AnimationGroup.prototype.toString = function (fullDetails) {
  53505. var ret = "Name: " + this.name;
  53506. ret += ", type: " + this.getClassName();
  53507. if (fullDetails) {
  53508. ret += ", from: " + this._from;
  53509. ret += ", to: " + this._to;
  53510. ret += ", isStarted: " + this._isStarted;
  53511. ret += ", speedRatio: " + this._speedRatio;
  53512. ret += ", targetedAnimations length: " + this._targetedAnimations.length;
  53513. ret += ", animatables length: " + this._animatables;
  53514. }
  53515. return ret;
  53516. };
  53517. return AnimationGroup;
  53518. }());
  53519. BABYLON.AnimationGroup = AnimationGroup;
  53520. })(BABYLON || (BABYLON = {}));
  53521. //# sourceMappingURL=babylon.animationGroup.js.map
  53522. var BABYLON;
  53523. (function (BABYLON) {
  53524. // Static values to help the garbage collector
  53525. // Quaternion
  53526. var _staticOffsetValueQuaternion = Object.freeze(new BABYLON.Quaternion(0, 0, 0, 0));
  53527. // Vector3
  53528. var _staticOffsetValueVector3 = Object.freeze(BABYLON.Vector3.Zero());
  53529. // Vector2
  53530. var _staticOffsetValueVector2 = Object.freeze(BABYLON.Vector2.Zero());
  53531. // Size
  53532. var _staticOffsetValueSize = Object.freeze(BABYLON.Size.Zero());
  53533. // Color3
  53534. var _staticOffsetValueColor3 = Object.freeze(BABYLON.Color3.Black());
  53535. /**
  53536. * Defines a runtime animation
  53537. */
  53538. var RuntimeAnimation = /** @class */ (function () {
  53539. /**
  53540. * Create a new RuntimeAnimation object
  53541. * @param target defines the target of the animation
  53542. * @param animation defines the source animation object
  53543. * @param scene defines the hosting scene
  53544. * @param host defines the initiating Animatable
  53545. */
  53546. function RuntimeAnimation(target, animation, scene, host) {
  53547. var _this = this;
  53548. this._events = new Array();
  53549. /**
  53550. * The current frame of the runtime animation
  53551. */
  53552. this._currentFrame = 0;
  53553. /**
  53554. * The original value of the runtime animation
  53555. */
  53556. this._originalValue = new Array();
  53557. /**
  53558. * The offsets cache of the runtime animation
  53559. */
  53560. this._offsetsCache = {};
  53561. /**
  53562. * The high limits cache of the runtime animation
  53563. */
  53564. this._highLimitsCache = {};
  53565. /**
  53566. * Specifies if the runtime animation has been stopped
  53567. */
  53568. this._stopped = false;
  53569. /**
  53570. * The blending factor of the runtime animation
  53571. */
  53572. this._blendingFactor = 0;
  53573. /**
  53574. * The target path of the runtime animation
  53575. */
  53576. this._targetPath = "";
  53577. /**
  53578. * The weight of the runtime animation
  53579. */
  53580. this._weight = 1.0;
  53581. /**
  53582. * The ratio offset of the runtime animation
  53583. */
  53584. this._ratioOffset = 0;
  53585. /**
  53586. * The previous delay of the runtime animation
  53587. */
  53588. this._previousDelay = 0;
  53589. /**
  53590. * The previous ratio of the runtime animation
  53591. */
  53592. this._previousRatio = 0;
  53593. this._animation = animation;
  53594. this._target = target;
  53595. this._scene = scene;
  53596. this._host = host;
  53597. animation._runtimeAnimations.push(this);
  53598. // Cloning events locally
  53599. var events = animation.getEvents();
  53600. if (events && events.length > 0) {
  53601. events.forEach(function (e) {
  53602. _this._events.push(e._clone());
  53603. });
  53604. }
  53605. }
  53606. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  53607. /**
  53608. * Gets the current frame of the runtime animation
  53609. */
  53610. get: function () {
  53611. return this._currentFrame;
  53612. },
  53613. enumerable: true,
  53614. configurable: true
  53615. });
  53616. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  53617. /**
  53618. * Gets the weight of the runtime animation
  53619. */
  53620. get: function () {
  53621. return this._weight;
  53622. },
  53623. enumerable: true,
  53624. configurable: true
  53625. });
  53626. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  53627. /**
  53628. * Gets the current value of the runtime animation
  53629. */
  53630. get: function () {
  53631. return this._currentValue;
  53632. },
  53633. enumerable: true,
  53634. configurable: true
  53635. });
  53636. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  53637. /**
  53638. * Gets the target path of the runtime animation
  53639. */
  53640. get: function () {
  53641. return this._targetPath;
  53642. },
  53643. enumerable: true,
  53644. configurable: true
  53645. });
  53646. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  53647. /**
  53648. * Gets the actual target of the runtime animation
  53649. */
  53650. get: function () {
  53651. return this._activeTarget;
  53652. },
  53653. enumerable: true,
  53654. configurable: true
  53655. });
  53656. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  53657. /**
  53658. * Gets the animation from the runtime animation
  53659. */
  53660. get: function () {
  53661. return this._animation;
  53662. },
  53663. enumerable: true,
  53664. configurable: true
  53665. });
  53666. /**
  53667. * Resets the runtime animation to the beginning
  53668. * @param restoreOriginal defines whether to restore the target property to the original value
  53669. */
  53670. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  53671. if (restoreOriginal === void 0) { restoreOriginal = false; }
  53672. if (restoreOriginal) {
  53673. if (this._target instanceof Array) {
  53674. var index = 0;
  53675. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  53676. var target = _a[_i];
  53677. if (this._originalValue[index] !== undefined) {
  53678. this._setValue(target, this._originalValue[index], -1);
  53679. }
  53680. index++;
  53681. }
  53682. }
  53683. else {
  53684. if (this._originalValue[0] !== undefined) {
  53685. this._setValue(this._target, this._originalValue[0], -1);
  53686. }
  53687. }
  53688. }
  53689. this._offsetsCache = {};
  53690. this._highLimitsCache = {};
  53691. this._currentFrame = 0;
  53692. this._blendingFactor = 0;
  53693. this._originalValue = new Array();
  53694. // Events
  53695. for (var index = 0; index < this._events.length; index++) {
  53696. this._events[index].isDone = false;
  53697. }
  53698. };
  53699. /**
  53700. * Specifies if the runtime animation is stopped
  53701. * @returns Boolean specifying if the runtime animation is stopped
  53702. */
  53703. RuntimeAnimation.prototype.isStopped = function () {
  53704. return this._stopped;
  53705. };
  53706. /**
  53707. * Disposes of the runtime animation
  53708. */
  53709. RuntimeAnimation.prototype.dispose = function () {
  53710. var index = this._animation.runtimeAnimations.indexOf(this);
  53711. if (index > -1) {
  53712. this._animation.runtimeAnimations.splice(index, 1);
  53713. }
  53714. };
  53715. /**
  53716. * Interpolates the animation from the current frame
  53717. * @param currentFrame The frame to interpolate the animation to
  53718. * @param repeatCount The number of times that the animation should loop
  53719. * @param loopMode The type of looping mode to use
  53720. * @param offsetValue Animation offset value
  53721. * @param highLimitValue The high limit value
  53722. * @returns The interpolated value
  53723. */
  53724. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  53725. this._currentFrame = currentFrame;
  53726. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  53727. this._workValue = BABYLON.Matrix.Zero();
  53728. }
  53729. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  53730. };
  53731. /**
  53732. * Apply the interpolated value to the target
  53733. * @param currentValue defines the value computed by the animation
  53734. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  53735. */
  53736. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  53737. if (weight === void 0) { weight = 1.0; }
  53738. if (this._target instanceof Array) {
  53739. var index = 0;
  53740. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  53741. var target = _a[_i];
  53742. this._setValue(target, currentValue, weight, index);
  53743. index++;
  53744. }
  53745. }
  53746. else {
  53747. this._setValue(this._target, currentValue, weight);
  53748. }
  53749. };
  53750. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  53751. if (targetIndex === void 0) { targetIndex = 0; }
  53752. // Set value
  53753. var path;
  53754. var destination;
  53755. var targetPropertyPath = this._animation.targetPropertyPath;
  53756. if (targetPropertyPath.length > 1) {
  53757. var property = target[targetPropertyPath[0]];
  53758. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  53759. property = property[targetPropertyPath[index]];
  53760. }
  53761. path = targetPropertyPath[targetPropertyPath.length - 1];
  53762. destination = property;
  53763. }
  53764. else {
  53765. path = targetPropertyPath[0];
  53766. destination = target;
  53767. }
  53768. this._targetPath = path;
  53769. this._activeTarget = destination;
  53770. this._weight = weight;
  53771. if (this._originalValue[targetIndex] === undefined) {
  53772. var originalValue = void 0;
  53773. if (destination.getRestPose && path === "_matrix") { // For bones
  53774. originalValue = destination.getRestPose();
  53775. }
  53776. else {
  53777. originalValue = destination[path];
  53778. }
  53779. if (originalValue && originalValue.clone) {
  53780. this._originalValue[targetIndex] = originalValue.clone();
  53781. }
  53782. else {
  53783. this._originalValue[targetIndex] = originalValue;
  53784. }
  53785. }
  53786. // Blending
  53787. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  53788. if (enableBlending && this._blendingFactor <= 1.0) {
  53789. if (!this._originalBlendValue) {
  53790. var originalValue = destination[path];
  53791. if (originalValue.clone) {
  53792. this._originalBlendValue = originalValue.clone();
  53793. }
  53794. else {
  53795. this._originalBlendValue = originalValue;
  53796. }
  53797. }
  53798. if (this._originalBlendValue.m) { // Matrix
  53799. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  53800. if (this._currentValue) {
  53801. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  53802. }
  53803. else {
  53804. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  53805. }
  53806. }
  53807. else {
  53808. if (this._currentValue) {
  53809. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  53810. }
  53811. else {
  53812. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  53813. }
  53814. }
  53815. }
  53816. else {
  53817. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  53818. }
  53819. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  53820. this._blendingFactor += blendingSpeed;
  53821. }
  53822. else {
  53823. this._currentValue = currentValue;
  53824. }
  53825. if (weight !== -1.0) {
  53826. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  53827. }
  53828. else {
  53829. destination[path] = this._currentValue;
  53830. }
  53831. if (target.markAsDirty) {
  53832. target.markAsDirty(this._animation.targetProperty);
  53833. }
  53834. };
  53835. /**
  53836. * Gets the loop pmode of the runtime animation
  53837. * @returns Loop Mode
  53838. */
  53839. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  53840. if (this._target && this._target.animationPropertiesOverride) {
  53841. return this._target.animationPropertiesOverride.loopMode;
  53842. }
  53843. return this._animation.loopMode;
  53844. };
  53845. /**
  53846. * Move the current animation to a given frame
  53847. * @param frame defines the frame to move to
  53848. */
  53849. RuntimeAnimation.prototype.goToFrame = function (frame) {
  53850. var keys = this._animation.getKeys();
  53851. if (frame < keys[0].frame) {
  53852. frame = keys[0].frame;
  53853. }
  53854. else if (frame > keys[keys.length - 1].frame) {
  53855. frame = keys[keys.length - 1].frame;
  53856. }
  53857. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  53858. this.setValue(currentValue, -1);
  53859. };
  53860. /**
  53861. * @hidden Internal use only
  53862. */
  53863. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  53864. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  53865. this._ratioOffset = this._previousRatio - newRatio;
  53866. };
  53867. /**
  53868. * Execute the current animation
  53869. * @param delay defines the delay to add to the current frame
  53870. * @param from defines the lower bound of the animation range
  53871. * @param to defines the upper bound of the animation range
  53872. * @param loop defines if the current animation must loop
  53873. * @param speedRatio defines the current speed ratio
  53874. * @param weight defines the weight of the animation (default is -1 so no weight)
  53875. * @returns a boolean indicating if the animation is running
  53876. */
  53877. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  53878. if (weight === void 0) { weight = -1.0; }
  53879. var targetPropertyPath = this._animation.targetPropertyPath;
  53880. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  53881. this._stopped = true;
  53882. return false;
  53883. }
  53884. var returnValue = true;
  53885. var keys = this._animation.getKeys();
  53886. // Adding a start key at frame 0 if missing
  53887. if (keys[0].frame !== 0) {
  53888. var newKey = { frame: 0, value: keys[0].value };
  53889. keys.splice(0, 0, newKey);
  53890. }
  53891. // Adding a duplicate key when there is only one key at frame zero
  53892. else if (keys.length === 1) {
  53893. var newKey = { frame: 0.001, value: keys[0].value };
  53894. keys.push(newKey);
  53895. }
  53896. // Check limits
  53897. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  53898. from = keys[0].frame;
  53899. }
  53900. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  53901. to = keys[keys.length - 1].frame;
  53902. }
  53903. //to and from cannot be the same key
  53904. if (from === to) {
  53905. if (from > keys[0].frame) {
  53906. from--;
  53907. }
  53908. else if (to < keys[keys.length - 1].frame) {
  53909. to++;
  53910. }
  53911. }
  53912. // Compute ratio
  53913. var range = to - from;
  53914. var offsetValue;
  53915. // ratio represents the frame delta between from and to
  53916. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  53917. var highLimitValue = 0;
  53918. this._previousDelay = delay;
  53919. this._previousRatio = ratio;
  53920. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  53921. returnValue = false;
  53922. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  53923. }
  53924. else {
  53925. // Get max value if required
  53926. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  53927. var keyOffset = to.toString() + from.toString();
  53928. if (!this._offsetsCache[keyOffset]) {
  53929. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  53930. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  53931. switch (this._animation.dataType) {
  53932. // Float
  53933. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  53934. this._offsetsCache[keyOffset] = toValue - fromValue;
  53935. break;
  53936. // Quaternion
  53937. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  53938. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53939. break;
  53940. // Vector3
  53941. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  53942. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53943. // Vector2
  53944. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  53945. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53946. // Size
  53947. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  53948. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53949. // Color3
  53950. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  53951. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53952. default:
  53953. break;
  53954. }
  53955. this._highLimitsCache[keyOffset] = toValue;
  53956. }
  53957. highLimitValue = this._highLimitsCache[keyOffset];
  53958. offsetValue = this._offsetsCache[keyOffset];
  53959. }
  53960. }
  53961. if (offsetValue === undefined) {
  53962. switch (this._animation.dataType) {
  53963. // Float
  53964. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  53965. offsetValue = 0;
  53966. break;
  53967. // Quaternion
  53968. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  53969. offsetValue = _staticOffsetValueQuaternion;
  53970. break;
  53971. // Vector3
  53972. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  53973. offsetValue = _staticOffsetValueVector3;
  53974. break;
  53975. // Vector2
  53976. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  53977. offsetValue = _staticOffsetValueVector2;
  53978. break;
  53979. // Size
  53980. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  53981. offsetValue = _staticOffsetValueSize;
  53982. break;
  53983. // Color3
  53984. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  53985. offsetValue = _staticOffsetValueColor3;
  53986. }
  53987. }
  53988. // Compute value
  53989. var repeatCount = (ratio / range) >> 0;
  53990. var currentFrame = returnValue ? from + ratio % range : to;
  53991. // Need to normalize?
  53992. if (this._host && this._host.syncRoot) {
  53993. var syncRoot = this._host.syncRoot;
  53994. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  53995. currentFrame = from + (to - from) * hostNormalizedFrame;
  53996. }
  53997. // Reset events if looping
  53998. var events = this._events;
  53999. if (range > 0 && this.currentFrame > currentFrame ||
  54000. range < 0 && this.currentFrame < currentFrame) {
  54001. // Need to reset animation events
  54002. for (var index = 0; index < events.length; index++) {
  54003. if (!events[index].onlyOnce) {
  54004. // reset event, the animation is looping
  54005. events[index].isDone = false;
  54006. }
  54007. }
  54008. }
  54009. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  54010. // Set value
  54011. this.setValue(currentValue, weight);
  54012. // Check events
  54013. for (var index = 0; index < events.length; index++) {
  54014. // Make sure current frame has passed event frame and that event frame is within the current range
  54015. // Also, handle both forward and reverse animations
  54016. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  54017. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  54018. var event = events[index];
  54019. if (!event.isDone) {
  54020. // If event should be done only once, remove it.
  54021. if (event.onlyOnce) {
  54022. events.splice(index, 1);
  54023. index--;
  54024. }
  54025. event.isDone = true;
  54026. event.action(currentFrame);
  54027. } // Don't do anything if the event has already be done.
  54028. }
  54029. }
  54030. if (!returnValue) {
  54031. this._stopped = true;
  54032. }
  54033. return returnValue;
  54034. };
  54035. return RuntimeAnimation;
  54036. }());
  54037. BABYLON.RuntimeAnimation = RuntimeAnimation;
  54038. })(BABYLON || (BABYLON = {}));
  54039. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  54040. var BABYLON;
  54041. (function (BABYLON) {
  54042. /**
  54043. * Class used to store an actual running animation
  54044. */
  54045. var Animatable = /** @class */ (function () {
  54046. /**
  54047. * Creates a new Animatable
  54048. * @param scene defines the hosting scene
  54049. * @param target defines the target object
  54050. * @param fromFrame defines the starting frame number (default is 0)
  54051. * @param toFrame defines the ending frame number (default is 100)
  54052. * @param loopAnimation defines if the animation must loop (default is false)
  54053. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  54054. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  54055. * @param animations defines a group of animation to add to the new Animatable
  54056. */
  54057. function Animatable(scene,
  54058. /** defines the target object */
  54059. target,
  54060. /** defines the starting frame number (default is 0) */
  54061. fromFrame,
  54062. /** defines the ending frame number (default is 100) */
  54063. toFrame,
  54064. /** defines if the animation must loop (default is false) */
  54065. loopAnimation, speedRatio,
  54066. /** defines a callback to call when animation ends if it is not looping */
  54067. onAnimationEnd, animations) {
  54068. if (fromFrame === void 0) { fromFrame = 0; }
  54069. if (toFrame === void 0) { toFrame = 100; }
  54070. if (loopAnimation === void 0) { loopAnimation = false; }
  54071. if (speedRatio === void 0) { speedRatio = 1.0; }
  54072. this.target = target;
  54073. this.fromFrame = fromFrame;
  54074. this.toFrame = toFrame;
  54075. this.loopAnimation = loopAnimation;
  54076. this.onAnimationEnd = onAnimationEnd;
  54077. this._localDelayOffset = null;
  54078. this._pausedDelay = null;
  54079. this._runtimeAnimations = new Array();
  54080. this._paused = false;
  54081. this._speedRatio = 1;
  54082. this._weight = -1.0;
  54083. /**
  54084. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  54085. * This will only apply for non looping animation (default is true)
  54086. */
  54087. this.disposeOnEnd = true;
  54088. /**
  54089. * Gets a boolean indicating if the animation has started
  54090. */
  54091. this.animationStarted = false;
  54092. /**
  54093. * Observer raised when the animation ends
  54094. */
  54095. this.onAnimationEndObservable = new BABYLON.Observable();
  54096. this._scene = scene;
  54097. if (animations) {
  54098. this.appendAnimations(target, animations);
  54099. }
  54100. this._speedRatio = speedRatio;
  54101. scene._activeAnimatables.push(this);
  54102. }
  54103. Object.defineProperty(Animatable.prototype, "syncRoot", {
  54104. /**
  54105. * Gets the root Animatable used to synchronize and normalize animations
  54106. */
  54107. get: function () {
  54108. return this._syncRoot;
  54109. },
  54110. enumerable: true,
  54111. configurable: true
  54112. });
  54113. Object.defineProperty(Animatable.prototype, "masterFrame", {
  54114. /**
  54115. * Gets the current frame of the first RuntimeAnimation
  54116. * Used to synchronize Animatables
  54117. */
  54118. get: function () {
  54119. if (this._runtimeAnimations.length === 0) {
  54120. return 0;
  54121. }
  54122. return this._runtimeAnimations[0].currentFrame;
  54123. },
  54124. enumerable: true,
  54125. configurable: true
  54126. });
  54127. Object.defineProperty(Animatable.prototype, "weight", {
  54128. /**
  54129. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  54130. */
  54131. get: function () {
  54132. return this._weight;
  54133. },
  54134. set: function (value) {
  54135. if (value === -1) { // -1 is ok and means no weight
  54136. this._weight = -1;
  54137. return;
  54138. }
  54139. // Else weight must be in [0, 1] range
  54140. this._weight = Math.min(Math.max(value, 0), 1.0);
  54141. },
  54142. enumerable: true,
  54143. configurable: true
  54144. });
  54145. Object.defineProperty(Animatable.prototype, "speedRatio", {
  54146. /**
  54147. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  54148. */
  54149. get: function () {
  54150. return this._speedRatio;
  54151. },
  54152. set: function (value) {
  54153. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  54154. var animation = this._runtimeAnimations[index];
  54155. animation._prepareForSpeedRatioChange(value);
  54156. }
  54157. this._speedRatio = value;
  54158. },
  54159. enumerable: true,
  54160. configurable: true
  54161. });
  54162. // Methods
  54163. /**
  54164. * Synchronize and normalize current Animatable with a source Animatable
  54165. * This is useful when using animation weights and when animations are not of the same length
  54166. * @param root defines the root Animatable to synchronize with
  54167. * @returns the current Animatable
  54168. */
  54169. Animatable.prototype.syncWith = function (root) {
  54170. this._syncRoot = root;
  54171. if (root) {
  54172. // Make sure this animatable will animate after the root
  54173. var index = this._scene._activeAnimatables.indexOf(this);
  54174. if (index > -1) {
  54175. this._scene._activeAnimatables.splice(index, 1);
  54176. this._scene._activeAnimatables.push(this);
  54177. }
  54178. }
  54179. return this;
  54180. };
  54181. /**
  54182. * Gets the list of runtime animations
  54183. * @returns an array of RuntimeAnimation
  54184. */
  54185. Animatable.prototype.getAnimations = function () {
  54186. return this._runtimeAnimations;
  54187. };
  54188. /**
  54189. * Adds more animations to the current animatable
  54190. * @param target defines the target of the animations
  54191. * @param animations defines the new animations to add
  54192. */
  54193. Animatable.prototype.appendAnimations = function (target, animations) {
  54194. for (var index = 0; index < animations.length; index++) {
  54195. var animation = animations[index];
  54196. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  54197. }
  54198. };
  54199. /**
  54200. * Gets the source animation for a specific property
  54201. * @param property defines the propertyu to look for
  54202. * @returns null or the source animation for the given property
  54203. */
  54204. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  54205. var runtimeAnimations = this._runtimeAnimations;
  54206. for (var index = 0; index < runtimeAnimations.length; index++) {
  54207. if (runtimeAnimations[index].animation.targetProperty === property) {
  54208. return runtimeAnimations[index].animation;
  54209. }
  54210. }
  54211. return null;
  54212. };
  54213. /**
  54214. * Gets the runtime animation for a specific property
  54215. * @param property defines the propertyu to look for
  54216. * @returns null or the runtime animation for the given property
  54217. */
  54218. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  54219. var runtimeAnimations = this._runtimeAnimations;
  54220. for (var index = 0; index < runtimeAnimations.length; index++) {
  54221. if (runtimeAnimations[index].animation.targetProperty === property) {
  54222. return runtimeAnimations[index];
  54223. }
  54224. }
  54225. return null;
  54226. };
  54227. /**
  54228. * Resets the animatable to its original state
  54229. */
  54230. Animatable.prototype.reset = function () {
  54231. var runtimeAnimations = this._runtimeAnimations;
  54232. for (var index = 0; index < runtimeAnimations.length; index++) {
  54233. runtimeAnimations[index].reset(true);
  54234. }
  54235. this._localDelayOffset = null;
  54236. this._pausedDelay = null;
  54237. };
  54238. /**
  54239. * Allows the animatable to blend with current running animations
  54240. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  54241. * @param blendingSpeed defines the blending speed to use
  54242. */
  54243. Animatable.prototype.enableBlending = function (blendingSpeed) {
  54244. var runtimeAnimations = this._runtimeAnimations;
  54245. for (var index = 0; index < runtimeAnimations.length; index++) {
  54246. runtimeAnimations[index].animation.enableBlending = true;
  54247. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  54248. }
  54249. };
  54250. /**
  54251. * Disable animation blending
  54252. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  54253. */
  54254. Animatable.prototype.disableBlending = function () {
  54255. var runtimeAnimations = this._runtimeAnimations;
  54256. for (var index = 0; index < runtimeAnimations.length; index++) {
  54257. runtimeAnimations[index].animation.enableBlending = false;
  54258. }
  54259. };
  54260. /**
  54261. * Jump directly to a given frame
  54262. * @param frame defines the frame to jump to
  54263. */
  54264. Animatable.prototype.goToFrame = function (frame) {
  54265. var runtimeAnimations = this._runtimeAnimations;
  54266. if (runtimeAnimations[0]) {
  54267. var fps = runtimeAnimations[0].animation.framePerSecond;
  54268. var currentFrame = runtimeAnimations[0].currentFrame;
  54269. var adjustTime = frame - currentFrame;
  54270. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  54271. if (this._localDelayOffset === null) {
  54272. this._localDelayOffset = 0;
  54273. }
  54274. this._localDelayOffset -= delay;
  54275. }
  54276. for (var index = 0; index < runtimeAnimations.length; index++) {
  54277. runtimeAnimations[index].goToFrame(frame);
  54278. }
  54279. };
  54280. /**
  54281. * Pause the animation
  54282. */
  54283. Animatable.prototype.pause = function () {
  54284. if (this._paused) {
  54285. return;
  54286. }
  54287. this._paused = true;
  54288. };
  54289. /**
  54290. * Restart the animation
  54291. */
  54292. Animatable.prototype.restart = function () {
  54293. this._paused = false;
  54294. };
  54295. Animatable.prototype._raiseOnAnimationEnd = function () {
  54296. if (this.onAnimationEnd) {
  54297. this.onAnimationEnd();
  54298. }
  54299. this.onAnimationEndObservable.notifyObservers(this);
  54300. };
  54301. /**
  54302. * Stop and delete the current animation
  54303. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  54304. * @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)
  54305. */
  54306. Animatable.prototype.stop = function (animationName, targetMask) {
  54307. if (animationName || targetMask) {
  54308. var idx = this._scene._activeAnimatables.indexOf(this);
  54309. if (idx > -1) {
  54310. var runtimeAnimations = this._runtimeAnimations;
  54311. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  54312. var runtimeAnimation = runtimeAnimations[index];
  54313. if (animationName && runtimeAnimation.animation.name != animationName) {
  54314. continue;
  54315. }
  54316. if (targetMask && !targetMask(runtimeAnimation.target)) {
  54317. continue;
  54318. }
  54319. runtimeAnimation.dispose();
  54320. runtimeAnimations.splice(index, 1);
  54321. }
  54322. if (runtimeAnimations.length == 0) {
  54323. this._scene._activeAnimatables.splice(idx, 1);
  54324. this._raiseOnAnimationEnd();
  54325. }
  54326. }
  54327. }
  54328. else {
  54329. var index = this._scene._activeAnimatables.indexOf(this);
  54330. if (index > -1) {
  54331. this._scene._activeAnimatables.splice(index, 1);
  54332. var runtimeAnimations = this._runtimeAnimations;
  54333. for (var index = 0; index < runtimeAnimations.length; index++) {
  54334. runtimeAnimations[index].dispose();
  54335. }
  54336. this._raiseOnAnimationEnd();
  54337. }
  54338. }
  54339. };
  54340. /**
  54341. * Wait asynchronously for the animation to end
  54342. * @returns a promise which will be fullfilled when the animation ends
  54343. */
  54344. Animatable.prototype.waitAsync = function () {
  54345. var _this = this;
  54346. return new Promise(function (resolve, reject) {
  54347. _this.onAnimationEndObservable.add(function () {
  54348. resolve(_this);
  54349. }, undefined, undefined, _this, true);
  54350. });
  54351. };
  54352. /** @hidden */
  54353. Animatable.prototype._animate = function (delay) {
  54354. if (this._paused) {
  54355. this.animationStarted = false;
  54356. if (this._pausedDelay === null) {
  54357. this._pausedDelay = delay;
  54358. }
  54359. return true;
  54360. }
  54361. if (this._localDelayOffset === null) {
  54362. this._localDelayOffset = delay;
  54363. this._pausedDelay = null;
  54364. }
  54365. else if (this._pausedDelay !== null) {
  54366. this._localDelayOffset += delay - this._pausedDelay;
  54367. this._pausedDelay = null;
  54368. }
  54369. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  54370. return true;
  54371. }
  54372. // Animating
  54373. var running = false;
  54374. var runtimeAnimations = this._runtimeAnimations;
  54375. var index;
  54376. for (index = 0; index < runtimeAnimations.length; index++) {
  54377. var animation = runtimeAnimations[index];
  54378. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  54379. running = running || isRunning;
  54380. }
  54381. this.animationStarted = running;
  54382. if (!running) {
  54383. if (this.disposeOnEnd) {
  54384. // Remove from active animatables
  54385. index = this._scene._activeAnimatables.indexOf(this);
  54386. this._scene._activeAnimatables.splice(index, 1);
  54387. // Dispose all runtime animations
  54388. for (index = 0; index < runtimeAnimations.length; index++) {
  54389. runtimeAnimations[index].dispose();
  54390. }
  54391. }
  54392. this._raiseOnAnimationEnd();
  54393. if (this.disposeOnEnd) {
  54394. this.onAnimationEnd = null;
  54395. this.onAnimationEndObservable.clear();
  54396. }
  54397. }
  54398. return running;
  54399. };
  54400. return Animatable;
  54401. }());
  54402. BABYLON.Animatable = Animatable;
  54403. })(BABYLON || (BABYLON = {}));
  54404. //# sourceMappingURL=babylon.animatable.js.map
  54405. var BABYLON;
  54406. (function (BABYLON) {
  54407. /**
  54408. * Base class used for every default easing function.
  54409. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54410. */
  54411. var EasingFunction = /** @class */ (function () {
  54412. function EasingFunction() {
  54413. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  54414. }
  54415. /**
  54416. * Sets the easing mode of the current function.
  54417. * @param easingMode Defines the willing mode (EASINGMODE_EASEIN, EASINGMODE_EASEOUT or EASINGMODE_EASEINOUT)
  54418. */
  54419. EasingFunction.prototype.setEasingMode = function (easingMode) {
  54420. var n = Math.min(Math.max(easingMode, 0), 2);
  54421. this._easingMode = n;
  54422. };
  54423. /**
  54424. * Gets the current easing mode.
  54425. * @returns the easing mode
  54426. */
  54427. EasingFunction.prototype.getEasingMode = function () {
  54428. return this._easingMode;
  54429. };
  54430. /**
  54431. * @hidden
  54432. */
  54433. EasingFunction.prototype.easeInCore = function (gradient) {
  54434. throw new Error('You must implement this method');
  54435. };
  54436. /**
  54437. * Given an input gradient between 0 and 1, this returns the corrseponding value
  54438. * of the easing function.
  54439. * @param gradient Defines the value between 0 and 1 we want the easing value for
  54440. * @returns the corresponding value on the curve defined by the easing function
  54441. */
  54442. EasingFunction.prototype.ease = function (gradient) {
  54443. switch (this._easingMode) {
  54444. case EasingFunction.EASINGMODE_EASEIN:
  54445. return this.easeInCore(gradient);
  54446. case EasingFunction.EASINGMODE_EASEOUT:
  54447. return (1 - this.easeInCore(1 - gradient));
  54448. }
  54449. if (gradient >= 0.5) {
  54450. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  54451. }
  54452. return (this.easeInCore(gradient * 2) * 0.5);
  54453. };
  54454. /**
  54455. * Interpolation follows the mathematical formula associated with the easing function.
  54456. */
  54457. EasingFunction.EASINGMODE_EASEIN = 0;
  54458. /**
  54459. * Interpolation follows 100% interpolation minus the output of the formula associated with the easing function.
  54460. */
  54461. EasingFunction.EASINGMODE_EASEOUT = 1;
  54462. /**
  54463. * Interpolation uses EaseIn for the first half of the animation and EaseOut for the second half.
  54464. */
  54465. EasingFunction.EASINGMODE_EASEINOUT = 2;
  54466. return EasingFunction;
  54467. }());
  54468. BABYLON.EasingFunction = EasingFunction;
  54469. /**
  54470. * Easing function with a circle shape (see link below).
  54471. * @see https://easings.net/#easeInCirc
  54472. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54473. */
  54474. var CircleEase = /** @class */ (function (_super) {
  54475. __extends(CircleEase, _super);
  54476. function CircleEase() {
  54477. return _super !== null && _super.apply(this, arguments) || this;
  54478. }
  54479. /** @hidden */
  54480. CircleEase.prototype.easeInCore = function (gradient) {
  54481. gradient = Math.max(0, Math.min(1, gradient));
  54482. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  54483. };
  54484. return CircleEase;
  54485. }(EasingFunction));
  54486. BABYLON.CircleEase = CircleEase;
  54487. /**
  54488. * Easing function with a ease back shape (see link below).
  54489. * @see https://easings.net/#easeInBack
  54490. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54491. */
  54492. var BackEase = /** @class */ (function (_super) {
  54493. __extends(BackEase, _super);
  54494. /**
  54495. * Instantiates a back ease easing
  54496. * @see https://easings.net/#easeInBack
  54497. * @param amplitude Defines the amplitude of the function
  54498. */
  54499. function BackEase(
  54500. /** Defines the amplitude of the function */
  54501. amplitude) {
  54502. if (amplitude === void 0) { amplitude = 1; }
  54503. var _this = _super.call(this) || this;
  54504. _this.amplitude = amplitude;
  54505. return _this;
  54506. }
  54507. /** @hidden */
  54508. BackEase.prototype.easeInCore = function (gradient) {
  54509. var num = Math.max(0, this.amplitude);
  54510. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  54511. };
  54512. return BackEase;
  54513. }(EasingFunction));
  54514. BABYLON.BackEase = BackEase;
  54515. /**
  54516. * Easing function with a bouncing shape (see link below).
  54517. * @see https://easings.net/#easeInBounce
  54518. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54519. */
  54520. var BounceEase = /** @class */ (function (_super) {
  54521. __extends(BounceEase, _super);
  54522. /**
  54523. * Instantiates a bounce easing
  54524. * @see https://easings.net/#easeInBounce
  54525. * @param bounces Defines the number of bounces
  54526. * @param bounciness Defines the amplitude of the bounce
  54527. */
  54528. function BounceEase(
  54529. /** Defines the number of bounces */
  54530. bounces,
  54531. /** Defines the amplitude of the bounce */
  54532. bounciness) {
  54533. if (bounces === void 0) { bounces = 3; }
  54534. if (bounciness === void 0) { bounciness = 2; }
  54535. var _this = _super.call(this) || this;
  54536. _this.bounces = bounces;
  54537. _this.bounciness = bounciness;
  54538. return _this;
  54539. }
  54540. /** @hidden */
  54541. BounceEase.prototype.easeInCore = function (gradient) {
  54542. var y = Math.max(0.0, this.bounces);
  54543. var bounciness = this.bounciness;
  54544. if (bounciness <= 1.0) {
  54545. bounciness = 1.001;
  54546. }
  54547. var num9 = Math.pow(bounciness, y);
  54548. var num5 = 1.0 - bounciness;
  54549. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  54550. var num15 = gradient * num4;
  54551. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  54552. var num3 = Math.floor(num65);
  54553. var num13 = num3 + 1.0;
  54554. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  54555. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  54556. var num7 = (num8 + num12) * 0.5;
  54557. var num6 = gradient - num7;
  54558. var num2 = num7 - num8;
  54559. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  54560. };
  54561. return BounceEase;
  54562. }(EasingFunction));
  54563. BABYLON.BounceEase = BounceEase;
  54564. /**
  54565. * Easing function with a power of 3 shape (see link below).
  54566. * @see https://easings.net/#easeInCubic
  54567. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54568. */
  54569. var CubicEase = /** @class */ (function (_super) {
  54570. __extends(CubicEase, _super);
  54571. function CubicEase() {
  54572. return _super !== null && _super.apply(this, arguments) || this;
  54573. }
  54574. /** @hidden */
  54575. CubicEase.prototype.easeInCore = function (gradient) {
  54576. return (gradient * gradient * gradient);
  54577. };
  54578. return CubicEase;
  54579. }(EasingFunction));
  54580. BABYLON.CubicEase = CubicEase;
  54581. /**
  54582. * Easing function with an elastic shape (see link below).
  54583. * @see https://easings.net/#easeInElastic
  54584. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54585. */
  54586. var ElasticEase = /** @class */ (function (_super) {
  54587. __extends(ElasticEase, _super);
  54588. /**
  54589. * Instantiates an elastic easing function
  54590. * @see https://easings.net/#easeInElastic
  54591. * @param oscillations Defines the number of oscillations
  54592. * @param springiness Defines the amplitude of the oscillations
  54593. */
  54594. function ElasticEase(
  54595. /** Defines the number of oscillations*/
  54596. oscillations,
  54597. /** Defines the amplitude of the oscillations*/
  54598. springiness) {
  54599. if (oscillations === void 0) { oscillations = 3; }
  54600. if (springiness === void 0) { springiness = 3; }
  54601. var _this = _super.call(this) || this;
  54602. _this.oscillations = oscillations;
  54603. _this.springiness = springiness;
  54604. return _this;
  54605. }
  54606. /** @hidden */
  54607. ElasticEase.prototype.easeInCore = function (gradient) {
  54608. var num2;
  54609. var num3 = Math.max(0.0, this.oscillations);
  54610. var num = Math.max(0.0, this.springiness);
  54611. if (num == 0) {
  54612. num2 = gradient;
  54613. }
  54614. else {
  54615. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  54616. }
  54617. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  54618. };
  54619. return ElasticEase;
  54620. }(EasingFunction));
  54621. BABYLON.ElasticEase = ElasticEase;
  54622. /**
  54623. * Easing function with an exponential shape (see link below).
  54624. * @see https://easings.net/#easeInExpo
  54625. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54626. */
  54627. var ExponentialEase = /** @class */ (function (_super) {
  54628. __extends(ExponentialEase, _super);
  54629. /**
  54630. * Instantiates an exponential easing function
  54631. * @see https://easings.net/#easeInExpo
  54632. * @param exponent Defines the exponent of the function
  54633. */
  54634. function ExponentialEase(
  54635. /** Defines the exponent of the function */
  54636. exponent) {
  54637. if (exponent === void 0) { exponent = 2; }
  54638. var _this = _super.call(this) || this;
  54639. _this.exponent = exponent;
  54640. return _this;
  54641. }
  54642. /** @hidden */
  54643. ExponentialEase.prototype.easeInCore = function (gradient) {
  54644. if (this.exponent <= 0) {
  54645. return gradient;
  54646. }
  54647. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  54648. };
  54649. return ExponentialEase;
  54650. }(EasingFunction));
  54651. BABYLON.ExponentialEase = ExponentialEase;
  54652. /**
  54653. * Easing function with a power shape (see link below).
  54654. * @see https://easings.net/#easeInQuad
  54655. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54656. */
  54657. var PowerEase = /** @class */ (function (_super) {
  54658. __extends(PowerEase, _super);
  54659. /**
  54660. * Instantiates an power base easing function
  54661. * @see https://easings.net/#easeInQuad
  54662. * @param power Defines the power of the function
  54663. */
  54664. function PowerEase(
  54665. /** Defines the power of the function */
  54666. power) {
  54667. if (power === void 0) { power = 2; }
  54668. var _this = _super.call(this) || this;
  54669. _this.power = power;
  54670. return _this;
  54671. }
  54672. /** @hidden */
  54673. PowerEase.prototype.easeInCore = function (gradient) {
  54674. var y = Math.max(0.0, this.power);
  54675. return Math.pow(gradient, y);
  54676. };
  54677. return PowerEase;
  54678. }(EasingFunction));
  54679. BABYLON.PowerEase = PowerEase;
  54680. /**
  54681. * Easing function with a power of 2 shape (see link below).
  54682. * @see https://easings.net/#easeInQuad
  54683. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54684. */
  54685. var QuadraticEase = /** @class */ (function (_super) {
  54686. __extends(QuadraticEase, _super);
  54687. function QuadraticEase() {
  54688. return _super !== null && _super.apply(this, arguments) || this;
  54689. }
  54690. /** @hidden */
  54691. QuadraticEase.prototype.easeInCore = function (gradient) {
  54692. return (gradient * gradient);
  54693. };
  54694. return QuadraticEase;
  54695. }(EasingFunction));
  54696. BABYLON.QuadraticEase = QuadraticEase;
  54697. /**
  54698. * Easing function with a power of 4 shape (see link below).
  54699. * @see https://easings.net/#easeInQuart
  54700. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54701. */
  54702. var QuarticEase = /** @class */ (function (_super) {
  54703. __extends(QuarticEase, _super);
  54704. function QuarticEase() {
  54705. return _super !== null && _super.apply(this, arguments) || this;
  54706. }
  54707. /** @hidden */
  54708. QuarticEase.prototype.easeInCore = function (gradient) {
  54709. return (gradient * gradient * gradient * gradient);
  54710. };
  54711. return QuarticEase;
  54712. }(EasingFunction));
  54713. BABYLON.QuarticEase = QuarticEase;
  54714. /**
  54715. * Easing function with a power of 5 shape (see link below).
  54716. * @see https://easings.net/#easeInQuint
  54717. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54718. */
  54719. var QuinticEase = /** @class */ (function (_super) {
  54720. __extends(QuinticEase, _super);
  54721. function QuinticEase() {
  54722. return _super !== null && _super.apply(this, arguments) || this;
  54723. }
  54724. /** @hidden */
  54725. QuinticEase.prototype.easeInCore = function (gradient) {
  54726. return (gradient * gradient * gradient * gradient * gradient);
  54727. };
  54728. return QuinticEase;
  54729. }(EasingFunction));
  54730. BABYLON.QuinticEase = QuinticEase;
  54731. /**
  54732. * Easing function with a sin shape (see link below).
  54733. * @see https://easings.net/#easeInSine
  54734. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54735. */
  54736. var SineEase = /** @class */ (function (_super) {
  54737. __extends(SineEase, _super);
  54738. function SineEase() {
  54739. return _super !== null && _super.apply(this, arguments) || this;
  54740. }
  54741. /** @hidden */
  54742. SineEase.prototype.easeInCore = function (gradient) {
  54743. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  54744. };
  54745. return SineEase;
  54746. }(EasingFunction));
  54747. BABYLON.SineEase = SineEase;
  54748. /**
  54749. * Easing function with a bezier shape (see link below).
  54750. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  54751. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54752. */
  54753. var BezierCurveEase = /** @class */ (function (_super) {
  54754. __extends(BezierCurveEase, _super);
  54755. /**
  54756. * Instantiates a bezier function
  54757. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  54758. * @param x1 Defines the x component of the start tangent in the bezier curve
  54759. * @param y1 Defines the y component of the start tangent in the bezier curve
  54760. * @param x2 Defines the x component of the end tangent in the bezier curve
  54761. * @param y2 Defines the y component of the end tangent in the bezier curve
  54762. */
  54763. function BezierCurveEase(
  54764. /** Defines the x component of the start tangent in the bezier curve */
  54765. x1,
  54766. /** Defines the y component of the start tangent in the bezier curve */
  54767. y1,
  54768. /** Defines the x component of the end tangent in the bezier curve */
  54769. x2,
  54770. /** Defines the y component of the end tangent in the bezier curve */
  54771. y2) {
  54772. if (x1 === void 0) { x1 = 0; }
  54773. if (y1 === void 0) { y1 = 0; }
  54774. if (x2 === void 0) { x2 = 1; }
  54775. if (y2 === void 0) { y2 = 1; }
  54776. var _this = _super.call(this) || this;
  54777. _this.x1 = x1;
  54778. _this.y1 = y1;
  54779. _this.x2 = x2;
  54780. _this.y2 = y2;
  54781. return _this;
  54782. }
  54783. /** @hidden */
  54784. BezierCurveEase.prototype.easeInCore = function (gradient) {
  54785. return BABYLON.BezierCurve.Interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  54786. };
  54787. return BezierCurveEase;
  54788. }(EasingFunction));
  54789. BABYLON.BezierCurveEase = BezierCurveEase;
  54790. })(BABYLON || (BABYLON = {}));
  54791. //# sourceMappingURL=babylon.easing.js.map
  54792. var BABYLON;
  54793. (function (BABYLON) {
  54794. /**
  54795. * A Condition applied to an Action
  54796. */
  54797. var Condition = /** @class */ (function () {
  54798. /**
  54799. * Creates a new Condition
  54800. * @param actionManager the manager of the action the condition is applied to
  54801. */
  54802. function Condition(actionManager) {
  54803. this._actionManager = actionManager;
  54804. }
  54805. /**
  54806. * Check if the current condition is valid
  54807. * @returns a boolean
  54808. */
  54809. Condition.prototype.isValid = function () {
  54810. return true;
  54811. };
  54812. /**
  54813. * Internal only
  54814. * @hidden
  54815. */
  54816. Condition.prototype._getProperty = function (propertyPath) {
  54817. return this._actionManager._getProperty(propertyPath);
  54818. };
  54819. /**
  54820. * Internal only
  54821. * @hidden
  54822. */
  54823. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  54824. return this._actionManager._getEffectiveTarget(target, propertyPath);
  54825. };
  54826. /**
  54827. * Serialize placeholder for child classes
  54828. * @returns the serialized object
  54829. */
  54830. Condition.prototype.serialize = function () {
  54831. };
  54832. /**
  54833. * Internal only
  54834. * @hidden
  54835. */
  54836. Condition.prototype._serialize = function (serializedCondition) {
  54837. return {
  54838. type: 2,
  54839. children: [],
  54840. name: serializedCondition.name,
  54841. properties: serializedCondition.properties
  54842. };
  54843. };
  54844. return Condition;
  54845. }());
  54846. BABYLON.Condition = Condition;
  54847. /**
  54848. * Defines specific conditional operators as extensions of Condition
  54849. */
  54850. var ValueCondition = /** @class */ (function (_super) {
  54851. __extends(ValueCondition, _super);
  54852. /**
  54853. * Creates a new ValueCondition
  54854. * @param actionManager manager for the action the condition applies to
  54855. * @param target for the action
  54856. * @param propertyPath path to specify the property of the target the conditional operator uses
  54857. * @param value the value compared by the conditional operator against the current value of the property
  54858. * @param operator the conditional operator, default ValueCondition.IsEqual
  54859. */
  54860. function ValueCondition(actionManager, target,
  54861. /** path to specify the property of the target the conditional operator uses */
  54862. propertyPath,
  54863. /** the value compared by the conditional operator against the current value of the property */
  54864. value,
  54865. /** the conditional operator, default ValueCondition.IsEqual */
  54866. operator) {
  54867. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  54868. var _this = _super.call(this, actionManager) || this;
  54869. _this.propertyPath = propertyPath;
  54870. _this.value = value;
  54871. _this.operator = operator;
  54872. _this._target = target;
  54873. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  54874. _this._property = _this._getProperty(_this.propertyPath);
  54875. return _this;
  54876. }
  54877. Object.defineProperty(ValueCondition, "IsEqual", {
  54878. /**
  54879. * returns the number for IsEqual
  54880. */
  54881. get: function () {
  54882. return ValueCondition._IsEqual;
  54883. },
  54884. enumerable: true,
  54885. configurable: true
  54886. });
  54887. Object.defineProperty(ValueCondition, "IsDifferent", {
  54888. /**
  54889. * Returns the number for IsDifferent
  54890. */
  54891. get: function () {
  54892. return ValueCondition._IsDifferent;
  54893. },
  54894. enumerable: true,
  54895. configurable: true
  54896. });
  54897. Object.defineProperty(ValueCondition, "IsGreater", {
  54898. /**
  54899. * Returns the number for IsGreater
  54900. */
  54901. get: function () {
  54902. return ValueCondition._IsGreater;
  54903. },
  54904. enumerable: true,
  54905. configurable: true
  54906. });
  54907. Object.defineProperty(ValueCondition, "IsLesser", {
  54908. /**
  54909. * Returns the number for IsLesser
  54910. */
  54911. get: function () {
  54912. return ValueCondition._IsLesser;
  54913. },
  54914. enumerable: true,
  54915. configurable: true
  54916. });
  54917. /**
  54918. * Compares the given value with the property value for the specified conditional operator
  54919. * @returns the result of the comparison
  54920. */
  54921. ValueCondition.prototype.isValid = function () {
  54922. switch (this.operator) {
  54923. case ValueCondition.IsGreater:
  54924. return this._effectiveTarget[this._property] > this.value;
  54925. case ValueCondition.IsLesser:
  54926. return this._effectiveTarget[this._property] < this.value;
  54927. case ValueCondition.IsEqual:
  54928. case ValueCondition.IsDifferent:
  54929. var check;
  54930. if (this.value.equals) {
  54931. check = this.value.equals(this._effectiveTarget[this._property]);
  54932. }
  54933. else {
  54934. check = this.value === this._effectiveTarget[this._property];
  54935. }
  54936. return this.operator === ValueCondition.IsEqual ? check : !check;
  54937. }
  54938. return false;
  54939. };
  54940. /**
  54941. * Serialize the ValueCondition into a JSON compatible object
  54942. * @returns serialization object
  54943. */
  54944. ValueCondition.prototype.serialize = function () {
  54945. return this._serialize({
  54946. name: "ValueCondition",
  54947. properties: [
  54948. BABYLON.Action._GetTargetProperty(this._target),
  54949. { name: "propertyPath", value: this.propertyPath },
  54950. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  54951. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  54952. ]
  54953. });
  54954. };
  54955. /**
  54956. * Gets the name of the conditional operator for the ValueCondition
  54957. * @param operator the conditional operator
  54958. * @returns the name
  54959. */
  54960. ValueCondition.GetOperatorName = function (operator) {
  54961. switch (operator) {
  54962. case ValueCondition._IsEqual: return "IsEqual";
  54963. case ValueCondition._IsDifferent: return "IsDifferent";
  54964. case ValueCondition._IsGreater: return "IsGreater";
  54965. case ValueCondition._IsLesser: return "IsLesser";
  54966. default: return "";
  54967. }
  54968. };
  54969. /**
  54970. * Internal only
  54971. * @hidden
  54972. */
  54973. ValueCondition._IsEqual = 0;
  54974. /**
  54975. * Internal only
  54976. * @hidden
  54977. */
  54978. ValueCondition._IsDifferent = 1;
  54979. /**
  54980. * Internal only
  54981. * @hidden
  54982. */
  54983. ValueCondition._IsGreater = 2;
  54984. /**
  54985. * Internal only
  54986. * @hidden
  54987. */
  54988. ValueCondition._IsLesser = 3;
  54989. return ValueCondition;
  54990. }(Condition));
  54991. BABYLON.ValueCondition = ValueCondition;
  54992. /**
  54993. * Defines a predicate condition as an extension of Condition
  54994. */
  54995. var PredicateCondition = /** @class */ (function (_super) {
  54996. __extends(PredicateCondition, _super);
  54997. /**
  54998. * Creates a new PredicateCondition
  54999. * @param actionManager manager for the action the condition applies to
  55000. * @param predicate defines the predicate function used to validate the condition
  55001. */
  55002. function PredicateCondition(actionManager,
  55003. /** defines the predicate function used to validate the condition */
  55004. predicate) {
  55005. var _this = _super.call(this, actionManager) || this;
  55006. _this.predicate = predicate;
  55007. return _this;
  55008. }
  55009. /**
  55010. * @returns the validity of the predicate condition
  55011. */
  55012. PredicateCondition.prototype.isValid = function () {
  55013. return this.predicate();
  55014. };
  55015. return PredicateCondition;
  55016. }(Condition));
  55017. BABYLON.PredicateCondition = PredicateCondition;
  55018. /**
  55019. * Defines a state condition as an extension of Condition
  55020. */
  55021. var StateCondition = /** @class */ (function (_super) {
  55022. __extends(StateCondition, _super);
  55023. /**
  55024. * Creates a new StateCondition
  55025. * @param actionManager manager for the action the condition applies to
  55026. * @param target of the condition
  55027. * @param value to compare with target state
  55028. */
  55029. function StateCondition(actionManager, target,
  55030. /** Value to compare with target state */
  55031. value) {
  55032. var _this = _super.call(this, actionManager) || this;
  55033. _this.value = value;
  55034. _this._target = target;
  55035. return _this;
  55036. }
  55037. /**
  55038. * Gets a boolean indicating if the current condition is met
  55039. * @returns the validity of the state
  55040. */
  55041. StateCondition.prototype.isValid = function () {
  55042. return this._target.state === this.value;
  55043. };
  55044. /**
  55045. * Serialize the StateCondition into a JSON compatible object
  55046. * @returns serialization object
  55047. */
  55048. StateCondition.prototype.serialize = function () {
  55049. return this._serialize({
  55050. name: "StateCondition",
  55051. properties: [
  55052. BABYLON.Action._GetTargetProperty(this._target),
  55053. { name: "value", value: this.value }
  55054. ]
  55055. });
  55056. };
  55057. return StateCondition;
  55058. }(Condition));
  55059. BABYLON.StateCondition = StateCondition;
  55060. })(BABYLON || (BABYLON = {}));
  55061. //# sourceMappingURL=babylon.condition.js.map
  55062. var BABYLON;
  55063. (function (BABYLON) {
  55064. /**
  55065. * The action to be carried out following a trigger
  55066. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  55067. */
  55068. var Action = /** @class */ (function () {
  55069. /**
  55070. * Creates a new Action
  55071. * @param triggerOptions the trigger, with or without parameters, for the action
  55072. * @param condition an optional determinant of action
  55073. */
  55074. function Action(
  55075. /** the trigger, with or without parameters, for the action */
  55076. triggerOptions, condition) {
  55077. this.triggerOptions = triggerOptions;
  55078. /**
  55079. * An event triggered prior to action being executed.
  55080. */
  55081. this.onBeforeExecuteObservable = new BABYLON.Observable();
  55082. if (triggerOptions.parameter) {
  55083. this.trigger = triggerOptions.trigger;
  55084. this._triggerParameter = triggerOptions.parameter;
  55085. }
  55086. else if (triggerOptions.trigger) {
  55087. this.trigger = triggerOptions.trigger;
  55088. }
  55089. else {
  55090. this.trigger = triggerOptions;
  55091. }
  55092. this._nextActiveAction = this;
  55093. this._condition = condition;
  55094. }
  55095. /**
  55096. * Internal only
  55097. * @hidden
  55098. */
  55099. Action.prototype._prepare = function () {
  55100. };
  55101. /**
  55102. * Gets the trigger parameters
  55103. * @returns the trigger parameters
  55104. */
  55105. Action.prototype.getTriggerParameter = function () {
  55106. return this._triggerParameter;
  55107. };
  55108. /**
  55109. * Internal only - executes current action event
  55110. * @hidden
  55111. */
  55112. Action.prototype._executeCurrent = function (evt) {
  55113. if (this._nextActiveAction._condition) {
  55114. var condition = this._nextActiveAction._condition;
  55115. var currentRenderId = this._actionManager.getScene().getRenderId();
  55116. // We cache the current evaluation for the current frame
  55117. if (condition._evaluationId === currentRenderId) {
  55118. if (!condition._currentResult) {
  55119. return;
  55120. }
  55121. }
  55122. else {
  55123. condition._evaluationId = currentRenderId;
  55124. if (!condition.isValid()) {
  55125. condition._currentResult = false;
  55126. return;
  55127. }
  55128. condition._currentResult = true;
  55129. }
  55130. }
  55131. this.onBeforeExecuteObservable.notifyObservers(this);
  55132. this._nextActiveAction.execute(evt);
  55133. this.skipToNextActiveAction();
  55134. };
  55135. /**
  55136. * Execute placeholder for child classes
  55137. * @param evt optional action event
  55138. */
  55139. Action.prototype.execute = function (evt) {
  55140. };
  55141. /**
  55142. * Skips to next active action
  55143. */
  55144. Action.prototype.skipToNextActiveAction = function () {
  55145. if (this._nextActiveAction._child) {
  55146. if (!this._nextActiveAction._child._actionManager) {
  55147. this._nextActiveAction._child._actionManager = this._actionManager;
  55148. }
  55149. this._nextActiveAction = this._nextActiveAction._child;
  55150. }
  55151. else {
  55152. this._nextActiveAction = this;
  55153. }
  55154. };
  55155. /**
  55156. * Adds action to chain of actions, may be a DoNothingAction
  55157. * @param action defines the next action to execute
  55158. * @returns The action passed in
  55159. * @see https://www.babylonjs-playground.com/#1T30HR#0
  55160. */
  55161. Action.prototype.then = function (action) {
  55162. this._child = action;
  55163. action._actionManager = this._actionManager;
  55164. action._prepare();
  55165. return action;
  55166. };
  55167. /**
  55168. * Internal only
  55169. * @hidden
  55170. */
  55171. Action.prototype._getProperty = function (propertyPath) {
  55172. return this._actionManager._getProperty(propertyPath);
  55173. };
  55174. /**
  55175. * Internal only
  55176. * @hidden
  55177. */
  55178. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  55179. return this._actionManager._getEffectiveTarget(target, propertyPath);
  55180. };
  55181. /**
  55182. * Serialize placeholder for child classes
  55183. * @param parent of child
  55184. * @returns the serialized object
  55185. */
  55186. Action.prototype.serialize = function (parent) {
  55187. };
  55188. /**
  55189. * Internal only called by serialize
  55190. * @hidden
  55191. */
  55192. Action.prototype._serialize = function (serializedAction, parent) {
  55193. var serializationObject = {
  55194. type: 1,
  55195. children: [],
  55196. name: serializedAction.name,
  55197. properties: serializedAction.properties || []
  55198. };
  55199. // Serialize child
  55200. if (this._child) {
  55201. this._child.serialize(serializationObject);
  55202. }
  55203. // Check if "this" has a condition
  55204. if (this._condition) {
  55205. var serializedCondition = this._condition.serialize();
  55206. serializedCondition.children.push(serializationObject);
  55207. if (parent) {
  55208. parent.children.push(serializedCondition);
  55209. }
  55210. return serializedCondition;
  55211. }
  55212. if (parent) {
  55213. parent.children.push(serializationObject);
  55214. }
  55215. return serializationObject;
  55216. };
  55217. /**
  55218. * Internal only
  55219. * @hidden
  55220. */
  55221. Action._SerializeValueAsString = function (value) {
  55222. if (typeof value === "number") {
  55223. return value.toString();
  55224. }
  55225. if (typeof value === "boolean") {
  55226. return value ? "true" : "false";
  55227. }
  55228. if (value instanceof BABYLON.Vector2) {
  55229. return value.x + ", " + value.y;
  55230. }
  55231. if (value instanceof BABYLON.Vector3) {
  55232. return value.x + ", " + value.y + ", " + value.z;
  55233. }
  55234. if (value instanceof BABYLON.Color3) {
  55235. return value.r + ", " + value.g + ", " + value.b;
  55236. }
  55237. if (value instanceof BABYLON.Color4) {
  55238. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  55239. }
  55240. return value; // string
  55241. };
  55242. /**
  55243. * Internal only
  55244. * @hidden
  55245. */
  55246. Action._GetTargetProperty = function (target) {
  55247. return {
  55248. name: "target",
  55249. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  55250. : target instanceof BABYLON.Light ? "LightProperties"
  55251. : target instanceof BABYLON.Camera ? "CameraProperties"
  55252. : "SceneProperties",
  55253. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  55254. };
  55255. };
  55256. return Action;
  55257. }());
  55258. BABYLON.Action = Action;
  55259. })(BABYLON || (BABYLON = {}));
  55260. //# sourceMappingURL=babylon.action.js.map
  55261. var BABYLON;
  55262. (function (BABYLON) {
  55263. /**
  55264. * ActionEvent is the event being sent when an action is triggered.
  55265. */
  55266. var ActionEvent = /** @class */ (function () {
  55267. /**
  55268. * Creates a new ActionEvent
  55269. * @param source The mesh or sprite that triggered the action
  55270. * @param pointerX The X mouse cursor position at the time of the event
  55271. * @param pointerY The Y mouse cursor position at the time of the event
  55272. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  55273. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  55274. * @param additionalData additional data for the event
  55275. */
  55276. function ActionEvent(
  55277. /** The mesh or sprite that triggered the action */
  55278. source,
  55279. /** The X mouse cursor position at the time of the event */
  55280. pointerX,
  55281. /** The Y mouse cursor position at the time of the event */
  55282. pointerY,
  55283. /** The mesh that is currently pointed at (can be null) */
  55284. meshUnderPointer,
  55285. /** the original (browser) event that triggered the ActionEvent */
  55286. sourceEvent,
  55287. /** additional data for the event */
  55288. additionalData) {
  55289. this.source = source;
  55290. this.pointerX = pointerX;
  55291. this.pointerY = pointerY;
  55292. this.meshUnderPointer = meshUnderPointer;
  55293. this.sourceEvent = sourceEvent;
  55294. this.additionalData = additionalData;
  55295. }
  55296. /**
  55297. * Helper function to auto-create an ActionEvent from a source mesh.
  55298. * @param source The source mesh that triggered the event
  55299. * @param evt The original (browser) event
  55300. * @param additionalData additional data for the event
  55301. * @returns the new ActionEvent
  55302. */
  55303. ActionEvent.CreateNew = function (source, evt, additionalData) {
  55304. var scene = source.getScene();
  55305. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  55306. };
  55307. /**
  55308. * Helper function to auto-create an ActionEvent from a source sprite
  55309. * @param source The source sprite that triggered the event
  55310. * @param scene Scene associated with the sprite
  55311. * @param evt The original (browser) event
  55312. * @param additionalData additional data for the event
  55313. * @returns the new ActionEvent
  55314. */
  55315. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  55316. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  55317. };
  55318. /**
  55319. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  55320. * @param scene the scene where the event occurred
  55321. * @param evt The original (browser) event
  55322. * @returns the new ActionEvent
  55323. */
  55324. ActionEvent.CreateNewFromScene = function (scene, evt) {
  55325. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  55326. };
  55327. /**
  55328. * Helper function to auto-create an ActionEvent from a primitive
  55329. * @param prim defines the target primitive
  55330. * @param pointerPos defines the pointer position
  55331. * @param evt The original (browser) event
  55332. * @param additionalData additional data for the event
  55333. * @returns the new ActionEvent
  55334. */
  55335. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  55336. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  55337. };
  55338. return ActionEvent;
  55339. }());
  55340. BABYLON.ActionEvent = ActionEvent;
  55341. /**
  55342. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  55343. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  55344. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55345. */
  55346. var ActionManager = /** @class */ (function () {
  55347. /**
  55348. * Creates a new action manager
  55349. * @param scene defines the hosting scene
  55350. */
  55351. function ActionManager(scene) {
  55352. // Members
  55353. /** Gets the list of actions */
  55354. this.actions = new Array();
  55355. /** Gets the cursor to use when hovering items */
  55356. this.hoverCursor = '';
  55357. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55358. scene.actionManagers.push(this);
  55359. }
  55360. // Methods
  55361. /**
  55362. * Releases all associated resources
  55363. */
  55364. ActionManager.prototype.dispose = function () {
  55365. var index = this._scene.actionManagers.indexOf(this);
  55366. for (var i = 0; i < this.actions.length; i++) {
  55367. var action = this.actions[i];
  55368. ActionManager.Triggers[action.trigger]--;
  55369. if (ActionManager.Triggers[action.trigger] === 0) {
  55370. delete ActionManager.Triggers[action.trigger];
  55371. }
  55372. }
  55373. if (index > -1) {
  55374. this._scene.actionManagers.splice(index, 1);
  55375. }
  55376. };
  55377. /**
  55378. * Gets hosting scene
  55379. * @returns the hosting scene
  55380. */
  55381. ActionManager.prototype.getScene = function () {
  55382. return this._scene;
  55383. };
  55384. /**
  55385. * Does this action manager handles actions of any of the given triggers
  55386. * @param triggers defines the triggers to be tested
  55387. * @return a boolean indicating whether one (or more) of the triggers is handled
  55388. */
  55389. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  55390. for (var index = 0; index < this.actions.length; index++) {
  55391. var action = this.actions[index];
  55392. if (triggers.indexOf(action.trigger) > -1) {
  55393. return true;
  55394. }
  55395. }
  55396. return false;
  55397. };
  55398. /**
  55399. * Does this action manager handles actions of any of the given triggers. This function takes two arguments for
  55400. * speed.
  55401. * @param triggerA defines the trigger to be tested
  55402. * @param triggerB defines the trigger to be tested
  55403. * @return a boolean indicating whether one (or more) of the triggers is handled
  55404. */
  55405. ActionManager.prototype.hasSpecificTriggers2 = function (triggerA, triggerB) {
  55406. for (var index = 0; index < this.actions.length; index++) {
  55407. var action = this.actions[index];
  55408. if (triggerA == action.trigger || triggerB == action.trigger) {
  55409. return true;
  55410. }
  55411. }
  55412. return false;
  55413. };
  55414. /**
  55415. * Does this action manager handles actions of a given trigger
  55416. * @param trigger defines the trigger to be tested
  55417. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  55418. * @return whether the trigger is handled
  55419. */
  55420. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  55421. for (var index = 0; index < this.actions.length; index++) {
  55422. var action = this.actions[index];
  55423. if (action.trigger === trigger) {
  55424. if (parameterPredicate) {
  55425. if (parameterPredicate(action.getTriggerParameter())) {
  55426. return true;
  55427. }
  55428. }
  55429. else {
  55430. return true;
  55431. }
  55432. }
  55433. }
  55434. return false;
  55435. };
  55436. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  55437. /**
  55438. * Does this action manager has pointer triggers
  55439. */
  55440. get: function () {
  55441. for (var index = 0; index < this.actions.length; index++) {
  55442. var action = this.actions[index];
  55443. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPointerOutTrigger) {
  55444. return true;
  55445. }
  55446. }
  55447. return false;
  55448. },
  55449. enumerable: true,
  55450. configurable: true
  55451. });
  55452. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  55453. /**
  55454. * Does this action manager has pick triggers
  55455. */
  55456. get: function () {
  55457. for (var index = 0; index < this.actions.length; index++) {
  55458. var action = this.actions[index];
  55459. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPickUpTrigger) {
  55460. return true;
  55461. }
  55462. }
  55463. return false;
  55464. },
  55465. enumerable: true,
  55466. configurable: true
  55467. });
  55468. Object.defineProperty(ActionManager, "HasTriggers", {
  55469. /**
  55470. * Does exist one action manager with at least one trigger
  55471. **/
  55472. get: function () {
  55473. for (var t in ActionManager.Triggers) {
  55474. if (ActionManager.Triggers.hasOwnProperty(t)) {
  55475. return true;
  55476. }
  55477. }
  55478. return false;
  55479. },
  55480. enumerable: true,
  55481. configurable: true
  55482. });
  55483. Object.defineProperty(ActionManager, "HasPickTriggers", {
  55484. /**
  55485. * Does exist one action manager with at least one pick trigger
  55486. **/
  55487. get: function () {
  55488. for (var t in ActionManager.Triggers) {
  55489. if (ActionManager.Triggers.hasOwnProperty(t)) {
  55490. var t_int = parseInt(t);
  55491. if (t_int >= ActionManager.OnPickTrigger && t_int <= ActionManager.OnPickUpTrigger) {
  55492. return true;
  55493. }
  55494. }
  55495. }
  55496. return false;
  55497. },
  55498. enumerable: true,
  55499. configurable: true
  55500. });
  55501. /**
  55502. * Does exist one action manager that handles actions of a given trigger
  55503. * @param trigger defines the trigger to be tested
  55504. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  55505. **/
  55506. ActionManager.HasSpecificTrigger = function (trigger) {
  55507. for (var t in ActionManager.Triggers) {
  55508. if (ActionManager.Triggers.hasOwnProperty(t)) {
  55509. var t_int = parseInt(t);
  55510. if (t_int === trigger) {
  55511. return true;
  55512. }
  55513. }
  55514. }
  55515. return false;
  55516. };
  55517. /**
  55518. * Registers an action to this action manager
  55519. * @param action defines the action to be registered
  55520. * @return the action amended (prepared) after registration
  55521. */
  55522. ActionManager.prototype.registerAction = function (action) {
  55523. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  55524. if (this.getScene().actionManager !== this) {
  55525. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  55526. return null;
  55527. }
  55528. }
  55529. this.actions.push(action);
  55530. if (ActionManager.Triggers[action.trigger]) {
  55531. ActionManager.Triggers[action.trigger]++;
  55532. }
  55533. else {
  55534. ActionManager.Triggers[action.trigger] = 1;
  55535. }
  55536. action._actionManager = this;
  55537. action._prepare();
  55538. return action;
  55539. };
  55540. /**
  55541. * Unregisters an action to this action manager
  55542. * @param action defines the action to be unregistered
  55543. * @return a boolean indicating whether the action has been unregistered
  55544. */
  55545. ActionManager.prototype.unregisterAction = function (action) {
  55546. var index = this.actions.indexOf(action);
  55547. if (index !== -1) {
  55548. this.actions.splice(index, 1);
  55549. ActionManager.Triggers[action.trigger] -= 1;
  55550. if (ActionManager.Triggers[action.trigger] === 0) {
  55551. delete ActionManager.Triggers[action.trigger];
  55552. }
  55553. delete action._actionManager;
  55554. return true;
  55555. }
  55556. return false;
  55557. };
  55558. /**
  55559. * Process a specific trigger
  55560. * @param trigger defines the trigger to process
  55561. * @param evt defines the event details to be processed
  55562. */
  55563. ActionManager.prototype.processTrigger = function (trigger, evt) {
  55564. for (var index = 0; index < this.actions.length; index++) {
  55565. var action = this.actions[index];
  55566. if (action.trigger === trigger) {
  55567. if (evt) {
  55568. if (trigger === ActionManager.OnKeyUpTrigger
  55569. || trigger === ActionManager.OnKeyDownTrigger) {
  55570. var parameter = action.getTriggerParameter();
  55571. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  55572. if (!parameter.toLowerCase) {
  55573. continue;
  55574. }
  55575. var lowerCase = parameter.toLowerCase();
  55576. if (lowerCase !== evt.sourceEvent.key) {
  55577. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  55578. var actualkey = String.fromCharCode(unicode).toLowerCase();
  55579. if (actualkey !== lowerCase) {
  55580. continue;
  55581. }
  55582. }
  55583. }
  55584. }
  55585. }
  55586. action._executeCurrent(evt);
  55587. }
  55588. }
  55589. };
  55590. /** @hidden */
  55591. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  55592. var properties = propertyPath.split(".");
  55593. for (var index = 0; index < properties.length - 1; index++) {
  55594. target = target[properties[index]];
  55595. }
  55596. return target;
  55597. };
  55598. /** @hidden */
  55599. ActionManager.prototype._getProperty = function (propertyPath) {
  55600. var properties = propertyPath.split(".");
  55601. return properties[properties.length - 1];
  55602. };
  55603. /**
  55604. * Serialize this manager to a JSON object
  55605. * @param name defines the property name to store this manager
  55606. * @returns a JSON representation of this manager
  55607. */
  55608. ActionManager.prototype.serialize = function (name) {
  55609. var root = {
  55610. children: new Array(),
  55611. name: name,
  55612. type: 3,
  55613. properties: new Array() // Empty for root but required
  55614. };
  55615. for (var i = 0; i < this.actions.length; i++) {
  55616. var triggerObject = {
  55617. type: 0,
  55618. children: new Array(),
  55619. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  55620. properties: new Array()
  55621. };
  55622. var triggerOptions = this.actions[i].triggerOptions;
  55623. if (triggerOptions && typeof triggerOptions !== "number") {
  55624. if (triggerOptions.parameter instanceof BABYLON.Node) {
  55625. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  55626. }
  55627. else {
  55628. var parameter = {};
  55629. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  55630. if (triggerOptions.parameter && triggerOptions.parameter.mesh) {
  55631. parameter._meshId = triggerOptions.parameter.mesh.id;
  55632. }
  55633. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  55634. }
  55635. }
  55636. // Serialize child action, recursively
  55637. this.actions[i].serialize(triggerObject);
  55638. // Add serialized trigger
  55639. root.children.push(triggerObject);
  55640. }
  55641. return root;
  55642. };
  55643. /**
  55644. * Creates a new ActionManager from a JSON data
  55645. * @param parsedActions defines the JSON data to read from
  55646. * @param object defines the hosting mesh
  55647. * @param scene defines the hosting scene
  55648. */
  55649. ActionManager.Parse = function (parsedActions, object, scene) {
  55650. var actionManager = new ActionManager(scene);
  55651. if (object === null) {
  55652. scene.actionManager = actionManager;
  55653. }
  55654. else {
  55655. object.actionManager = actionManager;
  55656. }
  55657. // instanciate a new object
  55658. var instanciate = function (name, params) {
  55659. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  55660. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  55661. newInstance.constructor.apply(newInstance, params);
  55662. return newInstance;
  55663. };
  55664. var parseParameter = function (name, value, target, propertyPath) {
  55665. if (propertyPath === null) {
  55666. // String, boolean or float
  55667. var floatValue = parseFloat(value);
  55668. if (value === "true" || value === "false") {
  55669. return value === "true";
  55670. }
  55671. else {
  55672. return isNaN(floatValue) ? value : floatValue;
  55673. }
  55674. }
  55675. var effectiveTarget = propertyPath.split(".");
  55676. var values = value.split(",");
  55677. // Get effective Target
  55678. for (var i = 0; i < effectiveTarget.length; i++) {
  55679. target = target[effectiveTarget[i]];
  55680. }
  55681. // Return appropriate value with its type
  55682. if (typeof (target) === "boolean") {
  55683. return values[0] === "true";
  55684. }
  55685. if (typeof (target) === "string") {
  55686. return values[0];
  55687. }
  55688. // Parameters with multiple values such as Vector3 etc.
  55689. var split = new Array();
  55690. for (var i = 0; i < values.length; i++) {
  55691. split.push(parseFloat(values[i]));
  55692. }
  55693. if (target instanceof BABYLON.Vector3) {
  55694. return BABYLON.Vector3.FromArray(split);
  55695. }
  55696. if (target instanceof BABYLON.Vector4) {
  55697. return BABYLON.Vector4.FromArray(split);
  55698. }
  55699. if (target instanceof BABYLON.Color3) {
  55700. return BABYLON.Color3.FromArray(split);
  55701. }
  55702. if (target instanceof BABYLON.Color4) {
  55703. return BABYLON.Color4.FromArray(split);
  55704. }
  55705. return parseFloat(values[0]);
  55706. };
  55707. // traverse graph per trigger
  55708. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  55709. if (combineArray === void 0) { combineArray = null; }
  55710. if (parsedAction.detached) {
  55711. return;
  55712. }
  55713. var parameters = new Array();
  55714. var target = null;
  55715. var propertyPath = null;
  55716. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  55717. // Parameters
  55718. if (parsedAction.type === 2) {
  55719. parameters.push(actionManager);
  55720. }
  55721. else {
  55722. parameters.push(trigger);
  55723. }
  55724. if (combine) {
  55725. var actions = new Array();
  55726. for (var j = 0; j < parsedAction.combine.length; j++) {
  55727. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  55728. }
  55729. parameters.push(actions);
  55730. }
  55731. else {
  55732. for (var i = 0; i < parsedAction.properties.length; i++) {
  55733. var value = parsedAction.properties[i].value;
  55734. var name = parsedAction.properties[i].name;
  55735. var targetType = parsedAction.properties[i].targetType;
  55736. if (name === "target") {
  55737. if (targetType !== null && targetType === "SceneProperties") {
  55738. value = target = scene;
  55739. }
  55740. else {
  55741. value = target = scene.getNodeByName(value);
  55742. }
  55743. }
  55744. else if (name === "parent") {
  55745. value = scene.getNodeByName(value);
  55746. }
  55747. else if (name === "sound") {
  55748. // Can not externalize to component, so only checks for the presence off the API.
  55749. if (scene.getSoundByName) {
  55750. value = scene.getSoundByName(value);
  55751. }
  55752. }
  55753. else if (name !== "propertyPath") {
  55754. if (parsedAction.type === 2 && name === "operator") {
  55755. value = BABYLON.ValueCondition[value];
  55756. }
  55757. else {
  55758. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  55759. }
  55760. }
  55761. else {
  55762. propertyPath = value;
  55763. }
  55764. parameters.push(value);
  55765. }
  55766. }
  55767. if (combineArray === null) {
  55768. parameters.push(condition);
  55769. }
  55770. else {
  55771. parameters.push(null);
  55772. }
  55773. // If interpolate value action
  55774. if (parsedAction.name === "InterpolateValueAction") {
  55775. var param = parameters[parameters.length - 2];
  55776. parameters[parameters.length - 1] = param;
  55777. parameters[parameters.length - 2] = condition;
  55778. }
  55779. // Action or condition(s) and not CombineAction
  55780. var newAction = instanciate(parsedAction.name, parameters);
  55781. if (newAction instanceof BABYLON.Condition && condition !== null) {
  55782. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  55783. if (action) {
  55784. action.then(nothing);
  55785. }
  55786. else {
  55787. actionManager.registerAction(nothing);
  55788. }
  55789. action = nothing;
  55790. }
  55791. if (combineArray === null) {
  55792. if (newAction instanceof BABYLON.Condition) {
  55793. condition = newAction;
  55794. newAction = action;
  55795. }
  55796. else {
  55797. condition = null;
  55798. if (action) {
  55799. action.then(newAction);
  55800. }
  55801. else {
  55802. actionManager.registerAction(newAction);
  55803. }
  55804. }
  55805. }
  55806. else {
  55807. combineArray.push(newAction);
  55808. }
  55809. for (var i = 0; i < parsedAction.children.length; i++) {
  55810. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  55811. }
  55812. };
  55813. // triggers
  55814. for (var i = 0; i < parsedActions.children.length; i++) {
  55815. var triggerParams;
  55816. var trigger = parsedActions.children[i];
  55817. if (trigger.properties.length > 0) {
  55818. var param = trigger.properties[0].value;
  55819. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  55820. if (value._meshId) {
  55821. value.mesh = scene.getMeshByID(value._meshId);
  55822. }
  55823. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  55824. }
  55825. else {
  55826. triggerParams = ActionManager[trigger.name];
  55827. }
  55828. for (var j = 0; j < trigger.children.length; j++) {
  55829. if (!trigger.detached) {
  55830. traverse(trigger.children[j], triggerParams, null, null);
  55831. }
  55832. }
  55833. }
  55834. };
  55835. /**
  55836. * Get a trigger name by index
  55837. * @param trigger defines the trigger index
  55838. * @returns a trigger name
  55839. */
  55840. ActionManager.GetTriggerName = function (trigger) {
  55841. switch (trigger) {
  55842. case 0: return "NothingTrigger";
  55843. case 1: return "OnPickTrigger";
  55844. case 2: return "OnLeftPickTrigger";
  55845. case 3: return "OnRightPickTrigger";
  55846. case 4: return "OnCenterPickTrigger";
  55847. case 5: return "OnPickDownTrigger";
  55848. case 6: return "OnPickUpTrigger";
  55849. case 7: return "OnLongPressTrigger";
  55850. case 8: return "OnPointerOverTrigger";
  55851. case 9: return "OnPointerOutTrigger";
  55852. case 10: return "OnEveryFrameTrigger";
  55853. case 11: return "OnIntersectionEnterTrigger";
  55854. case 12: return "OnIntersectionExitTrigger";
  55855. case 13: return "OnKeyDownTrigger";
  55856. case 14: return "OnKeyUpTrigger";
  55857. case 15: return "OnPickOutTrigger";
  55858. default: return "";
  55859. }
  55860. };
  55861. /**
  55862. * Nothing
  55863. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55864. */
  55865. ActionManager.NothingTrigger = 0;
  55866. /**
  55867. * On pick
  55868. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55869. */
  55870. ActionManager.OnPickTrigger = 1;
  55871. /**
  55872. * On left pick
  55873. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55874. */
  55875. ActionManager.OnLeftPickTrigger = 2;
  55876. /**
  55877. * On right pick
  55878. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55879. */
  55880. ActionManager.OnRightPickTrigger = 3;
  55881. /**
  55882. * On center pick
  55883. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55884. */
  55885. ActionManager.OnCenterPickTrigger = 4;
  55886. /**
  55887. * On pick down
  55888. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55889. */
  55890. ActionManager.OnPickDownTrigger = 5;
  55891. /**
  55892. * On double pick
  55893. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55894. */
  55895. ActionManager.OnDoublePickTrigger = 6;
  55896. /**
  55897. * On pick up
  55898. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55899. */
  55900. ActionManager.OnPickUpTrigger = 7;
  55901. /**
  55902. * On pick out.
  55903. * This trigger will only be raised if you also declared a OnPickDown
  55904. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55905. */
  55906. ActionManager.OnPickOutTrigger = 16;
  55907. /**
  55908. * On long press
  55909. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55910. */
  55911. ActionManager.OnLongPressTrigger = 8;
  55912. /**
  55913. * On pointer over
  55914. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55915. */
  55916. ActionManager.OnPointerOverTrigger = 9;
  55917. /**
  55918. * On pointer out
  55919. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55920. */
  55921. ActionManager.OnPointerOutTrigger = 10;
  55922. /**
  55923. * On every frame
  55924. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55925. */
  55926. ActionManager.OnEveryFrameTrigger = 11;
  55927. /**
  55928. * On intersection enter
  55929. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55930. */
  55931. ActionManager.OnIntersectionEnterTrigger = 12;
  55932. /**
  55933. * On intersection exit
  55934. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55935. */
  55936. ActionManager.OnIntersectionExitTrigger = 13;
  55937. /**
  55938. * On key down
  55939. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55940. */
  55941. ActionManager.OnKeyDownTrigger = 14;
  55942. /**
  55943. * On key up
  55944. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55945. */
  55946. ActionManager.OnKeyUpTrigger = 15;
  55947. /** Gets the list of active triggers */
  55948. ActionManager.Triggers = {};
  55949. return ActionManager;
  55950. }());
  55951. BABYLON.ActionManager = ActionManager;
  55952. })(BABYLON || (BABYLON = {}));
  55953. //# sourceMappingURL=babylon.actionManager.js.map
  55954. var BABYLON;
  55955. (function (BABYLON) {
  55956. /**
  55957. * This defines an action responsible to change the value of a property
  55958. * by interpolating between its current value and the newly set one once triggered.
  55959. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55960. */
  55961. var InterpolateValueAction = /** @class */ (function (_super) {
  55962. __extends(InterpolateValueAction, _super);
  55963. /**
  55964. * Instantiate the action
  55965. * @param triggerOptions defines the trigger options
  55966. * @param target defines the object containing the value to interpolate
  55967. * @param propertyPath defines the path to the property in the target object
  55968. * @param value defines the target value at the end of the interpolation
  55969. * @param duration deines the time it will take for the property to interpolate to the value.
  55970. * @param condition defines the trigger related conditions
  55971. * @param stopOtherAnimations defines if the other scene animations should be stopped when the action has been triggered
  55972. * @param onInterpolationDone defines a callback raised once the interpolation animation has been done
  55973. */
  55974. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  55975. if (duration === void 0) { duration = 1000; }
  55976. var _this = _super.call(this, triggerOptions, condition) || this;
  55977. /**
  55978. * Defines the time it will take for the property to interpolate to the value.
  55979. */
  55980. _this.duration = 1000;
  55981. /**
  55982. * Observable triggered once the interpolation animation has been done.
  55983. */
  55984. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  55985. _this.propertyPath = propertyPath;
  55986. _this.value = value;
  55987. _this.duration = duration;
  55988. _this.stopOtherAnimations = stopOtherAnimations;
  55989. _this.onInterpolationDone = onInterpolationDone;
  55990. _this._target = _this._effectiveTarget = target;
  55991. return _this;
  55992. }
  55993. /** @hidden */
  55994. InterpolateValueAction.prototype._prepare = function () {
  55995. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  55996. this._property = this._getProperty(this.propertyPath);
  55997. };
  55998. /**
  55999. * Execute the action starts the value interpolation.
  56000. */
  56001. InterpolateValueAction.prototype.execute = function () {
  56002. var _this = this;
  56003. var scene = this._actionManager.getScene();
  56004. var keys = [
  56005. {
  56006. frame: 0,
  56007. value: this._effectiveTarget[this._property]
  56008. }, {
  56009. frame: 100,
  56010. value: this.value
  56011. }
  56012. ];
  56013. var dataType;
  56014. if (typeof this.value === "number") {
  56015. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  56016. }
  56017. else if (this.value instanceof BABYLON.Color3) {
  56018. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  56019. }
  56020. else if (this.value instanceof BABYLON.Vector3) {
  56021. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  56022. }
  56023. else if (this.value instanceof BABYLON.Matrix) {
  56024. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  56025. }
  56026. else if (this.value instanceof BABYLON.Quaternion) {
  56027. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  56028. }
  56029. else {
  56030. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  56031. return;
  56032. }
  56033. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  56034. animation.setKeys(keys);
  56035. if (this.stopOtherAnimations) {
  56036. scene.stopAnimation(this._effectiveTarget);
  56037. }
  56038. var wrapper = function () {
  56039. _this.onInterpolationDoneObservable.notifyObservers(_this);
  56040. if (_this.onInterpolationDone) {
  56041. _this.onInterpolationDone();
  56042. }
  56043. };
  56044. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  56045. };
  56046. /**
  56047. * Serializes the actions and its related information.
  56048. * @param parent defines the object to serialize in
  56049. * @returns the serialized object
  56050. */
  56051. InterpolateValueAction.prototype.serialize = function (parent) {
  56052. return _super.prototype._serialize.call(this, {
  56053. name: "InterpolateValueAction",
  56054. properties: [
  56055. BABYLON.Action._GetTargetProperty(this._target),
  56056. { name: "propertyPath", value: this.propertyPath },
  56057. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  56058. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  56059. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  56060. ]
  56061. }, parent);
  56062. };
  56063. return InterpolateValueAction;
  56064. }(BABYLON.Action));
  56065. BABYLON.InterpolateValueAction = InterpolateValueAction;
  56066. })(BABYLON || (BABYLON = {}));
  56067. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  56068. var BABYLON;
  56069. (function (BABYLON) {
  56070. /**
  56071. * This defines an action responsible to toggle a boolean once triggered.
  56072. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56073. */
  56074. var SwitchBooleanAction = /** @class */ (function (_super) {
  56075. __extends(SwitchBooleanAction, _super);
  56076. /**
  56077. * Instantiate the action
  56078. * @param triggerOptions defines the trigger options
  56079. * @param target defines the object containing the boolean
  56080. * @param propertyPath defines the path to the boolean property in the target object
  56081. * @param condition defines the trigger related conditions
  56082. */
  56083. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  56084. var _this = _super.call(this, triggerOptions, condition) || this;
  56085. _this.propertyPath = propertyPath;
  56086. _this._target = _this._effectiveTarget = target;
  56087. return _this;
  56088. }
  56089. /** @hidden */
  56090. SwitchBooleanAction.prototype._prepare = function () {
  56091. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  56092. this._property = this._getProperty(this.propertyPath);
  56093. };
  56094. /**
  56095. * Execute the action toggle the boolean value.
  56096. */
  56097. SwitchBooleanAction.prototype.execute = function () {
  56098. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  56099. };
  56100. /**
  56101. * Serializes the actions and its related information.
  56102. * @param parent defines the object to serialize in
  56103. * @returns the serialized object
  56104. */
  56105. SwitchBooleanAction.prototype.serialize = function (parent) {
  56106. return _super.prototype._serialize.call(this, {
  56107. name: "SwitchBooleanAction",
  56108. properties: [
  56109. BABYLON.Action._GetTargetProperty(this._target),
  56110. { name: "propertyPath", value: this.propertyPath }
  56111. ]
  56112. }, parent);
  56113. };
  56114. return SwitchBooleanAction;
  56115. }(BABYLON.Action));
  56116. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  56117. /**
  56118. * This defines an action responsible to set a the state field of the target
  56119. * to a desired value once triggered.
  56120. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56121. */
  56122. var SetStateAction = /** @class */ (function (_super) {
  56123. __extends(SetStateAction, _super);
  56124. /**
  56125. * Instantiate the action
  56126. * @param triggerOptions defines the trigger options
  56127. * @param target defines the object containing the state property
  56128. * @param value defines the value to store in the state field
  56129. * @param condition defines the trigger related conditions
  56130. */
  56131. function SetStateAction(triggerOptions, target, value, condition) {
  56132. var _this = _super.call(this, triggerOptions, condition) || this;
  56133. _this.value = value;
  56134. _this._target = target;
  56135. return _this;
  56136. }
  56137. /**
  56138. * Execute the action and store the value on the target state property.
  56139. */
  56140. SetStateAction.prototype.execute = function () {
  56141. this._target.state = this.value;
  56142. };
  56143. /**
  56144. * Serializes the actions and its related information.
  56145. * @param parent defines the object to serialize in
  56146. * @returns the serialized object
  56147. */
  56148. SetStateAction.prototype.serialize = function (parent) {
  56149. return _super.prototype._serialize.call(this, {
  56150. name: "SetStateAction",
  56151. properties: [
  56152. BABYLON.Action._GetTargetProperty(this._target),
  56153. { name: "value", value: this.value }
  56154. ]
  56155. }, parent);
  56156. };
  56157. return SetStateAction;
  56158. }(BABYLON.Action));
  56159. BABYLON.SetStateAction = SetStateAction;
  56160. /**
  56161. * This defines an action responsible to set a property of the target
  56162. * to a desired value once triggered.
  56163. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56164. */
  56165. var SetValueAction = /** @class */ (function (_super) {
  56166. __extends(SetValueAction, _super);
  56167. /**
  56168. * Instantiate the action
  56169. * @param triggerOptions defines the trigger options
  56170. * @param target defines the object containing the property
  56171. * @param propertyPath defines the path of the property to set in the target
  56172. * @param value defines the value to set in the property
  56173. * @param condition defines the trigger related conditions
  56174. */
  56175. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  56176. var _this = _super.call(this, triggerOptions, condition) || this;
  56177. _this.propertyPath = propertyPath;
  56178. _this.value = value;
  56179. _this._target = _this._effectiveTarget = target;
  56180. return _this;
  56181. }
  56182. /** @hidden */
  56183. SetValueAction.prototype._prepare = function () {
  56184. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  56185. this._property = this._getProperty(this.propertyPath);
  56186. };
  56187. /**
  56188. * Execute the action and set the targetted property to the desired value.
  56189. */
  56190. SetValueAction.prototype.execute = function () {
  56191. this._effectiveTarget[this._property] = this.value;
  56192. if (this._target.markAsDirty) {
  56193. this._target.markAsDirty(this._property);
  56194. }
  56195. };
  56196. /**
  56197. * Serializes the actions and its related information.
  56198. * @param parent defines the object to serialize in
  56199. * @returns the serialized object
  56200. */
  56201. SetValueAction.prototype.serialize = function (parent) {
  56202. return _super.prototype._serialize.call(this, {
  56203. name: "SetValueAction",
  56204. properties: [
  56205. BABYLON.Action._GetTargetProperty(this._target),
  56206. { name: "propertyPath", value: this.propertyPath },
  56207. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  56208. ]
  56209. }, parent);
  56210. };
  56211. return SetValueAction;
  56212. }(BABYLON.Action));
  56213. BABYLON.SetValueAction = SetValueAction;
  56214. /**
  56215. * This defines an action responsible to increment the target value
  56216. * to a desired value once triggered.
  56217. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56218. */
  56219. var IncrementValueAction = /** @class */ (function (_super) {
  56220. __extends(IncrementValueAction, _super);
  56221. /**
  56222. * Instantiate the action
  56223. * @param triggerOptions defines the trigger options
  56224. * @param target defines the object containing the property
  56225. * @param propertyPath defines the path of the property to increment in the target
  56226. * @param value defines the value value we should increment the property by
  56227. * @param condition defines the trigger related conditions
  56228. */
  56229. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  56230. var _this = _super.call(this, triggerOptions, condition) || this;
  56231. _this.propertyPath = propertyPath;
  56232. _this.value = value;
  56233. _this._target = _this._effectiveTarget = target;
  56234. return _this;
  56235. }
  56236. /** @hidden */
  56237. IncrementValueAction.prototype._prepare = function () {
  56238. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  56239. this._property = this._getProperty(this.propertyPath);
  56240. if (typeof this._effectiveTarget[this._property] !== "number") {
  56241. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  56242. }
  56243. };
  56244. /**
  56245. * Execute the action and increment the target of the value amount.
  56246. */
  56247. IncrementValueAction.prototype.execute = function () {
  56248. this._effectiveTarget[this._property] += this.value;
  56249. if (this._target.markAsDirty) {
  56250. this._target.markAsDirty(this._property);
  56251. }
  56252. };
  56253. /**
  56254. * Serializes the actions and its related information.
  56255. * @param parent defines the object to serialize in
  56256. * @returns the serialized object
  56257. */
  56258. IncrementValueAction.prototype.serialize = function (parent) {
  56259. return _super.prototype._serialize.call(this, {
  56260. name: "IncrementValueAction",
  56261. properties: [
  56262. BABYLON.Action._GetTargetProperty(this._target),
  56263. { name: "propertyPath", value: this.propertyPath },
  56264. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  56265. ]
  56266. }, parent);
  56267. };
  56268. return IncrementValueAction;
  56269. }(BABYLON.Action));
  56270. BABYLON.IncrementValueAction = IncrementValueAction;
  56271. /**
  56272. * This defines an action responsible to start an animation once triggered.
  56273. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56274. */
  56275. var PlayAnimationAction = /** @class */ (function (_super) {
  56276. __extends(PlayAnimationAction, _super);
  56277. /**
  56278. * Instantiate the action
  56279. * @param triggerOptions defines the trigger options
  56280. * @param target defines the target animation or animation name
  56281. * @param from defines from where the animation should start (animation frame)
  56282. * @param end defines where the animation should stop (animation frame)
  56283. * @param loop defines if the animation should loop or stop after the first play
  56284. * @param condition defines the trigger related conditions
  56285. */
  56286. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  56287. var _this = _super.call(this, triggerOptions, condition) || this;
  56288. _this.from = from;
  56289. _this.to = to;
  56290. _this.loop = loop;
  56291. _this._target = target;
  56292. return _this;
  56293. }
  56294. /** @hidden */
  56295. PlayAnimationAction.prototype._prepare = function () {
  56296. };
  56297. /**
  56298. * Execute the action and play the animation.
  56299. */
  56300. PlayAnimationAction.prototype.execute = function () {
  56301. var scene = this._actionManager.getScene();
  56302. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  56303. };
  56304. /**
  56305. * Serializes the actions and its related information.
  56306. * @param parent defines the object to serialize in
  56307. * @returns the serialized object
  56308. */
  56309. PlayAnimationAction.prototype.serialize = function (parent) {
  56310. return _super.prototype._serialize.call(this, {
  56311. name: "PlayAnimationAction",
  56312. properties: [
  56313. BABYLON.Action._GetTargetProperty(this._target),
  56314. { name: "from", value: String(this.from) },
  56315. { name: "to", value: String(this.to) },
  56316. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  56317. ]
  56318. }, parent);
  56319. };
  56320. return PlayAnimationAction;
  56321. }(BABYLON.Action));
  56322. BABYLON.PlayAnimationAction = PlayAnimationAction;
  56323. /**
  56324. * This defines an action responsible to stop an animation once triggered.
  56325. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56326. */
  56327. var StopAnimationAction = /** @class */ (function (_super) {
  56328. __extends(StopAnimationAction, _super);
  56329. /**
  56330. * Instantiate the action
  56331. * @param triggerOptions defines the trigger options
  56332. * @param target defines the target animation or animation name
  56333. * @param condition defines the trigger related conditions
  56334. */
  56335. function StopAnimationAction(triggerOptions, target, condition) {
  56336. var _this = _super.call(this, triggerOptions, condition) || this;
  56337. _this._target = target;
  56338. return _this;
  56339. }
  56340. /** @hidden */
  56341. StopAnimationAction.prototype._prepare = function () {
  56342. };
  56343. /**
  56344. * Execute the action and stop the animation.
  56345. */
  56346. StopAnimationAction.prototype.execute = function () {
  56347. var scene = this._actionManager.getScene();
  56348. scene.stopAnimation(this._target);
  56349. };
  56350. /**
  56351. * Serializes the actions and its related information.
  56352. * @param parent defines the object to serialize in
  56353. * @returns the serialized object
  56354. */
  56355. StopAnimationAction.prototype.serialize = function (parent) {
  56356. return _super.prototype._serialize.call(this, {
  56357. name: "StopAnimationAction",
  56358. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  56359. }, parent);
  56360. };
  56361. return StopAnimationAction;
  56362. }(BABYLON.Action));
  56363. BABYLON.StopAnimationAction = StopAnimationAction;
  56364. /**
  56365. * This defines an action responsible that does nothing once triggered.
  56366. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56367. */
  56368. var DoNothingAction = /** @class */ (function (_super) {
  56369. __extends(DoNothingAction, _super);
  56370. /**
  56371. * Instantiate the action
  56372. * @param triggerOptions defines the trigger options
  56373. * @param condition defines the trigger related conditions
  56374. */
  56375. function DoNothingAction(triggerOptions, condition) {
  56376. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  56377. return _super.call(this, triggerOptions, condition) || this;
  56378. }
  56379. /**
  56380. * Execute the action and do nothing.
  56381. */
  56382. DoNothingAction.prototype.execute = function () {
  56383. };
  56384. /**
  56385. * Serializes the actions and its related information.
  56386. * @param parent defines the object to serialize in
  56387. * @returns the serialized object
  56388. */
  56389. DoNothingAction.prototype.serialize = function (parent) {
  56390. return _super.prototype._serialize.call(this, {
  56391. name: "DoNothingAction",
  56392. properties: []
  56393. }, parent);
  56394. };
  56395. return DoNothingAction;
  56396. }(BABYLON.Action));
  56397. BABYLON.DoNothingAction = DoNothingAction;
  56398. /**
  56399. * This defines an action responsible to trigger several actions once triggered.
  56400. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56401. */
  56402. var CombineAction = /** @class */ (function (_super) {
  56403. __extends(CombineAction, _super);
  56404. /**
  56405. * Instantiate the action
  56406. * @param triggerOptions defines the trigger options
  56407. * @param children defines the list of aggregated animations to run
  56408. * @param condition defines the trigger related conditions
  56409. */
  56410. function CombineAction(triggerOptions, children, condition) {
  56411. var _this = _super.call(this, triggerOptions, condition) || this;
  56412. _this.children = children;
  56413. return _this;
  56414. }
  56415. /** @hidden */
  56416. CombineAction.prototype._prepare = function () {
  56417. for (var index = 0; index < this.children.length; index++) {
  56418. this.children[index]._actionManager = this._actionManager;
  56419. this.children[index]._prepare();
  56420. }
  56421. };
  56422. /**
  56423. * Execute the action and executes all the aggregated actions.
  56424. */
  56425. CombineAction.prototype.execute = function (evt) {
  56426. for (var index = 0; index < this.children.length; index++) {
  56427. this.children[index].execute(evt);
  56428. }
  56429. };
  56430. /**
  56431. * Serializes the actions and its related information.
  56432. * @param parent defines the object to serialize in
  56433. * @returns the serialized object
  56434. */
  56435. CombineAction.prototype.serialize = function (parent) {
  56436. var serializationObject = _super.prototype._serialize.call(this, {
  56437. name: "CombineAction",
  56438. properties: [],
  56439. combine: []
  56440. }, parent);
  56441. for (var i = 0; i < this.children.length; i++) {
  56442. serializationObject.combine.push(this.children[i].serialize(null));
  56443. }
  56444. return serializationObject;
  56445. };
  56446. return CombineAction;
  56447. }(BABYLON.Action));
  56448. BABYLON.CombineAction = CombineAction;
  56449. /**
  56450. * This defines an action responsible to run code (external event) once triggered.
  56451. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56452. */
  56453. var ExecuteCodeAction = /** @class */ (function (_super) {
  56454. __extends(ExecuteCodeAction, _super);
  56455. /**
  56456. * Instantiate the action
  56457. * @param triggerOptions defines the trigger options
  56458. * @param func defines the callback function to run
  56459. * @param condition defines the trigger related conditions
  56460. */
  56461. function ExecuteCodeAction(triggerOptions, func, condition) {
  56462. var _this = _super.call(this, triggerOptions, condition) || this;
  56463. _this.func = func;
  56464. return _this;
  56465. }
  56466. /**
  56467. * Execute the action and run the attached code.
  56468. */
  56469. ExecuteCodeAction.prototype.execute = function (evt) {
  56470. this.func(evt);
  56471. };
  56472. return ExecuteCodeAction;
  56473. }(BABYLON.Action));
  56474. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  56475. /**
  56476. * This defines an action responsible to set the parent property of the target once triggered.
  56477. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56478. */
  56479. var SetParentAction = /** @class */ (function (_super) {
  56480. __extends(SetParentAction, _super);
  56481. /**
  56482. * Instantiate the action
  56483. * @param triggerOptions defines the trigger options
  56484. * @param target defines the target containing the parent property
  56485. * @param parent defines from where the animation should start (animation frame)
  56486. * @param condition defines the trigger related conditions
  56487. */
  56488. function SetParentAction(triggerOptions, target, parent, condition) {
  56489. var _this = _super.call(this, triggerOptions, condition) || this;
  56490. _this._target = target;
  56491. _this._parent = parent;
  56492. return _this;
  56493. }
  56494. /** @hidden */
  56495. SetParentAction.prototype._prepare = function () {
  56496. };
  56497. /**
  56498. * Execute the action and set the parent property.
  56499. */
  56500. SetParentAction.prototype.execute = function () {
  56501. if (this._target.parent === this._parent) {
  56502. return;
  56503. }
  56504. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  56505. invertParentWorldMatrix.invert();
  56506. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  56507. this._target.parent = this._parent;
  56508. };
  56509. /**
  56510. * Serializes the actions and its related information.
  56511. * @param parent defines the object to serialize in
  56512. * @returns the serialized object
  56513. */
  56514. SetParentAction.prototype.serialize = function (parent) {
  56515. return _super.prototype._serialize.call(this, {
  56516. name: "SetParentAction",
  56517. properties: [
  56518. BABYLON.Action._GetTargetProperty(this._target),
  56519. BABYLON.Action._GetTargetProperty(this._parent),
  56520. ]
  56521. }, parent);
  56522. };
  56523. return SetParentAction;
  56524. }(BABYLON.Action));
  56525. BABYLON.SetParentAction = SetParentAction;
  56526. })(BABYLON || (BABYLON = {}));
  56527. //# sourceMappingURL=babylon.directActions.js.map
  56528. var BABYLON;
  56529. (function (BABYLON) {
  56530. /**
  56531. * Class used to manage multiple sprites on the same spritesheet
  56532. * @see http://doc.babylonjs.com/babylon101/sprites
  56533. */
  56534. var SpriteManager = /** @class */ (function () {
  56535. /**
  56536. * Creates a new sprite manager
  56537. * @param name defines the manager's name
  56538. * @param imgUrl defines the sprite sheet url
  56539. * @param capacity defines the maximum allowed number of sprites
  56540. * @param cellSize defines the size of a sprite cell
  56541. * @param scene defines the hosting scene
  56542. * @param epsilon defines the epsilon value to align texture (0.01 by default)
  56543. * @param samplingMode defines the smapling mode to use with spritesheet
  56544. */
  56545. function SpriteManager(
  56546. /** defines the manager's name */
  56547. name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  56548. if (epsilon === void 0) { epsilon = 0.01; }
  56549. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  56550. this.name = name;
  56551. /** Gets the list of sprites */
  56552. this.sprites = new Array();
  56553. /** Gets or sets the rendering group id (0 by default) */
  56554. this.renderingGroupId = 0;
  56555. /** Gets or sets camera layer mask */
  56556. this.layerMask = 0x0FFFFFFF;
  56557. /** Gets or sets a boolean indicating if the manager must consider scene fog when rendering */
  56558. this.fogEnabled = true;
  56559. /** Gets or sets a boolean indicating if the sprites are pickable */
  56560. this.isPickable = false;
  56561. /**
  56562. * An event triggered when the manager is disposed.
  56563. */
  56564. this.onDisposeObservable = new BABYLON.Observable();
  56565. this._vertexBuffers = {};
  56566. if (!scene._getComponent(BABYLON.SceneComponentConstants.NAME_SPRITE)) {
  56567. scene._addComponent(new BABYLON.SpriteSceneComponent(scene));
  56568. }
  56569. this._capacity = capacity;
  56570. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  56571. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56572. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56573. if (cellSize.width && cellSize.height) {
  56574. this.cellWidth = cellSize.width;
  56575. this.cellHeight = cellSize.height;
  56576. }
  56577. else if (cellSize !== undefined) {
  56578. this.cellWidth = cellSize;
  56579. this.cellHeight = cellSize;
  56580. }
  56581. else {
  56582. return;
  56583. }
  56584. this._epsilon = epsilon;
  56585. this._scene = scene;
  56586. this._scene.spriteManagers.push(this);
  56587. var indices = [];
  56588. var index = 0;
  56589. for (var count = 0; count < capacity; count++) {
  56590. indices.push(index);
  56591. indices.push(index + 1);
  56592. indices.push(index + 2);
  56593. indices.push(index);
  56594. indices.push(index + 2);
  56595. indices.push(index + 3);
  56596. index += 4;
  56597. }
  56598. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  56599. // VBO
  56600. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  56601. this._vertexData = new Float32Array(capacity * 16 * 4);
  56602. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  56603. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  56604. var options = this._buffer.createVertexBuffer("options", 4, 4);
  56605. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  56606. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  56607. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  56608. this._vertexBuffers["options"] = options;
  56609. this._vertexBuffers["cellInfo"] = cellInfo;
  56610. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  56611. // Effects
  56612. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  56613. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  56614. }
  56615. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  56616. /**
  56617. * Callback called when the manager is disposed
  56618. */
  56619. set: function (callback) {
  56620. if (this._onDisposeObserver) {
  56621. this.onDisposeObservable.remove(this._onDisposeObserver);
  56622. }
  56623. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  56624. },
  56625. enumerable: true,
  56626. configurable: true
  56627. });
  56628. Object.defineProperty(SpriteManager.prototype, "texture", {
  56629. /**
  56630. * Gets or sets the spritesheet texture
  56631. */
  56632. get: function () {
  56633. return this._spriteTexture;
  56634. },
  56635. set: function (value) {
  56636. this._spriteTexture = value;
  56637. },
  56638. enumerable: true,
  56639. configurable: true
  56640. });
  56641. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  56642. var arrayOffset = index * 16;
  56643. if (offsetX === 0) {
  56644. offsetX = this._epsilon;
  56645. }
  56646. else if (offsetX === 1) {
  56647. offsetX = 1 - this._epsilon;
  56648. }
  56649. if (offsetY === 0) {
  56650. offsetY = this._epsilon;
  56651. }
  56652. else if (offsetY === 1) {
  56653. offsetY = 1 - this._epsilon;
  56654. }
  56655. this._vertexData[arrayOffset] = sprite.position.x;
  56656. this._vertexData[arrayOffset + 1] = sprite.position.y;
  56657. this._vertexData[arrayOffset + 2] = sprite.position.z;
  56658. this._vertexData[arrayOffset + 3] = sprite.angle;
  56659. this._vertexData[arrayOffset + 4] = sprite.width;
  56660. this._vertexData[arrayOffset + 5] = sprite.height;
  56661. this._vertexData[arrayOffset + 6] = offsetX;
  56662. this._vertexData[arrayOffset + 7] = offsetY;
  56663. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  56664. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  56665. var offset = (sprite.cellIndex / rowSize) >> 0;
  56666. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  56667. this._vertexData[arrayOffset + 11] = offset;
  56668. // Color
  56669. this._vertexData[arrayOffset + 12] = sprite.color.r;
  56670. this._vertexData[arrayOffset + 13] = sprite.color.g;
  56671. this._vertexData[arrayOffset + 14] = sprite.color.b;
  56672. this._vertexData[arrayOffset + 15] = sprite.color.a;
  56673. };
  56674. /**
  56675. * Intersects the sprites with a ray
  56676. * @param ray defines the ray to intersect with
  56677. * @param camera defines the current active camera
  56678. * @param predicate defines a predicate used to select candidate sprites
  56679. * @param fastCheck defines if a fast check only must be done (the first potential sprite is will be used and not the closer)
  56680. * @returns null if no hit or a PickingInfo
  56681. */
  56682. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  56683. var count = Math.min(this._capacity, this.sprites.length);
  56684. var min = BABYLON.Vector3.Zero();
  56685. var max = BABYLON.Vector3.Zero();
  56686. var distance = Number.MAX_VALUE;
  56687. var currentSprite = null;
  56688. var cameraSpacePosition = BABYLON.Vector3.Zero();
  56689. var cameraView = camera.getViewMatrix();
  56690. for (var index = 0; index < count; index++) {
  56691. var sprite = this.sprites[index];
  56692. if (!sprite) {
  56693. continue;
  56694. }
  56695. if (predicate) {
  56696. if (!predicate(sprite)) {
  56697. continue;
  56698. }
  56699. }
  56700. else if (!sprite.isPickable) {
  56701. continue;
  56702. }
  56703. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  56704. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  56705. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  56706. if (ray.intersectsBoxMinMax(min, max)) {
  56707. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  56708. if (distance > currentDistance) {
  56709. distance = currentDistance;
  56710. currentSprite = sprite;
  56711. if (fastCheck) {
  56712. break;
  56713. }
  56714. }
  56715. }
  56716. }
  56717. if (currentSprite) {
  56718. var result = new BABYLON.PickingInfo();
  56719. result.hit = true;
  56720. result.pickedSprite = currentSprite;
  56721. result.distance = distance;
  56722. return result;
  56723. }
  56724. return null;
  56725. };
  56726. /**
  56727. * Render all child sprites
  56728. */
  56729. SpriteManager.prototype.render = function () {
  56730. // Check
  56731. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady()) {
  56732. return;
  56733. }
  56734. var engine = this._scene.getEngine();
  56735. var baseSize = this._spriteTexture.getBaseSize();
  56736. // Sprites
  56737. var deltaTime = engine.getDeltaTime();
  56738. var max = Math.min(this._capacity, this.sprites.length);
  56739. var rowSize = baseSize.width / this.cellWidth;
  56740. var offset = 0;
  56741. for (var index = 0; index < max; index++) {
  56742. var sprite = this.sprites[index];
  56743. if (!sprite || !sprite.isVisible) {
  56744. continue;
  56745. }
  56746. sprite._animate(deltaTime);
  56747. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  56748. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  56749. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  56750. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  56751. }
  56752. this._buffer.update(this._vertexData);
  56753. // Render
  56754. var effect = this._effectBase;
  56755. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  56756. effect = this._effectFog;
  56757. }
  56758. engine.enableEffect(effect);
  56759. var viewMatrix = this._scene.getViewMatrix();
  56760. effect.setTexture("diffuseSampler", this._spriteTexture);
  56761. effect.setMatrix("view", viewMatrix);
  56762. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56763. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  56764. // Fog
  56765. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  56766. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  56767. effect.setColor3("vFogColor", this._scene.fogColor);
  56768. }
  56769. // VBOs
  56770. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56771. // Draw order
  56772. engine.setDepthFunctionToLessOrEqual();
  56773. effect.setBool("alphaTest", true);
  56774. engine.setColorWrite(false);
  56775. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  56776. engine.setColorWrite(true);
  56777. effect.setBool("alphaTest", false);
  56778. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56779. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  56780. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56781. };
  56782. /**
  56783. * Release associated resources
  56784. */
  56785. SpriteManager.prototype.dispose = function () {
  56786. if (this._buffer) {
  56787. this._buffer.dispose();
  56788. this._buffer = null;
  56789. }
  56790. if (this._indexBuffer) {
  56791. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56792. this._indexBuffer = null;
  56793. }
  56794. if (this._spriteTexture) {
  56795. this._spriteTexture.dispose();
  56796. this._spriteTexture = null;
  56797. }
  56798. // Remove from scene
  56799. var index = this._scene.spriteManagers.indexOf(this);
  56800. this._scene.spriteManagers.splice(index, 1);
  56801. // Callback
  56802. this.onDisposeObservable.notifyObservers(this);
  56803. this.onDisposeObservable.clear();
  56804. };
  56805. return SpriteManager;
  56806. }());
  56807. BABYLON.SpriteManager = SpriteManager;
  56808. })(BABYLON || (BABYLON = {}));
  56809. //# sourceMappingURL=babylon.spriteManager.js.map
  56810. var BABYLON;
  56811. (function (BABYLON) {
  56812. /**
  56813. * Class used to represent a sprite
  56814. * @see http://doc.babylonjs.com/babylon101/sprites
  56815. */
  56816. var Sprite = /** @class */ (function () {
  56817. /**
  56818. * Creates a new Sprite
  56819. * @param name defines the name
  56820. * @param manager defines the manager
  56821. */
  56822. function Sprite(
  56823. /** defines the name */
  56824. name, manager) {
  56825. this.name = name;
  56826. /** Gets or sets the main color */
  56827. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56828. /** Gets or sets the width */
  56829. this.width = 1.0;
  56830. /** Gets or sets the height */
  56831. this.height = 1.0;
  56832. /** Gets or sets rotation angle */
  56833. this.angle = 0;
  56834. /** Gets or sets the cell index in the sprite sheet */
  56835. this.cellIndex = 0;
  56836. /** Gets or sets a boolean indicating if UV coordinates should be inverted in U axis */
  56837. this.invertU = 0;
  56838. /** Gets or sets a boolean indicating if UV coordinates should be inverted in B axis */
  56839. this.invertV = 0;
  56840. /** Gets the list of attached animations */
  56841. this.animations = new Array();
  56842. /** Gets or sets a boolean indicating if the sprite can be picked */
  56843. this.isPickable = false;
  56844. this._animationStarted = false;
  56845. this._loopAnimation = false;
  56846. this._fromIndex = 0;
  56847. this._toIndex = 0;
  56848. this._delay = 0;
  56849. this._direction = 1;
  56850. this._time = 0;
  56851. /**
  56852. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  56853. */
  56854. this.isVisible = true;
  56855. this._manager = manager;
  56856. this._manager.sprites.push(this);
  56857. this.position = BABYLON.Vector3.Zero();
  56858. }
  56859. Object.defineProperty(Sprite.prototype, "size", {
  56860. /**
  56861. * Gets or sets the sprite size
  56862. */
  56863. get: function () {
  56864. return this.width;
  56865. },
  56866. set: function (value) {
  56867. this.width = value;
  56868. this.height = value;
  56869. },
  56870. enumerable: true,
  56871. configurable: true
  56872. });
  56873. /**
  56874. * Starts an animation
  56875. * @param from defines the initial key
  56876. * @param to defines the end key
  56877. * @param loop defines if the animation must loop
  56878. * @param delay defines the start delay (in ms)
  56879. * @param onAnimationEnd defines a callback to call when animation ends
  56880. */
  56881. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  56882. this._fromIndex = from;
  56883. this._toIndex = to;
  56884. this._loopAnimation = loop;
  56885. this._delay = delay;
  56886. this._animationStarted = true;
  56887. this._direction = from < to ? 1 : -1;
  56888. this.cellIndex = from;
  56889. this._time = 0;
  56890. this._onAnimationEnd = onAnimationEnd;
  56891. };
  56892. /** Stops current animation (if any) */
  56893. Sprite.prototype.stopAnimation = function () {
  56894. this._animationStarted = false;
  56895. };
  56896. /** @hidden */
  56897. Sprite.prototype._animate = function (deltaTime) {
  56898. if (!this._animationStarted) {
  56899. return;
  56900. }
  56901. this._time += deltaTime;
  56902. if (this._time > this._delay) {
  56903. this._time = this._time % this._delay;
  56904. this.cellIndex += this._direction;
  56905. if (this.cellIndex > this._toIndex) {
  56906. if (this._loopAnimation) {
  56907. this.cellIndex = this._fromIndex;
  56908. }
  56909. else {
  56910. this.cellIndex = this._toIndex;
  56911. this._animationStarted = false;
  56912. if (this._onAnimationEnd) {
  56913. this._onAnimationEnd();
  56914. }
  56915. if (this.disposeWhenFinishedAnimating) {
  56916. this.dispose();
  56917. }
  56918. }
  56919. }
  56920. }
  56921. };
  56922. /** Release associated resources */
  56923. Sprite.prototype.dispose = function () {
  56924. for (var i = 0; i < this._manager.sprites.length; i++) {
  56925. if (this._manager.sprites[i] == this) {
  56926. this._manager.sprites.splice(i, 1);
  56927. }
  56928. }
  56929. };
  56930. return Sprite;
  56931. }());
  56932. BABYLON.Sprite = Sprite;
  56933. })(BABYLON || (BABYLON = {}));
  56934. //# sourceMappingURL=babylon.sprite.js.map
  56935. var BABYLON;
  56936. (function (BABYLON) {
  56937. BABYLON.Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  56938. if (!BABYLON.PickingInfo) {
  56939. return null;
  56940. }
  56941. var pickingInfo = null;
  56942. if (!camera) {
  56943. if (!this.activeCamera) {
  56944. return null;
  56945. }
  56946. camera = this.activeCamera;
  56947. }
  56948. if (this.spriteManagers.length > 0) {
  56949. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  56950. var spriteManager = this.spriteManagers[spriteIndex];
  56951. if (!spriteManager.isPickable) {
  56952. continue;
  56953. }
  56954. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  56955. if (!result || !result.hit) {
  56956. continue;
  56957. }
  56958. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance) {
  56959. continue;
  56960. }
  56961. pickingInfo = result;
  56962. if (fastCheck) {
  56963. break;
  56964. }
  56965. }
  56966. }
  56967. return pickingInfo || new BABYLON.PickingInfo();
  56968. };
  56969. BABYLON.Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  56970. this.createPickingRayInCameraSpaceToRef(x, y, this._tempSpritePickingRay, camera);
  56971. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  56972. };
  56973. BABYLON.Scene.prototype.pickSpriteWithRay = function (ray, predicate, fastCheck, camera) {
  56974. if (!this._tempSpritePickingRay) {
  56975. return null;
  56976. }
  56977. if (!camera) {
  56978. if (!this.activeCamera) {
  56979. return null;
  56980. }
  56981. camera = this.activeCamera;
  56982. }
  56983. BABYLON.Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay);
  56984. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  56985. };
  56986. BABYLON.Scene.prototype.setPointerOverSprite = function (sprite) {
  56987. if (this._pointerOverSprite === sprite) {
  56988. return;
  56989. }
  56990. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  56991. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  56992. }
  56993. this._pointerOverSprite = sprite;
  56994. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  56995. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  56996. }
  56997. };
  56998. BABYLON.Scene.prototype.getPointerOverSprite = function () {
  56999. return this._pointerOverSprite;
  57000. };
  57001. /**
  57002. * Defines the sprite scene component responsible to manage sprites
  57003. * in a given scene.
  57004. */
  57005. var SpriteSceneComponent = /** @class */ (function () {
  57006. /**
  57007. * Creates a new instance of the component for the given scene
  57008. * @param scene Defines the scene to register the component in
  57009. */
  57010. function SpriteSceneComponent(scene) {
  57011. /**
  57012. * The component name helpfull to identify the component in the list of scene components.
  57013. */
  57014. this.name = BABYLON.SceneComponentConstants.NAME_SPRITE;
  57015. this.scene = scene;
  57016. this.scene.spriteManagers = new Array();
  57017. this.scene._tempSpritePickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  57018. this.scene.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  57019. this.scene.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  57020. this._spritePredicate = function (sprite) {
  57021. if (!sprite.actionManager) {
  57022. return false;
  57023. }
  57024. return sprite.isPickable && sprite.actionManager.hasPointerTriggers;
  57025. };
  57026. }
  57027. /**
  57028. * Registers the component in a given scene
  57029. */
  57030. SpriteSceneComponent.prototype.register = function () {
  57031. this.scene._pointerMoveStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERMOVE_SPRITE, this, this._pointerMove);
  57032. this.scene._pointerDownStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERDOWN_SPRITE, this, this._pointerDown);
  57033. this.scene._pointerUpStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERUP_SPRITE, this, this._pointerUp);
  57034. };
  57035. /**
  57036. * Rebuilds the elements related to this component in case of
  57037. * context lost for instance.
  57038. */
  57039. SpriteSceneComponent.prototype.rebuild = function () {
  57040. /** Nothing to do for sprites */
  57041. };
  57042. /**
  57043. * Disposes the component and the associated ressources.
  57044. */
  57045. SpriteSceneComponent.prototype.dispose = function () {
  57046. this.scene.onBeforeSpritesRenderingObservable.clear();
  57047. this.scene.onAfterSpritesRenderingObservable.clear();
  57048. var spriteManagers = this.scene.spriteManagers;
  57049. while (spriteManagers.length) {
  57050. spriteManagers[0].dispose();
  57051. }
  57052. };
  57053. SpriteSceneComponent.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, fastCheck, camera) {
  57054. var result = this.scene.pickSprite(x, y, this._spritePredicate, fastCheck, camera);
  57055. if (result) {
  57056. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  57057. }
  57058. return result;
  57059. };
  57060. SpriteSceneComponent.prototype._pointerMove = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, isMeshPicked, canvas) {
  57061. var scene = this.scene;
  57062. if (isMeshPicked) {
  57063. scene.setPointerOverSprite(null);
  57064. }
  57065. else {
  57066. pickResult = this._pickSpriteButKeepRay(pickResult, unTranslatedPointerX, unTranslatedPointerY, false, scene.cameraToUseForPointers || undefined);
  57067. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  57068. scene.setPointerOverSprite(pickResult.pickedSprite);
  57069. if (scene._pointerOverSprite && scene._pointerOverSprite.actionManager && scene._pointerOverSprite.actionManager.hoverCursor) {
  57070. canvas.style.cursor = scene._pointerOverSprite.actionManager.hoverCursor;
  57071. }
  57072. else {
  57073. canvas.style.cursor = scene.hoverCursor;
  57074. }
  57075. }
  57076. else {
  57077. scene.setPointerOverSprite(null);
  57078. }
  57079. }
  57080. return pickResult;
  57081. };
  57082. SpriteSceneComponent.prototype._pointerDown = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  57083. var scene = this.scene;
  57084. scene._pickedDownSprite = null;
  57085. if (scene.spriteManagers.length > 0) {
  57086. pickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  57087. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  57088. if (pickResult.pickedSprite.actionManager) {
  57089. scene._pickedDownSprite = pickResult.pickedSprite;
  57090. switch (evt.button) {
  57091. case 0:
  57092. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  57093. break;
  57094. case 1:
  57095. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  57096. break;
  57097. case 2:
  57098. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  57099. break;
  57100. }
  57101. if (pickResult.pickedSprite.actionManager) {
  57102. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  57103. }
  57104. }
  57105. }
  57106. }
  57107. return pickResult;
  57108. };
  57109. SpriteSceneComponent.prototype._pointerUp = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  57110. var scene = this.scene;
  57111. if (scene.spriteManagers.length > 0) {
  57112. var spritePickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  57113. if (spritePickResult) {
  57114. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  57115. if (spritePickResult.pickedSprite.actionManager) {
  57116. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  57117. if (spritePickResult.pickedSprite.actionManager) {
  57118. if (!this.scene._isPointerSwiping()) {
  57119. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  57120. }
  57121. }
  57122. }
  57123. }
  57124. if (scene._pickedDownSprite && scene._pickedDownSprite.actionManager && scene._pickedDownSprite !== spritePickResult.pickedSprite) {
  57125. scene._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(scene._pickedDownSprite, scene, evt));
  57126. }
  57127. }
  57128. }
  57129. return pickResult;
  57130. };
  57131. return SpriteSceneComponent;
  57132. }());
  57133. BABYLON.SpriteSceneComponent = SpriteSceneComponent;
  57134. })(BABYLON || (BABYLON = {}));
  57135. //# sourceMappingURL=babylon.spriteSceneComponent.js.map
  57136. var BABYLON;
  57137. (function (BABYLON) {
  57138. /**
  57139. * @hidden
  57140. */
  57141. var IntersectionInfo = /** @class */ (function () {
  57142. function IntersectionInfo(bu, bv, distance) {
  57143. this.bu = bu;
  57144. this.bv = bv;
  57145. this.distance = distance;
  57146. this.faceId = 0;
  57147. this.subMeshId = 0;
  57148. }
  57149. return IntersectionInfo;
  57150. }());
  57151. BABYLON.IntersectionInfo = IntersectionInfo;
  57152. /**
  57153. * Information about the result of picking within a scene
  57154. * @see https://doc.babylonjs.com/babylon101/picking_collisions
  57155. */
  57156. var PickingInfo = /** @class */ (function () {
  57157. function PickingInfo() {
  57158. /**
  57159. * If the pick collided with an object
  57160. */
  57161. this.hit = false;
  57162. /**
  57163. * Distance away where the pick collided
  57164. */
  57165. this.distance = 0;
  57166. /**
  57167. * The location of pick collision
  57168. */
  57169. this.pickedPoint = null;
  57170. /**
  57171. * The mesh corresponding the the pick collision
  57172. */
  57173. this.pickedMesh = null;
  57174. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  57175. this.bu = 0;
  57176. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  57177. this.bv = 0;
  57178. /** The id of the face on the mesh that was picked */
  57179. this.faceId = -1;
  57180. /** Id of the the submesh that was picked */
  57181. this.subMeshId = 0;
  57182. /** If a sprite was picked, this will be the sprite the pick collided with */
  57183. this.pickedSprite = null;
  57184. /**
  57185. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  57186. */
  57187. this.originMesh = null;
  57188. /**
  57189. * The ray that was used to perform the picking.
  57190. */
  57191. this.ray = null;
  57192. }
  57193. /**
  57194. * Gets the normal correspodning to the face the pick collided with
  57195. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  57196. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  57197. * @returns The normal correspodning to the face the pick collided with
  57198. */
  57199. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  57200. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  57201. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  57202. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  57203. return null;
  57204. }
  57205. var indices = this.pickedMesh.getIndices();
  57206. if (!indices) {
  57207. return null;
  57208. }
  57209. var result;
  57210. if (useVerticesNormals) {
  57211. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57212. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  57213. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  57214. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  57215. normal0 = normal0.scale(this.bu);
  57216. normal1 = normal1.scale(this.bv);
  57217. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  57218. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  57219. }
  57220. else {
  57221. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57222. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  57223. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  57224. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  57225. var p1p2 = vertex1.subtract(vertex2);
  57226. var p3p2 = vertex3.subtract(vertex2);
  57227. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  57228. }
  57229. if (useWorldCoordinates) {
  57230. var wm = this.pickedMesh.getWorldMatrix();
  57231. if (this.pickedMesh.nonUniformScaling) {
  57232. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  57233. wm = BABYLON.Tmp.Matrix[0];
  57234. wm.setTranslationFromFloats(0, 0, 0);
  57235. wm.invert();
  57236. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  57237. wm = BABYLON.Tmp.Matrix[1];
  57238. }
  57239. result = BABYLON.Vector3.TransformNormal(result, wm);
  57240. }
  57241. result.normalize();
  57242. return result;
  57243. };
  57244. /**
  57245. * Gets the texture coordinates of where the pick occured
  57246. * @returns the vector containing the coordnates of the texture
  57247. */
  57248. PickingInfo.prototype.getTextureCoordinates = function () {
  57249. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  57250. return null;
  57251. }
  57252. var indices = this.pickedMesh.getIndices();
  57253. if (!indices) {
  57254. return null;
  57255. }
  57256. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  57257. if (!uvs) {
  57258. return null;
  57259. }
  57260. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  57261. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  57262. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  57263. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  57264. uv1 = uv1.scale(this.bu);
  57265. uv2 = uv2.scale(this.bv);
  57266. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  57267. };
  57268. return PickingInfo;
  57269. }());
  57270. BABYLON.PickingInfo = PickingInfo;
  57271. })(BABYLON || (BABYLON = {}));
  57272. //# sourceMappingURL=babylon.pickingInfo.js.map
  57273. var BABYLON;
  57274. (function (BABYLON) {
  57275. /**
  57276. * Class representing a ray with position and direction
  57277. */
  57278. var Ray = /** @class */ (function () {
  57279. /**
  57280. * Creates a new ray
  57281. * @param origin origin point
  57282. * @param direction direction
  57283. * @param length length of the ray
  57284. */
  57285. function Ray(
  57286. /** origin point */
  57287. origin,
  57288. /** direction */
  57289. direction,
  57290. /** length of the ray */
  57291. length) {
  57292. if (length === void 0) { length = Number.MAX_VALUE; }
  57293. this.origin = origin;
  57294. this.direction = direction;
  57295. this.length = length;
  57296. }
  57297. // Methods
  57298. /**
  57299. * Checks if the ray intersects a box
  57300. * @param minimum bound of the box
  57301. * @param maximum bound of the box
  57302. * @returns if the box was hit
  57303. */
  57304. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  57305. var d = 0.0;
  57306. var maxValue = Number.MAX_VALUE;
  57307. var inv;
  57308. var min;
  57309. var max;
  57310. var temp;
  57311. if (Math.abs(this.direction.x) < 0.0000001) {
  57312. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  57313. return false;
  57314. }
  57315. }
  57316. else {
  57317. inv = 1.0 / this.direction.x;
  57318. min = (minimum.x - this.origin.x) * inv;
  57319. max = (maximum.x - this.origin.x) * inv;
  57320. if (max === -Infinity) {
  57321. max = Infinity;
  57322. }
  57323. if (min > max) {
  57324. temp = min;
  57325. min = max;
  57326. max = temp;
  57327. }
  57328. d = Math.max(min, d);
  57329. maxValue = Math.min(max, maxValue);
  57330. if (d > maxValue) {
  57331. return false;
  57332. }
  57333. }
  57334. if (Math.abs(this.direction.y) < 0.0000001) {
  57335. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  57336. return false;
  57337. }
  57338. }
  57339. else {
  57340. inv = 1.0 / this.direction.y;
  57341. min = (minimum.y - this.origin.y) * inv;
  57342. max = (maximum.y - this.origin.y) * inv;
  57343. if (max === -Infinity) {
  57344. max = Infinity;
  57345. }
  57346. if (min > max) {
  57347. temp = min;
  57348. min = max;
  57349. max = temp;
  57350. }
  57351. d = Math.max(min, d);
  57352. maxValue = Math.min(max, maxValue);
  57353. if (d > maxValue) {
  57354. return false;
  57355. }
  57356. }
  57357. if (Math.abs(this.direction.z) < 0.0000001) {
  57358. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  57359. return false;
  57360. }
  57361. }
  57362. else {
  57363. inv = 1.0 / this.direction.z;
  57364. min = (minimum.z - this.origin.z) * inv;
  57365. max = (maximum.z - this.origin.z) * inv;
  57366. if (max === -Infinity) {
  57367. max = Infinity;
  57368. }
  57369. if (min > max) {
  57370. temp = min;
  57371. min = max;
  57372. max = temp;
  57373. }
  57374. d = Math.max(min, d);
  57375. maxValue = Math.min(max, maxValue);
  57376. if (d > maxValue) {
  57377. return false;
  57378. }
  57379. }
  57380. return true;
  57381. };
  57382. /**
  57383. * Checks if the ray intersects a box
  57384. * @param box the bounding box to check
  57385. * @returns if the box was hit
  57386. */
  57387. Ray.prototype.intersectsBox = function (box) {
  57388. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  57389. };
  57390. /**
  57391. * If the ray hits a sphere
  57392. * @param sphere the bounding sphere to check
  57393. * @returns true if it hits the sphere
  57394. */
  57395. Ray.prototype.intersectsSphere = function (sphere) {
  57396. var x = sphere.center.x - this.origin.x;
  57397. var y = sphere.center.y - this.origin.y;
  57398. var z = sphere.center.z - this.origin.z;
  57399. var pyth = (x * x) + (y * y) + (z * z);
  57400. var rr = sphere.radius * sphere.radius;
  57401. if (pyth <= rr) {
  57402. return true;
  57403. }
  57404. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  57405. if (dot < 0.0) {
  57406. return false;
  57407. }
  57408. var temp = pyth - (dot * dot);
  57409. return temp <= rr;
  57410. };
  57411. /**
  57412. * If the ray hits a triange
  57413. * @param vertex0 triangle vertex
  57414. * @param vertex1 triangle vertex
  57415. * @param vertex2 triangle vertex
  57416. * @returns intersection information if hit
  57417. */
  57418. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  57419. if (!this._edge1) {
  57420. this._edge1 = BABYLON.Vector3.Zero();
  57421. this._edge2 = BABYLON.Vector3.Zero();
  57422. this._pvec = BABYLON.Vector3.Zero();
  57423. this._tvec = BABYLON.Vector3.Zero();
  57424. this._qvec = BABYLON.Vector3.Zero();
  57425. }
  57426. vertex1.subtractToRef(vertex0, this._edge1);
  57427. vertex2.subtractToRef(vertex0, this._edge2);
  57428. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  57429. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  57430. if (det === 0) {
  57431. return null;
  57432. }
  57433. var invdet = 1 / det;
  57434. this.origin.subtractToRef(vertex0, this._tvec);
  57435. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  57436. if (bu < 0 || bu > 1.0) {
  57437. return null;
  57438. }
  57439. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  57440. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  57441. if (bv < 0 || bu + bv > 1.0) {
  57442. return null;
  57443. }
  57444. //check if the distance is longer than the predefined length.
  57445. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  57446. if (distance > this.length) {
  57447. return null;
  57448. }
  57449. return new BABYLON.IntersectionInfo(bu, bv, distance);
  57450. };
  57451. /**
  57452. * Checks if ray intersects a plane
  57453. * @param plane the plane to check
  57454. * @returns the distance away it was hit
  57455. */
  57456. Ray.prototype.intersectsPlane = function (plane) {
  57457. var distance;
  57458. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  57459. if (Math.abs(result1) < 9.99999997475243E-07) {
  57460. return null;
  57461. }
  57462. else {
  57463. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  57464. distance = (-plane.d - result2) / result1;
  57465. if (distance < 0.0) {
  57466. if (distance < -9.99999997475243E-07) {
  57467. return null;
  57468. }
  57469. else {
  57470. return 0;
  57471. }
  57472. }
  57473. return distance;
  57474. }
  57475. };
  57476. /**
  57477. * Checks if ray intersects a mesh
  57478. * @param mesh the mesh to check
  57479. * @param fastCheck if only the bounding box should checked
  57480. * @returns picking info of the intersecton
  57481. */
  57482. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  57483. var tm = BABYLON.Tmp.Matrix[0];
  57484. mesh.getWorldMatrix().invertToRef(tm);
  57485. if (this._tmpRay) {
  57486. Ray.TransformToRef(this, tm, this._tmpRay);
  57487. }
  57488. else {
  57489. this._tmpRay = Ray.Transform(this, tm);
  57490. }
  57491. return mesh.intersects(this._tmpRay, fastCheck);
  57492. };
  57493. /**
  57494. * Checks if ray intersects a mesh
  57495. * @param meshes the meshes to check
  57496. * @param fastCheck if only the bounding box should checked
  57497. * @param results array to store result in
  57498. * @returns Array of picking infos
  57499. */
  57500. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  57501. if (results) {
  57502. results.length = 0;
  57503. }
  57504. else {
  57505. results = [];
  57506. }
  57507. for (var i = 0; i < meshes.length; i++) {
  57508. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  57509. if (pickInfo.hit) {
  57510. results.push(pickInfo);
  57511. }
  57512. }
  57513. results.sort(this._comparePickingInfo);
  57514. return results;
  57515. };
  57516. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  57517. if (pickingInfoA.distance < pickingInfoB.distance) {
  57518. return -1;
  57519. }
  57520. else if (pickingInfoA.distance > pickingInfoB.distance) {
  57521. return 1;
  57522. }
  57523. else {
  57524. return 0;
  57525. }
  57526. };
  57527. /**
  57528. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  57529. * @param sega the first point of the segment to test the intersection against
  57530. * @param segb the second point of the segment to test the intersection against
  57531. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  57532. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  57533. */
  57534. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  57535. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  57536. var u = segb.subtract(sega);
  57537. var v = rsegb.subtract(this.origin);
  57538. var w = sega.subtract(this.origin);
  57539. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  57540. var b = BABYLON.Vector3.Dot(u, v);
  57541. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  57542. var d = BABYLON.Vector3.Dot(u, w);
  57543. var e = BABYLON.Vector3.Dot(v, w);
  57544. var D = a * c - b * b; // always >= 0
  57545. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  57546. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  57547. // compute the line parameters of the two closest points
  57548. if (D < Ray.smallnum) { // the lines are almost parallel
  57549. sN = 0.0; // force using point P0 on segment S1
  57550. sD = 1.0; // to prevent possible division by 0.0 later
  57551. tN = e;
  57552. tD = c;
  57553. }
  57554. else { // get the closest points on the infinite lines
  57555. sN = (b * e - c * d);
  57556. tN = (a * e - b * d);
  57557. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  57558. sN = 0.0;
  57559. tN = e;
  57560. tD = c;
  57561. }
  57562. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  57563. sN = sD;
  57564. tN = e + b;
  57565. tD = c;
  57566. }
  57567. }
  57568. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  57569. tN = 0.0;
  57570. // recompute sc for this edge
  57571. if (-d < 0.0) {
  57572. sN = 0.0;
  57573. }
  57574. else if (-d > a) {
  57575. sN = sD;
  57576. }
  57577. else {
  57578. sN = -d;
  57579. sD = a;
  57580. }
  57581. }
  57582. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  57583. tN = tD;
  57584. // recompute sc for this edge
  57585. if ((-d + b) < 0.0) {
  57586. sN = 0;
  57587. }
  57588. else if ((-d + b) > a) {
  57589. sN = sD;
  57590. }
  57591. else {
  57592. sN = (-d + b);
  57593. sD = a;
  57594. }
  57595. }
  57596. // finally do the division to get sc and tc
  57597. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  57598. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  57599. // get the difference of the two closest points
  57600. var qtc = v.multiplyByFloats(tc, tc, tc);
  57601. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  57602. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  57603. if (isIntersected) {
  57604. return qtc.length();
  57605. }
  57606. return -1;
  57607. };
  57608. /**
  57609. * Update the ray from viewport position
  57610. * @param x position
  57611. * @param y y position
  57612. * @param viewportWidth viewport width
  57613. * @param viewportHeight viewport height
  57614. * @param world world matrix
  57615. * @param view view matrix
  57616. * @param projection projection matrix
  57617. * @returns this ray updated
  57618. */
  57619. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  57620. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  57621. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  57622. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  57623. this.direction.normalize();
  57624. return this;
  57625. };
  57626. // Statics
  57627. /**
  57628. * Creates a ray with origin and direction of 0,0,0
  57629. * @returns the new ray
  57630. */
  57631. Ray.Zero = function () {
  57632. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  57633. };
  57634. /**
  57635. * Creates a new ray from screen space and viewport
  57636. * @param x position
  57637. * @param y y position
  57638. * @param viewportWidth viewport width
  57639. * @param viewportHeight viewport height
  57640. * @param world world matrix
  57641. * @param view view matrix
  57642. * @param projection projection matrix
  57643. * @returns new ray
  57644. */
  57645. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  57646. var result = Ray.Zero();
  57647. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  57648. };
  57649. /**
  57650. * 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
  57651. * transformed to the given world matrix.
  57652. * @param origin The origin point
  57653. * @param end The end point
  57654. * @param world a matrix to transform the ray to. Default is the identity matrix.
  57655. * @returns the new ray
  57656. */
  57657. Ray.CreateNewFromTo = function (origin, end, world) {
  57658. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  57659. var direction = end.subtract(origin);
  57660. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  57661. direction.normalize();
  57662. return Ray.Transform(new Ray(origin, direction, length), world);
  57663. };
  57664. /**
  57665. * Transforms a ray by a matrix
  57666. * @param ray ray to transform
  57667. * @param matrix matrix to apply
  57668. * @returns the resulting new ray
  57669. */
  57670. Ray.Transform = function (ray, matrix) {
  57671. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  57672. Ray.TransformToRef(ray, matrix, result);
  57673. return result;
  57674. };
  57675. /**
  57676. * Transforms a ray by a matrix
  57677. * @param ray ray to transform
  57678. * @param matrix matrix to apply
  57679. * @param result ray to store result in
  57680. */
  57681. Ray.TransformToRef = function (ray, matrix, result) {
  57682. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  57683. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  57684. result.length = ray.length;
  57685. var dir = result.direction;
  57686. var len = dir.length();
  57687. if (!(len === 0 || len === 1)) {
  57688. var num = 1.0 / len;
  57689. dir.x *= num;
  57690. dir.y *= num;
  57691. dir.z *= num;
  57692. result.length *= len;
  57693. }
  57694. };
  57695. Ray.smallnum = 0.00000001;
  57696. Ray.rayl = 10e8;
  57697. return Ray;
  57698. }());
  57699. BABYLON.Ray = Ray;
  57700. })(BABYLON || (BABYLON = {}));
  57701. //# sourceMappingURL=babylon.ray.js.map
  57702. var BABYLON;
  57703. (function (BABYLON) {
  57704. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  57705. if (boxMin.x > sphereCenter.x + sphereRadius) {
  57706. return false;
  57707. }
  57708. if (sphereCenter.x - sphereRadius > boxMax.x) {
  57709. return false;
  57710. }
  57711. if (boxMin.y > sphereCenter.y + sphereRadius) {
  57712. return false;
  57713. }
  57714. if (sphereCenter.y - sphereRadius > boxMax.y) {
  57715. return false;
  57716. }
  57717. if (boxMin.z > sphereCenter.z + sphereRadius) {
  57718. return false;
  57719. }
  57720. if (sphereCenter.z - sphereRadius > boxMax.z) {
  57721. return false;
  57722. }
  57723. return true;
  57724. };
  57725. var getLowestRoot = (function () {
  57726. var result = { root: 0, found: false };
  57727. return function (a, b, c, maxR) {
  57728. result.root = 0;
  57729. result.found = false;
  57730. var determinant = b * b - 4.0 * a * c;
  57731. if (determinant < 0) {
  57732. return result;
  57733. }
  57734. var sqrtD = Math.sqrt(determinant);
  57735. var r1 = (-b - sqrtD) / (2.0 * a);
  57736. var r2 = (-b + sqrtD) / (2.0 * a);
  57737. if (r1 > r2) {
  57738. var temp = r2;
  57739. r2 = r1;
  57740. r1 = temp;
  57741. }
  57742. if (r1 > 0 && r1 < maxR) {
  57743. result.root = r1;
  57744. result.found = true;
  57745. return result;
  57746. }
  57747. if (r2 > 0 && r2 < maxR) {
  57748. result.root = r2;
  57749. result.found = true;
  57750. return result;
  57751. }
  57752. return result;
  57753. };
  57754. })();
  57755. /** @hidden */
  57756. var Collider = /** @class */ (function () {
  57757. function Collider() {
  57758. this._collisionPoint = BABYLON.Vector3.Zero();
  57759. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  57760. this._tempVector = BABYLON.Vector3.Zero();
  57761. this._tempVector2 = BABYLON.Vector3.Zero();
  57762. this._tempVector3 = BABYLON.Vector3.Zero();
  57763. this._tempVector4 = BABYLON.Vector3.Zero();
  57764. this._edge = BABYLON.Vector3.Zero();
  57765. this._baseToVertex = BABYLON.Vector3.Zero();
  57766. this._destinationPoint = BABYLON.Vector3.Zero();
  57767. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  57768. this._displacementVector = BABYLON.Vector3.Zero();
  57769. /** @hidden */
  57770. this._radius = BABYLON.Vector3.One();
  57771. /** @hidden */
  57772. this._retry = 0;
  57773. /** @hidden */
  57774. this._basePointWorld = BABYLON.Vector3.Zero();
  57775. this._velocityWorld = BABYLON.Vector3.Zero();
  57776. this._normalizedVelocity = BABYLON.Vector3.Zero();
  57777. this._collisionMask = -1;
  57778. }
  57779. Object.defineProperty(Collider.prototype, "collisionMask", {
  57780. get: function () {
  57781. return this._collisionMask;
  57782. },
  57783. set: function (mask) {
  57784. this._collisionMask = !isNaN(mask) ? mask : -1;
  57785. },
  57786. enumerable: true,
  57787. configurable: true
  57788. });
  57789. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  57790. /**
  57791. * Gets the plane normal used to compute the sliding response (in local space)
  57792. */
  57793. get: function () {
  57794. return this._slidePlaneNormal;
  57795. },
  57796. enumerable: true,
  57797. configurable: true
  57798. });
  57799. // Methods
  57800. /** @hidden */
  57801. Collider.prototype._initialize = function (source, dir, e) {
  57802. this._velocity = dir;
  57803. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  57804. this._basePoint = source;
  57805. source.multiplyToRef(this._radius, this._basePointWorld);
  57806. dir.multiplyToRef(this._radius, this._velocityWorld);
  57807. this._velocityWorldLength = this._velocityWorld.length();
  57808. this._epsilon = e;
  57809. this.collisionFound = false;
  57810. };
  57811. /** @hidden */
  57812. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  57813. pa.subtractToRef(point, this._tempVector);
  57814. pb.subtractToRef(point, this._tempVector2);
  57815. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  57816. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  57817. if (d < 0) {
  57818. return false;
  57819. }
  57820. pc.subtractToRef(point, this._tempVector3);
  57821. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  57822. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  57823. if (d < 0) {
  57824. return false;
  57825. }
  57826. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  57827. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  57828. return d >= 0;
  57829. };
  57830. /** @hidden */
  57831. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  57832. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  57833. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  57834. if (distance > this._velocityWorldLength + max + sphereRadius) {
  57835. return false;
  57836. }
  57837. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max)) {
  57838. return false;
  57839. }
  57840. return true;
  57841. };
  57842. /** @hidden */
  57843. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  57844. var t0;
  57845. var embeddedInPlane = false;
  57846. //defensive programming, actually not needed.
  57847. if (!trianglePlaneArray) {
  57848. trianglePlaneArray = [];
  57849. }
  57850. if (!trianglePlaneArray[faceIndex]) {
  57851. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  57852. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  57853. }
  57854. var trianglePlane = trianglePlaneArray[faceIndex];
  57855. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0)) {
  57856. return;
  57857. }
  57858. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  57859. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  57860. if (normalDotVelocity == 0) {
  57861. if (Math.abs(signedDistToTrianglePlane) >= 1.0) {
  57862. return;
  57863. }
  57864. embeddedInPlane = true;
  57865. t0 = 0;
  57866. }
  57867. else {
  57868. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  57869. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  57870. if (t0 > t1) {
  57871. var temp = t1;
  57872. t1 = t0;
  57873. t0 = temp;
  57874. }
  57875. if (t0 > 1.0 || t1 < 0.0) {
  57876. return;
  57877. }
  57878. if (t0 < 0) {
  57879. t0 = 0;
  57880. }
  57881. if (t0 > 1.0) {
  57882. t0 = 1.0;
  57883. }
  57884. }
  57885. this._collisionPoint.copyFromFloats(0, 0, 0);
  57886. var found = false;
  57887. var t = 1.0;
  57888. if (!embeddedInPlane) {
  57889. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  57890. this._velocity.scaleToRef(t0, this._tempVector);
  57891. this._planeIntersectionPoint.addInPlace(this._tempVector);
  57892. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  57893. found = true;
  57894. t = t0;
  57895. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  57896. }
  57897. }
  57898. if (!found) {
  57899. var velocitySquaredLength = this._velocity.lengthSquared();
  57900. var a = velocitySquaredLength;
  57901. this._basePoint.subtractToRef(p1, this._tempVector);
  57902. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  57903. var c = this._tempVector.lengthSquared() - 1.0;
  57904. var lowestRoot = getLowestRoot(a, b, c, t);
  57905. if (lowestRoot.found) {
  57906. t = lowestRoot.root;
  57907. found = true;
  57908. this._collisionPoint.copyFrom(p1);
  57909. }
  57910. this._basePoint.subtractToRef(p2, this._tempVector);
  57911. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  57912. c = this._tempVector.lengthSquared() - 1.0;
  57913. lowestRoot = getLowestRoot(a, b, c, t);
  57914. if (lowestRoot.found) {
  57915. t = lowestRoot.root;
  57916. found = true;
  57917. this._collisionPoint.copyFrom(p2);
  57918. }
  57919. this._basePoint.subtractToRef(p3, this._tempVector);
  57920. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  57921. c = this._tempVector.lengthSquared() - 1.0;
  57922. lowestRoot = getLowestRoot(a, b, c, t);
  57923. if (lowestRoot.found) {
  57924. t = lowestRoot.root;
  57925. found = true;
  57926. this._collisionPoint.copyFrom(p3);
  57927. }
  57928. p2.subtractToRef(p1, this._edge);
  57929. p1.subtractToRef(this._basePoint, this._baseToVertex);
  57930. var edgeSquaredLength = this._edge.lengthSquared();
  57931. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  57932. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  57933. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  57934. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  57935. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  57936. lowestRoot = getLowestRoot(a, b, c, t);
  57937. if (lowestRoot.found) {
  57938. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  57939. if (f >= 0.0 && f <= 1.0) {
  57940. t = lowestRoot.root;
  57941. found = true;
  57942. this._edge.scaleInPlace(f);
  57943. p1.addToRef(this._edge, this._collisionPoint);
  57944. }
  57945. }
  57946. p3.subtractToRef(p2, this._edge);
  57947. p2.subtractToRef(this._basePoint, this._baseToVertex);
  57948. edgeSquaredLength = this._edge.lengthSquared();
  57949. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  57950. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  57951. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  57952. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  57953. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  57954. lowestRoot = getLowestRoot(a, b, c, t);
  57955. if (lowestRoot.found) {
  57956. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  57957. if (f >= 0.0 && f <= 1.0) {
  57958. t = lowestRoot.root;
  57959. found = true;
  57960. this._edge.scaleInPlace(f);
  57961. p2.addToRef(this._edge, this._collisionPoint);
  57962. }
  57963. }
  57964. p1.subtractToRef(p3, this._edge);
  57965. p3.subtractToRef(this._basePoint, this._baseToVertex);
  57966. edgeSquaredLength = this._edge.lengthSquared();
  57967. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  57968. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  57969. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  57970. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  57971. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  57972. lowestRoot = getLowestRoot(a, b, c, t);
  57973. if (lowestRoot.found) {
  57974. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  57975. if (f >= 0.0 && f <= 1.0) {
  57976. t = lowestRoot.root;
  57977. found = true;
  57978. this._edge.scaleInPlace(f);
  57979. p3.addToRef(this._edge, this._collisionPoint);
  57980. }
  57981. }
  57982. }
  57983. if (found) {
  57984. var distToCollision = t * this._velocity.length();
  57985. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  57986. if (!this.intersectionPoint) {
  57987. this.intersectionPoint = this._collisionPoint.clone();
  57988. }
  57989. else {
  57990. this.intersectionPoint.copyFrom(this._collisionPoint);
  57991. }
  57992. this._nearestDistance = distToCollision;
  57993. this.collisionFound = true;
  57994. }
  57995. }
  57996. };
  57997. /** @hidden */
  57998. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  57999. for (var i = indexStart; i < indexEnd; i += 3) {
  58000. var p1 = pts[indices[i] - decal];
  58001. var p2 = pts[indices[i + 1] - decal];
  58002. var p3 = pts[indices[i + 2] - decal];
  58003. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  58004. }
  58005. };
  58006. /** @hidden */
  58007. Collider.prototype._getResponse = function (pos, vel) {
  58008. pos.addToRef(vel, this._destinationPoint);
  58009. vel.scaleInPlace((this._nearestDistance / vel.length()));
  58010. this._basePoint.addToRef(vel, pos);
  58011. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  58012. this._slidePlaneNormal.normalize();
  58013. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  58014. pos.addInPlace(this._displacementVector);
  58015. this.intersectionPoint.addInPlace(this._displacementVector);
  58016. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  58017. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  58018. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  58019. };
  58020. return Collider;
  58021. }());
  58022. BABYLON.Collider = Collider;
  58023. })(BABYLON || (BABYLON = {}));
  58024. //# sourceMappingURL=babylon.collider.js.map
  58025. var BABYLON;
  58026. (function (BABYLON) {
  58027. //WebWorker code will be inserted to this variable.
  58028. /** @hidden */
  58029. BABYLON.CollisionWorker = "";
  58030. /** Defines supported task for worker process */
  58031. var WorkerTaskType;
  58032. (function (WorkerTaskType) {
  58033. /** Initialization */
  58034. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  58035. /** Update of geometry */
  58036. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  58037. /** Evaluate collision */
  58038. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  58039. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  58040. /** Defines kind of replies returned by worker */
  58041. var WorkerReplyType;
  58042. (function (WorkerReplyType) {
  58043. /** Success */
  58044. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  58045. /** Unkown error */
  58046. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  58047. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  58048. /** @hidden */
  58049. var CollisionCoordinatorWorker = /** @class */ (function () {
  58050. function CollisionCoordinatorWorker() {
  58051. var _this = this;
  58052. this._scaledPosition = BABYLON.Vector3.Zero();
  58053. this._scaledVelocity = BABYLON.Vector3.Zero();
  58054. this.onMeshUpdated = function (transformNode) {
  58055. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  58056. };
  58057. this.onGeometryUpdated = function (geometry) {
  58058. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  58059. };
  58060. this._afterRender = function () {
  58061. if (!_this._init) {
  58062. return;
  58063. }
  58064. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  58065. return;
  58066. }
  58067. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  58068. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  58069. if (_this._runningUpdated > 4) {
  58070. return;
  58071. }
  58072. ++_this._runningUpdated;
  58073. var payload = {
  58074. updatedMeshes: _this._addUpdateMeshesList,
  58075. updatedGeometries: _this._addUpdateGeometriesList,
  58076. removedGeometries: _this._toRemoveGeometryArray,
  58077. removedMeshes: _this._toRemoveMeshesArray
  58078. };
  58079. var message = {
  58080. payload: payload,
  58081. taskType: WorkerTaskType.UPDATE
  58082. };
  58083. var serializable = [];
  58084. for (var id in payload.updatedGeometries) {
  58085. if (payload.updatedGeometries.hasOwnProperty(id)) {
  58086. //prepare transferables
  58087. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  58088. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  58089. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  58090. }
  58091. }
  58092. _this._worker.postMessage(message, serializable);
  58093. _this._addUpdateMeshesList = {};
  58094. _this._addUpdateGeometriesList = {};
  58095. _this._toRemoveGeometryArray = [];
  58096. _this._toRemoveMeshesArray = [];
  58097. };
  58098. this._onMessageFromWorker = function (e) {
  58099. var returnData = e.data;
  58100. if (returnData.error != WorkerReplyType.SUCCESS) {
  58101. //TODO what errors can be returned from the worker?
  58102. BABYLON.Tools.Warn("error returned from worker!");
  58103. return;
  58104. }
  58105. switch (returnData.taskType) {
  58106. case WorkerTaskType.INIT:
  58107. _this._init = true;
  58108. //Update the worked with ALL of the scene's current state
  58109. _this._scene.meshes.forEach(function (mesh) {
  58110. _this.onMeshAdded(mesh);
  58111. });
  58112. _this._scene.getGeometries().forEach(function (geometry) {
  58113. _this.onGeometryAdded(geometry);
  58114. });
  58115. break;
  58116. case WorkerTaskType.UPDATE:
  58117. _this._runningUpdated--;
  58118. break;
  58119. case WorkerTaskType.COLLIDE:
  58120. var returnPayload = returnData.payload;
  58121. if (!_this._collisionsCallbackArray[returnPayload.collisionId]) {
  58122. return;
  58123. }
  58124. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  58125. if (callback) {
  58126. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  58127. if (mesh) {
  58128. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  58129. }
  58130. }
  58131. //cleanup
  58132. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  58133. break;
  58134. }
  58135. };
  58136. this._collisionsCallbackArray = [];
  58137. this._init = false;
  58138. this._runningUpdated = 0;
  58139. this._addUpdateMeshesList = {};
  58140. this._addUpdateGeometriesList = {};
  58141. this._toRemoveGeometryArray = [];
  58142. this._toRemoveMeshesArray = [];
  58143. }
  58144. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  58145. if (!this._init) {
  58146. return;
  58147. }
  58148. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000]) {
  58149. return;
  58150. }
  58151. position.divideToRef(collider._radius, this._scaledPosition);
  58152. displacement.divideToRef(collider._radius, this._scaledVelocity);
  58153. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  58154. var payload = {
  58155. collider: {
  58156. position: this._scaledPosition.asArray(),
  58157. velocity: this._scaledVelocity.asArray(),
  58158. radius: collider._radius.asArray()
  58159. },
  58160. collisionId: collisionIndex,
  58161. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  58162. maximumRetry: maximumRetry
  58163. };
  58164. var message = {
  58165. payload: payload,
  58166. taskType: WorkerTaskType.COLLIDE
  58167. };
  58168. this._worker.postMessage(message);
  58169. };
  58170. CollisionCoordinatorWorker.prototype.init = function (scene) {
  58171. this._scene = scene;
  58172. this._scene.registerAfterRender(this._afterRender);
  58173. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  58174. this._worker = new Worker(workerUrl);
  58175. this._worker.onmessage = this._onMessageFromWorker;
  58176. var message = {
  58177. payload: {},
  58178. taskType: WorkerTaskType.INIT
  58179. };
  58180. this._worker.postMessage(message);
  58181. };
  58182. CollisionCoordinatorWorker.prototype.destroy = function () {
  58183. this._scene.unregisterAfterRender(this._afterRender);
  58184. this._worker.terminate();
  58185. };
  58186. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  58187. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  58188. this.onMeshUpdated(mesh);
  58189. };
  58190. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  58191. this._toRemoveMeshesArray.push(mesh.uniqueId);
  58192. };
  58193. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  58194. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  58195. geometry.onGeometryUpdated = this.onGeometryUpdated;
  58196. this.onGeometryUpdated(geometry);
  58197. };
  58198. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  58199. this._toRemoveGeometryArray.push(geometry.id);
  58200. };
  58201. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  58202. var submeshes = [];
  58203. if (mesh.subMeshes) {
  58204. submeshes = mesh.subMeshes.map(function (sm, idx) {
  58205. var boundingInfo = sm.getBoundingInfo();
  58206. return {
  58207. position: idx,
  58208. verticesStart: sm.verticesStart,
  58209. verticesCount: sm.verticesCount,
  58210. indexStart: sm.indexStart,
  58211. indexCount: sm.indexCount,
  58212. hasMaterial: !!sm.getMaterial(),
  58213. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  58214. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  58215. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  58216. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  58217. };
  58218. });
  58219. }
  58220. var geometryId = null;
  58221. if (mesh instanceof BABYLON.Mesh) {
  58222. var geometry = mesh.geometry;
  58223. geometryId = geometry ? geometry.id : null;
  58224. }
  58225. else if (mesh instanceof BABYLON.InstancedMesh) {
  58226. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  58227. geometryId = geometry ? geometry.id : null;
  58228. }
  58229. var boundingInfo = mesh.getBoundingInfo();
  58230. return {
  58231. uniqueId: mesh.uniqueId,
  58232. id: mesh.id,
  58233. name: mesh.name,
  58234. geometryId: geometryId,
  58235. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  58236. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  58237. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  58238. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  58239. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  58240. subMeshes: submeshes,
  58241. checkCollisions: mesh.checkCollisions
  58242. };
  58243. };
  58244. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  58245. return {
  58246. id: geometry.id,
  58247. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  58248. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  58249. indices: new Uint32Array(geometry.getIndices() || []),
  58250. };
  58251. };
  58252. return CollisionCoordinatorWorker;
  58253. }());
  58254. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  58255. /** @hidden */
  58256. var CollisionCoordinatorLegacy = /** @class */ (function () {
  58257. function CollisionCoordinatorLegacy() {
  58258. this._scaledPosition = BABYLON.Vector3.Zero();
  58259. this._scaledVelocity = BABYLON.Vector3.Zero();
  58260. this._finalPosition = BABYLON.Vector3.Zero();
  58261. }
  58262. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  58263. position.divideToRef(collider._radius, this._scaledPosition);
  58264. displacement.divideToRef(collider._radius, this._scaledVelocity);
  58265. collider.collidedMesh = null;
  58266. collider._retry = 0;
  58267. collider._initialVelocity = this._scaledVelocity;
  58268. collider._initialPosition = this._scaledPosition;
  58269. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  58270. this._finalPosition.multiplyInPlace(collider._radius);
  58271. //run the callback
  58272. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  58273. };
  58274. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  58275. this._scene = scene;
  58276. };
  58277. CollisionCoordinatorLegacy.prototype.destroy = function () {
  58278. //Legacy need no destruction method.
  58279. };
  58280. //No update in legacy mode
  58281. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  58282. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  58283. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  58284. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  58285. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  58286. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  58287. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  58288. if (excludedMesh === void 0) { excludedMesh = null; }
  58289. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  58290. if (collider._retry >= maximumRetry) {
  58291. finalPosition.copyFrom(position);
  58292. return;
  58293. }
  58294. // Check if this is a mesh else camera or -1
  58295. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  58296. collider._initialize(position, velocity, closeDistance);
  58297. // Check all meshes
  58298. for (var index = 0; index < this._scene.meshes.length; index++) {
  58299. var mesh = this._scene.meshes[index];
  58300. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  58301. mesh._checkCollision(collider);
  58302. }
  58303. }
  58304. if (!collider.collisionFound) {
  58305. position.addToRef(velocity, finalPosition);
  58306. return;
  58307. }
  58308. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  58309. collider._getResponse(position, velocity);
  58310. }
  58311. if (velocity.length() <= closeDistance) {
  58312. finalPosition.copyFrom(position);
  58313. return;
  58314. }
  58315. collider._retry++;
  58316. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  58317. };
  58318. return CollisionCoordinatorLegacy;
  58319. }());
  58320. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  58321. })(BABYLON || (BABYLON = {}));
  58322. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  58323. var BABYLON;
  58324. (function (BABYLON) {
  58325. /**
  58326. * A particle represents one of the element emitted by a particle system.
  58327. * This is mainly define by its coordinates, direction, velocity and age.
  58328. */
  58329. var Particle = /** @class */ (function () {
  58330. /**
  58331. * Creates a new instance Particle
  58332. * @param particleSystem the particle system the particle belongs to
  58333. */
  58334. function Particle(
  58335. /**
  58336. * The particle system the particle belongs to.
  58337. */
  58338. particleSystem) {
  58339. this.particleSystem = particleSystem;
  58340. /**
  58341. * The world position of the particle in the scene.
  58342. */
  58343. this.position = BABYLON.Vector3.Zero();
  58344. /**
  58345. * The world direction of the particle in the scene.
  58346. */
  58347. this.direction = BABYLON.Vector3.Zero();
  58348. /**
  58349. * The color of the particle.
  58350. */
  58351. this.color = new BABYLON.Color4(0, 0, 0, 0);
  58352. /**
  58353. * The color change of the particle per step.
  58354. */
  58355. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  58356. /**
  58357. * Defines how long will the life of the particle be.
  58358. */
  58359. this.lifeTime = 1.0;
  58360. /**
  58361. * The current age of the particle.
  58362. */
  58363. this.age = 0;
  58364. /**
  58365. * The current size of the particle.
  58366. */
  58367. this.size = 0;
  58368. /**
  58369. * The current scale of the particle.
  58370. */
  58371. this.scale = new BABYLON.Vector2(1, 1);
  58372. /**
  58373. * The current angle of the particle.
  58374. */
  58375. this.angle = 0;
  58376. /**
  58377. * Defines how fast is the angle changing.
  58378. */
  58379. this.angularSpeed = 0;
  58380. /**
  58381. * Defines the cell index used by the particle to be rendered from a sprite.
  58382. */
  58383. this.cellIndex = 0;
  58384. /** @hidden */
  58385. this._attachedSubEmitters = null;
  58386. /** @hidden */
  58387. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  58388. /** @hidden */
  58389. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  58390. /** @hidden */
  58391. this._currentSize1 = 0;
  58392. /** @hidden */
  58393. this._currentSize2 = 0;
  58394. /** @hidden */
  58395. this._currentAngularSpeed1 = 0;
  58396. /** @hidden */
  58397. this._currentAngularSpeed2 = 0;
  58398. /** @hidden */
  58399. this._currentVelocity1 = 0;
  58400. /** @hidden */
  58401. this._currentVelocity2 = 0;
  58402. /** @hidden */
  58403. this._currentLimitVelocity1 = 0;
  58404. /** @hidden */
  58405. this._currentLimitVelocity2 = 0;
  58406. /** @hidden */
  58407. this._currentDrag1 = 0;
  58408. /** @hidden */
  58409. this._currentDrag2 = 0;
  58410. this.id = Particle._Count++;
  58411. if (!this.particleSystem.isAnimationSheetEnabled) {
  58412. return;
  58413. }
  58414. this.updateCellInfoFromSystem();
  58415. }
  58416. Particle.prototype.updateCellInfoFromSystem = function () {
  58417. this.cellIndex = this.particleSystem.startSpriteCellID;
  58418. };
  58419. /**
  58420. * Defines how the sprite cell index is updated for the particle
  58421. */
  58422. Particle.prototype.updateCellIndex = function () {
  58423. var offsetAge = this.age;
  58424. var changeSpeed = this.particleSystem.spriteCellChangeSpeed;
  58425. if (this.particleSystem.spriteRandomStartCell) {
  58426. if (this._randomCellOffset === undefined) {
  58427. this._randomCellOffset = Math.random() * this.lifeTime;
  58428. }
  58429. if (changeSpeed === 0) { // Special case when speed = 0 meaning we want to stay on initial cell
  58430. changeSpeed = 1;
  58431. offsetAge = this._randomCellOffset;
  58432. }
  58433. else {
  58434. offsetAge += this._randomCellOffset;
  58435. }
  58436. }
  58437. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  58438. var ratio = BABYLON.Scalar.Clamp(((offsetAge * changeSpeed) % this.lifeTime) / this.lifeTime);
  58439. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  58440. };
  58441. /** @hidden */
  58442. Particle.prototype._inheritParticleInfoToSubEmitter = function (subEmitter) {
  58443. if (subEmitter.particleSystem.emitter.position) {
  58444. var emitterMesh = subEmitter.particleSystem.emitter;
  58445. emitterMesh.position.copyFrom(this.position);
  58446. if (subEmitter.inheritDirection) {
  58447. emitterMesh.position.subtractToRef(this.direction, BABYLON.Tmp.Vector3[0]);
  58448. // Look at using Y as forward
  58449. emitterMesh.lookAt(BABYLON.Tmp.Vector3[0], 0, Math.PI / 2);
  58450. }
  58451. }
  58452. else {
  58453. var emitterPosition = subEmitter.particleSystem.emitter;
  58454. emitterPosition.copyFrom(this.position);
  58455. }
  58456. // Set inheritedVelocityOffset to be used when new particles are created
  58457. this.direction.scaleToRef(subEmitter.inheritedVelocityAmount / 2, BABYLON.Tmp.Vector3[0]);
  58458. subEmitter.particleSystem._inheritedVelocityOffset.copyFrom(BABYLON.Tmp.Vector3[0]);
  58459. };
  58460. /** @hidden */
  58461. Particle.prototype._inheritParticleInfoToSubEmitters = function () {
  58462. var _this = this;
  58463. if (this._attachedSubEmitters && this._attachedSubEmitters.length > 0) {
  58464. this._attachedSubEmitters.forEach(function (subEmitter) {
  58465. _this._inheritParticleInfoToSubEmitter(subEmitter);
  58466. });
  58467. }
  58468. };
  58469. /** @hidden */
  58470. Particle.prototype._reset = function () {
  58471. this.age = 0;
  58472. this._currentColorGradient = null;
  58473. this._currentSizeGradient = null;
  58474. this._currentAngularSpeedGradient = null;
  58475. this._currentVelocityGradient = null;
  58476. this._currentLimitVelocityGradient = null;
  58477. this._currentDragGradient = null;
  58478. this.cellIndex = this.particleSystem.startSpriteCellID;
  58479. this._randomCellOffset = undefined;
  58480. };
  58481. /**
  58482. * Copy the properties of particle to another one.
  58483. * @param other the particle to copy the information to.
  58484. */
  58485. Particle.prototype.copyTo = function (other) {
  58486. other.position.copyFrom(this.position);
  58487. if (this._initialDirection) {
  58488. if (other._initialDirection) {
  58489. other._initialDirection.copyFrom(this._initialDirection);
  58490. }
  58491. else {
  58492. other._initialDirection = this._initialDirection.clone();
  58493. }
  58494. }
  58495. else {
  58496. other._initialDirection = null;
  58497. }
  58498. other.direction.copyFrom(this.direction);
  58499. other.color.copyFrom(this.color);
  58500. other.colorStep.copyFrom(this.colorStep);
  58501. other.lifeTime = this.lifeTime;
  58502. other.age = this.age;
  58503. other._randomCellOffset = this._randomCellOffset;
  58504. other.size = this.size;
  58505. other.scale.copyFrom(this.scale);
  58506. other.angle = this.angle;
  58507. other.angularSpeed = this.angularSpeed;
  58508. other.particleSystem = this.particleSystem;
  58509. other.cellIndex = this.cellIndex;
  58510. other.id = this.id;
  58511. other._attachedSubEmitters = this._attachedSubEmitters;
  58512. if (this._currentColorGradient) {
  58513. other._currentColorGradient = this._currentColorGradient;
  58514. other._currentColor1.copyFrom(this._currentColor1);
  58515. other._currentColor2.copyFrom(this._currentColor2);
  58516. }
  58517. if (this._currentSizeGradient) {
  58518. other._currentSizeGradient = this._currentSizeGradient;
  58519. other._currentSize1 = this._currentSize1;
  58520. other._currentSize2 = this._currentSize2;
  58521. }
  58522. if (this._currentAngularSpeedGradient) {
  58523. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  58524. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  58525. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  58526. }
  58527. if (this._currentVelocityGradient) {
  58528. other._currentVelocityGradient = this._currentVelocityGradient;
  58529. other._currentVelocity1 = this._currentVelocity1;
  58530. other._currentVelocity2 = this._currentVelocity2;
  58531. }
  58532. if (this._currentLimitVelocityGradient) {
  58533. other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
  58534. other._currentLimitVelocity1 = this._currentLimitVelocity1;
  58535. other._currentLimitVelocity2 = this._currentLimitVelocity2;
  58536. }
  58537. if (this._currentDragGradient) {
  58538. other._currentDragGradient = this._currentDragGradient;
  58539. other._currentDrag1 = this._currentDrag1;
  58540. other._currentDrag2 = this._currentDrag2;
  58541. }
  58542. if (this.particleSystem.isAnimationSheetEnabled) {
  58543. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  58544. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  58545. }
  58546. if (this.particleSystem.useRampGradients) {
  58547. other.remapData.copyFrom(this.remapData);
  58548. }
  58549. if (this._randomNoiseCoordinates1) {
  58550. if (other._randomNoiseCoordinates1) {
  58551. other._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1);
  58552. other._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2);
  58553. }
  58554. else {
  58555. other._randomNoiseCoordinates1 = this._randomNoiseCoordinates1.clone();
  58556. other._randomNoiseCoordinates2 = this._randomNoiseCoordinates2.clone();
  58557. }
  58558. }
  58559. };
  58560. Particle._Count = 0;
  58561. return Particle;
  58562. }());
  58563. BABYLON.Particle = Particle;
  58564. })(BABYLON || (BABYLON = {}));
  58565. //# sourceMappingURL=babylon.particle.js.map
  58566. var BABYLON;
  58567. (function (BABYLON) {
  58568. /**
  58569. * This represents the base class for particle system in Babylon.
  58570. * 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.
  58571. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  58572. * @example https://doc.babylonjs.com/babylon101/particles
  58573. */
  58574. var BaseParticleSystem = /** @class */ (function () {
  58575. /**
  58576. * Instantiates a particle system.
  58577. * 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.
  58578. * @param name The name of the particle system
  58579. */
  58580. function BaseParticleSystem(name) {
  58581. /**
  58582. * List of animations used by the particle system.
  58583. */
  58584. this.animations = [];
  58585. /**
  58586. * The rendering group used by the Particle system to chose when to render.
  58587. */
  58588. this.renderingGroupId = 0;
  58589. /**
  58590. * The emitter represents the Mesh or position we are attaching the particle system to.
  58591. */
  58592. this.emitter = null;
  58593. /**
  58594. * The maximum number of particles to emit per frame
  58595. */
  58596. this.emitRate = 10;
  58597. /**
  58598. * If you want to launch only a few particles at once, that can be done, as well.
  58599. */
  58600. this.manualEmitCount = -1;
  58601. /**
  58602. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  58603. */
  58604. this.updateSpeed = 0.01;
  58605. /**
  58606. * The amount of time the particle system is running (depends of the overall update speed).
  58607. */
  58608. this.targetStopDuration = 0;
  58609. /**
  58610. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  58611. */
  58612. this.disposeOnStop = false;
  58613. /**
  58614. * Minimum power of emitting particles.
  58615. */
  58616. this.minEmitPower = 1;
  58617. /**
  58618. * Maximum power of emitting particles.
  58619. */
  58620. this.maxEmitPower = 1;
  58621. /**
  58622. * Minimum life time of emitting particles.
  58623. */
  58624. this.minLifeTime = 1;
  58625. /**
  58626. * Maximum life time of emitting particles.
  58627. */
  58628. this.maxLifeTime = 1;
  58629. /**
  58630. * Minimum Size of emitting particles.
  58631. */
  58632. this.minSize = 1;
  58633. /**
  58634. * Maximum Size of emitting particles.
  58635. */
  58636. this.maxSize = 1;
  58637. /**
  58638. * Minimum scale of emitting particles on X axis.
  58639. */
  58640. this.minScaleX = 1;
  58641. /**
  58642. * Maximum scale of emitting particles on X axis.
  58643. */
  58644. this.maxScaleX = 1;
  58645. /**
  58646. * Minimum scale of emitting particles on Y axis.
  58647. */
  58648. this.minScaleY = 1;
  58649. /**
  58650. * Maximum scale of emitting particles on Y axis.
  58651. */
  58652. this.maxScaleY = 1;
  58653. /**
  58654. * Gets or sets the minimal initial rotation in radians.
  58655. */
  58656. this.minInitialRotation = 0;
  58657. /**
  58658. * Gets or sets the maximal initial rotation in radians.
  58659. */
  58660. this.maxInitialRotation = 0;
  58661. /**
  58662. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  58663. */
  58664. this.minAngularSpeed = 0;
  58665. /**
  58666. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  58667. */
  58668. this.maxAngularSpeed = 0;
  58669. /**
  58670. * The layer mask we are rendering the particles through.
  58671. */
  58672. this.layerMask = 0x0FFFFFFF;
  58673. /**
  58674. * This can help using your own shader to render the particle system.
  58675. * The according effect will be created
  58676. */
  58677. this.customShader = null;
  58678. /**
  58679. * By default particle system starts as soon as they are created. This prevents the
  58680. * automatic start to happen and let you decide when to start emitting particles.
  58681. */
  58682. this.preventAutoStart = false;
  58683. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  58684. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  58685. /**
  58686. * Callback triggered when the particle animation is ending.
  58687. */
  58688. this.onAnimationEnd = null;
  58689. /**
  58690. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  58691. */
  58692. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  58693. /**
  58694. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  58695. * to override the particles.
  58696. */
  58697. this.forceDepthWrite = false;
  58698. /** 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 */
  58699. this.preWarmCycles = 0;
  58700. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  58701. this.preWarmStepOffset = 1;
  58702. /**
  58703. * 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)
  58704. */
  58705. this.spriteCellChangeSpeed = 1;
  58706. /**
  58707. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  58708. */
  58709. this.startSpriteCellID = 0;
  58710. /**
  58711. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  58712. */
  58713. this.endSpriteCellID = 0;
  58714. /**
  58715. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  58716. */
  58717. this.spriteCellWidth = 0;
  58718. /**
  58719. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  58720. */
  58721. this.spriteCellHeight = 0;
  58722. /**
  58723. * This allows the system to random pick the start cell ID between startSpriteCellID and endSpriteCellID
  58724. */
  58725. this.spriteRandomStartCell = false;
  58726. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  58727. this.translationPivot = new BABYLON.Vector2(0, 0);
  58728. /**
  58729. * Gets or sets a boolean indicating that hosted animations (in the system.animations array) must be started when system.start() is called
  58730. */
  58731. this.beginAnimationOnStart = false;
  58732. /**
  58733. * Gets or sets the frame to start the animation from when beginAnimationOnStart is true
  58734. */
  58735. this.beginAnimationFrom = 0;
  58736. /**
  58737. * Gets or sets the frame to end the animation on when beginAnimationOnStart is true
  58738. */
  58739. this.beginAnimationTo = 60;
  58740. /**
  58741. * Gets or sets a boolean indicating if animations must loop when beginAnimationOnStart is true
  58742. */
  58743. this.beginAnimationLoop = false;
  58744. /**
  58745. * You can use gravity if you want to give an orientation to your particles.
  58746. */
  58747. this.gravity = BABYLON.Vector3.Zero();
  58748. this._colorGradients = null;
  58749. this._sizeGradients = null;
  58750. this._lifeTimeGradients = null;
  58751. this._angularSpeedGradients = null;
  58752. this._velocityGradients = null;
  58753. this._limitVelocityGradients = null;
  58754. this._dragGradients = null;
  58755. this._emitRateGradients = null;
  58756. this._startSizeGradients = null;
  58757. this._rampGradients = null;
  58758. this._colorRemapGradients = null;
  58759. this._alphaRemapGradients = null;
  58760. /**
  58761. * Defines the delay in milliseconds before starting the system (0 by default)
  58762. */
  58763. this.startDelay = 0;
  58764. /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */
  58765. this.limitVelocityDamping = 0.4;
  58766. /**
  58767. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  58768. */
  58769. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58770. /**
  58771. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  58772. */
  58773. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58774. /**
  58775. * Color the particle will have at the end of its lifetime
  58776. */
  58777. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  58778. /**
  58779. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  58780. */
  58781. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58782. /** @hidden */
  58783. this._isSubEmitter = false;
  58784. /**
  58785. * Gets or sets the billboard mode to use when isBillboardBased = true.
  58786. * Value can be: ParticleSystem.BILLBOARDMODE_ALL, ParticleSystem.BILLBOARDMODE_Y, ParticleSystem.BILLBOARDMODE_STRETCHED
  58787. */
  58788. this.billboardMode = BABYLON.ParticleSystem.BILLBOARDMODE_ALL;
  58789. this._isBillboardBased = true;
  58790. /**
  58791. * Local cache of defines for image processing.
  58792. */
  58793. this._imageProcessingConfigurationDefines = new BABYLON.ImageProcessingConfigurationDefines();
  58794. this.id = name;
  58795. this.name = name;
  58796. }
  58797. Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
  58798. /**
  58799. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  58800. */
  58801. get: function () {
  58802. return this._isAnimationSheetEnabled;
  58803. },
  58804. set: function (value) {
  58805. if (this._isAnimationSheetEnabled == value) {
  58806. return;
  58807. }
  58808. this._isAnimationSheetEnabled = value;
  58809. this._reset();
  58810. },
  58811. enumerable: true,
  58812. configurable: true
  58813. });
  58814. /**
  58815. * Get hosting scene
  58816. * @returns the scene
  58817. */
  58818. BaseParticleSystem.prototype.getScene = function () {
  58819. return this._scene;
  58820. };
  58821. BaseParticleSystem.prototype._hasTargetStopDurationDependantGradient = function () {
  58822. return (this._startSizeGradients && this._startSizeGradients.length > 0)
  58823. || (this._emitRateGradients && this._emitRateGradients.length > 0)
  58824. || (this._lifeTimeGradients && this._lifeTimeGradients.length > 0);
  58825. };
  58826. /**
  58827. * Gets the current list of drag gradients.
  58828. * You must use addDragGradient and removeDragGradient to udpate this list
  58829. * @returns the list of drag gradients
  58830. */
  58831. BaseParticleSystem.prototype.getDragGradients = function () {
  58832. return this._dragGradients;
  58833. };
  58834. /**
  58835. * Gets the current list of limit velocity gradients.
  58836. * You must use addLimitVelocityGradient and removeLimitVelocityGradient to udpate this list
  58837. * @returns the list of limit velocity gradients
  58838. */
  58839. BaseParticleSystem.prototype.getLimitVelocityGradients = function () {
  58840. return this._limitVelocityGradients;
  58841. };
  58842. /**
  58843. * Gets the current list of color gradients.
  58844. * You must use addColorGradient and removeColorGradient to udpate this list
  58845. * @returns the list of color gradients
  58846. */
  58847. BaseParticleSystem.prototype.getColorGradients = function () {
  58848. return this._colorGradients;
  58849. };
  58850. /**
  58851. * Gets the current list of size gradients.
  58852. * You must use addSizeGradient and removeSizeGradient to udpate this list
  58853. * @returns the list of size gradients
  58854. */
  58855. BaseParticleSystem.prototype.getSizeGradients = function () {
  58856. return this._sizeGradients;
  58857. };
  58858. /**
  58859. * Gets the current list of color remap gradients.
  58860. * You must use addColorRemapGradient and removeColorRemapGradient to udpate this list
  58861. * @returns the list of color remap gradients
  58862. */
  58863. BaseParticleSystem.prototype.getColorRemapGradients = function () {
  58864. return this._colorRemapGradients;
  58865. };
  58866. /**
  58867. * Gets the current list of alpha remap gradients.
  58868. * You must use addAlphaRemapGradient and removeAlphaRemapGradient to udpate this list
  58869. * @returns the list of alpha remap gradients
  58870. */
  58871. BaseParticleSystem.prototype.getAlphaRemapGradients = function () {
  58872. return this._alphaRemapGradients;
  58873. };
  58874. /**
  58875. * Gets the current list of life time gradients.
  58876. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  58877. * @returns the list of life time gradients
  58878. */
  58879. BaseParticleSystem.prototype.getLifeTimeGradients = function () {
  58880. return this._lifeTimeGradients;
  58881. };
  58882. /**
  58883. * Gets the current list of angular speed gradients.
  58884. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  58885. * @returns the list of angular speed gradients
  58886. */
  58887. BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
  58888. return this._angularSpeedGradients;
  58889. };
  58890. /**
  58891. * Gets the current list of velocity gradients.
  58892. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  58893. * @returns the list of velocity gradients
  58894. */
  58895. BaseParticleSystem.prototype.getVelocityGradients = function () {
  58896. return this._velocityGradients;
  58897. };
  58898. /**
  58899. * Gets the current list of start size gradients.
  58900. * You must use addStartSizeGradient and removeStartSizeGradient to udpate this list
  58901. * @returns the list of start size gradients
  58902. */
  58903. BaseParticleSystem.prototype.getStartSizeGradients = function () {
  58904. return this._startSizeGradients;
  58905. };
  58906. /**
  58907. * Gets the current list of emit rate gradients.
  58908. * You must use addEmitRateGradient and removeEmitRateGradient to udpate this list
  58909. * @returns the list of emit rate gradients
  58910. */
  58911. BaseParticleSystem.prototype.getEmitRateGradients = function () {
  58912. return this._emitRateGradients;
  58913. };
  58914. Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
  58915. /**
  58916. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58917. * This only works when particleEmitterTyps is a BoxParticleEmitter
  58918. */
  58919. get: function () {
  58920. if (this.particleEmitterType.direction1) {
  58921. return this.particleEmitterType.direction1;
  58922. }
  58923. return BABYLON.Vector3.Zero();
  58924. },
  58925. set: function (value) {
  58926. if (this.particleEmitterType.direction1) {
  58927. this.particleEmitterType.direction1 = value;
  58928. }
  58929. },
  58930. enumerable: true,
  58931. configurable: true
  58932. });
  58933. Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
  58934. /**
  58935. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58936. * This only works when particleEmitterTyps is a BoxParticleEmitter
  58937. */
  58938. get: function () {
  58939. if (this.particleEmitterType.direction2) {
  58940. return this.particleEmitterType.direction2;
  58941. }
  58942. return BABYLON.Vector3.Zero();
  58943. },
  58944. set: function (value) {
  58945. if (this.particleEmitterType.direction2) {
  58946. this.particleEmitterType.direction2 = value;
  58947. }
  58948. },
  58949. enumerable: true,
  58950. configurable: true
  58951. });
  58952. Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
  58953. /**
  58954. * 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.
  58955. * This only works when particleEmitterTyps is a BoxParticleEmitter
  58956. */
  58957. get: function () {
  58958. if (this.particleEmitterType.minEmitBox) {
  58959. return this.particleEmitterType.minEmitBox;
  58960. }
  58961. return BABYLON.Vector3.Zero();
  58962. },
  58963. set: function (value) {
  58964. if (this.particleEmitterType.minEmitBox) {
  58965. this.particleEmitterType.minEmitBox = value;
  58966. }
  58967. },
  58968. enumerable: true,
  58969. configurable: true
  58970. });
  58971. Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
  58972. /**
  58973. * 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.
  58974. * This only works when particleEmitterTyps is a BoxParticleEmitter
  58975. */
  58976. get: function () {
  58977. if (this.particleEmitterType.maxEmitBox) {
  58978. return this.particleEmitterType.maxEmitBox;
  58979. }
  58980. return BABYLON.Vector3.Zero();
  58981. },
  58982. set: function (value) {
  58983. if (this.particleEmitterType.maxEmitBox) {
  58984. this.particleEmitterType.maxEmitBox = value;
  58985. }
  58986. },
  58987. enumerable: true,
  58988. configurable: true
  58989. });
  58990. Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
  58991. /**
  58992. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  58993. */
  58994. get: function () {
  58995. return this._isBillboardBased;
  58996. },
  58997. set: function (value) {
  58998. if (this._isBillboardBased === value) {
  58999. return;
  59000. }
  59001. this._isBillboardBased = value;
  59002. this._reset();
  59003. },
  59004. enumerable: true,
  59005. configurable: true
  59006. });
  59007. Object.defineProperty(BaseParticleSystem.prototype, "imageProcessingConfiguration", {
  59008. /**
  59009. * Gets the image processing configuration used either in this material.
  59010. */
  59011. get: function () {
  59012. return this._imageProcessingConfiguration;
  59013. },
  59014. /**
  59015. * Sets the Default image processing configuration used either in the this material.
  59016. *
  59017. * If sets to null, the scene one is in use.
  59018. */
  59019. set: function (value) {
  59020. this._attachImageProcessingConfiguration(value);
  59021. },
  59022. enumerable: true,
  59023. configurable: true
  59024. });
  59025. /**
  59026. * Attaches a new image processing configuration to the Standard Material.
  59027. * @param configuration
  59028. */
  59029. BaseParticleSystem.prototype._attachImageProcessingConfiguration = function (configuration) {
  59030. if (configuration === this._imageProcessingConfiguration) {
  59031. return;
  59032. }
  59033. // Pick the scene configuration if needed.
  59034. if (!configuration) {
  59035. this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
  59036. }
  59037. else {
  59038. this._imageProcessingConfiguration = configuration;
  59039. }
  59040. };
  59041. /** @hidden */
  59042. BaseParticleSystem.prototype._reset = function () {
  59043. };
  59044. /** @hidden */
  59045. BaseParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  59046. if (!gradients) {
  59047. return this;
  59048. }
  59049. var index = 0;
  59050. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  59051. var valueGradient = gradients_1[_i];
  59052. if (valueGradient.gradient === gradient) {
  59053. gradients.splice(index, 1);
  59054. break;
  59055. }
  59056. index++;
  59057. }
  59058. if (texture) {
  59059. texture.dispose();
  59060. }
  59061. return this;
  59062. };
  59063. /**
  59064. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  59065. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  59066. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  59067. * @returns the emitter
  59068. */
  59069. BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  59070. var particleEmitter = new BABYLON.PointParticleEmitter();
  59071. particleEmitter.direction1 = direction1;
  59072. particleEmitter.direction2 = direction2;
  59073. this.particleEmitterType = particleEmitter;
  59074. return particleEmitter;
  59075. };
  59076. /**
  59077. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  59078. * @param radius The radius of the hemisphere to emit from
  59079. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  59080. * @returns the emitter
  59081. */
  59082. BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  59083. if (radius === void 0) { radius = 1; }
  59084. if (radiusRange === void 0) { radiusRange = 1; }
  59085. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  59086. this.particleEmitterType = particleEmitter;
  59087. return particleEmitter;
  59088. };
  59089. /**
  59090. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  59091. * @param radius The radius of the sphere to emit from
  59092. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  59093. * @returns the emitter
  59094. */
  59095. BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  59096. if (radius === void 0) { radius = 1; }
  59097. if (radiusRange === void 0) { radiusRange = 1; }
  59098. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  59099. this.particleEmitterType = particleEmitter;
  59100. return particleEmitter;
  59101. };
  59102. /**
  59103. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  59104. * @param radius The radius of the sphere to emit from
  59105. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  59106. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  59107. * @returns the emitter
  59108. */
  59109. BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  59110. if (radius === void 0) { radius = 1; }
  59111. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  59112. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  59113. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  59114. this.particleEmitterType = particleEmitter;
  59115. return particleEmitter;
  59116. };
  59117. /**
  59118. * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position)
  59119. * @param radius The radius of the emission cylinder
  59120. * @param height The height of the emission cylinder
  59121. * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius
  59122. * @param directionRandomizer How much to randomize the particle direction [0-1]
  59123. * @returns the emitter
  59124. */
  59125. BaseParticleSystem.prototype.createCylinderEmitter = function (radius, height, radiusRange, directionRandomizer) {
  59126. if (radius === void 0) { radius = 1; }
  59127. if (height === void 0) { height = 1; }
  59128. if (radiusRange === void 0) { radiusRange = 1; }
  59129. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  59130. var particleEmitter = new BABYLON.CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer);
  59131. this.particleEmitterType = particleEmitter;
  59132. return particleEmitter;
  59133. };
  59134. /**
  59135. * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2)
  59136. * @param radius The radius of the cylinder to emit from
  59137. * @param height The height of the emission cylinder
  59138. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  59139. * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder
  59140. * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder
  59141. * @returns the emitter
  59142. */
  59143. BaseParticleSystem.prototype.createDirectedCylinderEmitter = function (radius, height, radiusRange, direction1, direction2) {
  59144. if (radius === void 0) { radius = 1; }
  59145. if (height === void 0) { height = 1; }
  59146. if (radiusRange === void 0) { radiusRange = 1; }
  59147. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  59148. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  59149. var particleEmitter = new BABYLON.CylinderDirectedParticleEmitter(radius, height, radiusRange, direction1, direction2);
  59150. this.particleEmitterType = particleEmitter;
  59151. return particleEmitter;
  59152. };
  59153. /**
  59154. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  59155. * @param radius The radius of the cone to emit from
  59156. * @param angle The base angle of the cone
  59157. * @returns the emitter
  59158. */
  59159. BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  59160. if (radius === void 0) { radius = 1; }
  59161. if (angle === void 0) { angle = Math.PI / 4; }
  59162. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  59163. this.particleEmitterType = particleEmitter;
  59164. return particleEmitter;
  59165. };
  59166. /**
  59167. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  59168. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  59169. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  59170. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  59171. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  59172. * @returns the emitter
  59173. */
  59174. BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  59175. var particleEmitter = new BABYLON.BoxParticleEmitter();
  59176. this.particleEmitterType = particleEmitter;
  59177. this.direction1 = direction1;
  59178. this.direction2 = direction2;
  59179. this.minEmitBox = minEmitBox;
  59180. this.maxEmitBox = maxEmitBox;
  59181. return particleEmitter;
  59182. };
  59183. /**
  59184. * Source color is added to the destination color without alpha affecting the result
  59185. */
  59186. BaseParticleSystem.BLENDMODE_ONEONE = 0;
  59187. /**
  59188. * Blend current color and particle color using particle’s alpha
  59189. */
  59190. BaseParticleSystem.BLENDMODE_STANDARD = 1;
  59191. /**
  59192. * Add current color and particle color multiplied by particle’s alpha
  59193. */
  59194. BaseParticleSystem.BLENDMODE_ADD = 2;
  59195. /**
  59196. * Multiply current color with particle color
  59197. */
  59198. BaseParticleSystem.BLENDMODE_MULTIPLY = 3;
  59199. /**
  59200. * Multiply current color with particle color then add current color and particle color multiplied by particle’s alpha
  59201. */
  59202. BaseParticleSystem.BLENDMODE_MULTIPLYADD = 4;
  59203. return BaseParticleSystem;
  59204. }());
  59205. BABYLON.BaseParticleSystem = BaseParticleSystem;
  59206. })(BABYLON || (BABYLON = {}));
  59207. //# sourceMappingURL=babylon.baseParticleSystem.js.map
  59208. var BABYLON;
  59209. (function (BABYLON) {
  59210. /**
  59211. * This represents a particle system in Babylon.
  59212. * 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.
  59213. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  59214. * @example https://doc.babylonjs.com/babylon101/particles
  59215. */
  59216. var ParticleSystem = /** @class */ (function (_super) {
  59217. __extends(ParticleSystem, _super);
  59218. /**
  59219. * Instantiates a particle system.
  59220. * 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.
  59221. * @param name The name of the particle system
  59222. * @param capacity The max number of particles alive at the same time
  59223. * @param scene The scene the particle system belongs to
  59224. * @param customEffect a custom effect used to change the way particles are rendered by default
  59225. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  59226. * @param epsilon Offset used to render the particles
  59227. */
  59228. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  59229. if (customEffect === void 0) { customEffect = null; }
  59230. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  59231. if (epsilon === void 0) { epsilon = 0.01; }
  59232. var _this = _super.call(this, name) || this;
  59233. /**
  59234. * @hidden
  59235. */
  59236. _this._inheritedVelocityOffset = new BABYLON.Vector3();
  59237. /**
  59238. * An event triggered when the system is disposed
  59239. */
  59240. _this.onDisposeObservable = new BABYLON.Observable();
  59241. _this._particles = new Array();
  59242. _this._stockParticles = new Array();
  59243. _this._newPartsExcess = 0;
  59244. _this._vertexBuffers = {};
  59245. _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  59246. _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  59247. _this._scaledDirection = BABYLON.Vector3.Zero();
  59248. _this._scaledGravity = BABYLON.Vector3.Zero();
  59249. _this._currentRenderId = -1;
  59250. _this._useInstancing = false;
  59251. _this._started = false;
  59252. _this._stopped = false;
  59253. _this._actualFrame = 0;
  59254. /** @hidden */
  59255. _this._currentEmitRate1 = 0;
  59256. /** @hidden */
  59257. _this._currentEmitRate2 = 0;
  59258. /** @hidden */
  59259. _this._currentStartSize1 = 0;
  59260. /** @hidden */
  59261. _this._currentStartSize2 = 0;
  59262. _this._rawTextureWidth = 256;
  59263. _this._useRampGradients = false;
  59264. /**
  59265. * @hidden
  59266. * If the particle systems emitter should be disposed when the particle system is disposed
  59267. */
  59268. _this._disposeEmitterOnDispose = false;
  59269. // start of sub system methods
  59270. /**
  59271. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  59272. * Its lifetime will start back at 0.
  59273. */
  59274. _this.recycleParticle = function (particle) {
  59275. // move particle from activeParticle list to stock particles
  59276. var lastParticle = _this._particles.pop();
  59277. if (lastParticle !== particle) {
  59278. lastParticle.copyTo(particle);
  59279. }
  59280. _this._stockParticles.push(lastParticle);
  59281. };
  59282. _this._createParticle = function () {
  59283. var particle;
  59284. if (_this._stockParticles.length !== 0) {
  59285. particle = _this._stockParticles.pop();
  59286. particle._reset();
  59287. }
  59288. else {
  59289. particle = new BABYLON.Particle(_this);
  59290. }
  59291. // Attach emitters
  59292. if (_this._subEmitters && _this._subEmitters.length > 0) {
  59293. var subEmitters = _this._subEmitters[Math.floor(Math.random() * _this._subEmitters.length)];
  59294. particle._attachedSubEmitters = [];
  59295. subEmitters.forEach(function (subEmitter) {
  59296. if (subEmitter.type === BABYLON.SubEmitterType.ATTACHED) {
  59297. var newEmitter = subEmitter.clone();
  59298. particle._attachedSubEmitters.push(newEmitter);
  59299. newEmitter.particleSystem.start();
  59300. }
  59301. });
  59302. }
  59303. return particle;
  59304. };
  59305. _this._emitFromParticle = function (particle) {
  59306. if (!_this._subEmitters || _this._subEmitters.length === 0) {
  59307. return;
  59308. }
  59309. var templateIndex = Math.floor(Math.random() * _this._subEmitters.length);
  59310. _this._subEmitters[templateIndex].forEach(function (subEmitter) {
  59311. if (subEmitter.type === BABYLON.SubEmitterType.END) {
  59312. var subSystem = subEmitter.clone();
  59313. particle._inheritParticleInfoToSubEmitter(subSystem);
  59314. subSystem.particleSystem._rootParticleSystem = _this;
  59315. _this.activeSubSystems.push(subSystem.particleSystem);
  59316. subSystem.particleSystem.start();
  59317. }
  59318. });
  59319. };
  59320. _this._capacity = capacity;
  59321. _this._epsilon = epsilon;
  59322. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  59323. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  59324. // Setup the default processing configuration to the scene.
  59325. _this._attachImageProcessingConfiguration(null);
  59326. _this._customEffect = customEffect;
  59327. _this._scene.particleSystems.push(_this);
  59328. _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
  59329. _this._createIndexBuffer();
  59330. _this._createVertexBuffers();
  59331. // Default emitter type
  59332. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  59333. // Update
  59334. _this.updateFunction = function (particles) {
  59335. var noiseTextureSize = null;
  59336. var noiseTextureData = null;
  59337. if (_this.noiseTexture) { // We need to get texture data back to CPU
  59338. noiseTextureSize = _this.noiseTexture.getSize();
  59339. noiseTextureData = (_this.noiseTexture.getContent());
  59340. }
  59341. var _loop_1 = function () {
  59342. particle = particles[index];
  59343. var scaledUpdateSpeed = _this._scaledUpdateSpeed;
  59344. var previousAge = particle.age;
  59345. particle.age += scaledUpdateSpeed;
  59346. // Evaluate step to death
  59347. if (particle.age > particle.lifeTime) {
  59348. var diff = particle.age - previousAge;
  59349. var oldDiff = particle.lifeTime - previousAge;
  59350. scaledUpdateSpeed = (oldDiff * scaledUpdateSpeed) / diff;
  59351. particle.age = particle.lifeTime;
  59352. }
  59353. var ratio = particle.age / particle.lifeTime;
  59354. // Color
  59355. if (_this._colorGradients && _this._colorGradients.length > 0) {
  59356. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  59357. if (currentGradient !== particle._currentColorGradient) {
  59358. particle._currentColor1.copyFrom(particle._currentColor2);
  59359. nextGradient.getColorToRef(particle._currentColor2);
  59360. particle._currentColorGradient = currentGradient;
  59361. }
  59362. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  59363. });
  59364. }
  59365. else {
  59366. particle.colorStep.scaleToRef(scaledUpdateSpeed, _this._scaledColorStep);
  59367. particle.color.addInPlace(_this._scaledColorStep);
  59368. if (particle.color.a < 0) {
  59369. particle.color.a = 0;
  59370. }
  59371. }
  59372. // Angular speed
  59373. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  59374. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  59375. if (currentGradient !== particle._currentAngularSpeedGradient) {
  59376. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  59377. particle._currentAngularSpeed2 = nextGradient.getFactor();
  59378. particle._currentAngularSpeedGradient = currentGradient;
  59379. }
  59380. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  59381. });
  59382. }
  59383. particle.angle += particle.angularSpeed * scaledUpdateSpeed;
  59384. // Direction
  59385. var directionScale = scaledUpdateSpeed;
  59386. /// Velocity
  59387. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  59388. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  59389. if (currentGradient !== particle._currentVelocityGradient) {
  59390. particle._currentVelocity1 = particle._currentVelocity2;
  59391. particle._currentVelocity2 = nextGradient.getFactor();
  59392. particle._currentVelocityGradient = currentGradient;
  59393. }
  59394. directionScale *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  59395. });
  59396. }
  59397. particle.direction.scaleToRef(directionScale, _this._scaledDirection);
  59398. /// Limit velocity
  59399. if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
  59400. BABYLON.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function (currentGradient, nextGradient, scale) {
  59401. if (currentGradient !== particle._currentLimitVelocityGradient) {
  59402. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  59403. particle._currentLimitVelocity2 = nextGradient.getFactor();
  59404. particle._currentLimitVelocityGradient = currentGradient;
  59405. }
  59406. var limitVelocity = BABYLON.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  59407. var currentVelocity = particle.direction.length();
  59408. if (currentVelocity > limitVelocity) {
  59409. particle.direction.scaleInPlace(_this.limitVelocityDamping);
  59410. }
  59411. });
  59412. }
  59413. /// Drag
  59414. if (_this._dragGradients && _this._dragGradients.length > 0) {
  59415. BABYLON.Tools.GetCurrentGradient(ratio, _this._dragGradients, function (currentGradient, nextGradient, scale) {
  59416. if (currentGradient !== particle._currentDragGradient) {
  59417. particle._currentDrag1 = particle._currentDrag2;
  59418. particle._currentDrag2 = nextGradient.getFactor();
  59419. particle._currentDragGradient = currentGradient;
  59420. }
  59421. var drag = BABYLON.Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);
  59422. _this._scaledDirection.scaleInPlace(1.0 - drag);
  59423. });
  59424. }
  59425. particle.position.addInPlace(_this._scaledDirection);
  59426. // Noise
  59427. if (noiseTextureData && noiseTextureSize) {
  59428. var fetchedColorR = _this._fetchR(particle._randomNoiseCoordinates1.x, particle._randomNoiseCoordinates1.y, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  59429. var fetchedColorG = _this._fetchR(particle._randomNoiseCoordinates1.z, particle._randomNoiseCoordinates2.x, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  59430. var fetchedColorB = _this._fetchR(particle._randomNoiseCoordinates2.y, particle._randomNoiseCoordinates2.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  59431. var force = BABYLON.Tmp.Vector3[0];
  59432. var scaledForce = BABYLON.Tmp.Vector3[1];
  59433. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  59434. force.scaleToRef(scaledUpdateSpeed, scaledForce);
  59435. particle.direction.addInPlace(scaledForce);
  59436. }
  59437. // Gravity
  59438. _this.gravity.scaleToRef(scaledUpdateSpeed, _this._scaledGravity);
  59439. particle.direction.addInPlace(_this._scaledGravity);
  59440. // Size
  59441. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  59442. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  59443. if (currentGradient !== particle._currentSizeGradient) {
  59444. particle._currentSize1 = particle._currentSize2;
  59445. particle._currentSize2 = nextGradient.getFactor();
  59446. particle._currentSizeGradient = currentGradient;
  59447. }
  59448. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  59449. });
  59450. }
  59451. // Remap data
  59452. if (_this._useRampGradients) {
  59453. if (_this._colorRemapGradients && _this._colorRemapGradients.length > 0) {
  59454. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorRemapGradients, function (currentGradient, nextGradient, scale) {
  59455. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  59456. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  59457. particle.remapData.x = min;
  59458. particle.remapData.y = max - min;
  59459. });
  59460. }
  59461. if (_this._alphaRemapGradients && _this._alphaRemapGradients.length > 0) {
  59462. BABYLON.Tools.GetCurrentGradient(ratio, _this._alphaRemapGradients, function (currentGradient, nextGradient, scale) {
  59463. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  59464. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  59465. particle.remapData.z = min;
  59466. particle.remapData.w = max - min;
  59467. });
  59468. }
  59469. }
  59470. if (_this._isAnimationSheetEnabled) {
  59471. particle.updateCellIndex();
  59472. }
  59473. // Update the position of the attached sub-emitters to match their attached particle
  59474. particle._inheritParticleInfoToSubEmitters();
  59475. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  59476. _this._emitFromParticle(particle);
  59477. if (particle._attachedSubEmitters) {
  59478. particle._attachedSubEmitters.forEach(function (subEmitter) {
  59479. subEmitter.particleSystem.disposeOnStop = true;
  59480. subEmitter.particleSystem.stop();
  59481. });
  59482. particle._attachedSubEmitters = null;
  59483. }
  59484. _this.recycleParticle(particle);
  59485. index--;
  59486. return "continue";
  59487. }
  59488. };
  59489. var particle;
  59490. for (var index = 0; index < particles.length; index++) {
  59491. _loop_1();
  59492. }
  59493. };
  59494. return _this;
  59495. }
  59496. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  59497. /**
  59498. * Sets a callback that will be triggered when the system is disposed
  59499. */
  59500. set: function (callback) {
  59501. if (this._onDisposeObserver) {
  59502. this.onDisposeObservable.remove(this._onDisposeObserver);
  59503. }
  59504. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  59505. },
  59506. enumerable: true,
  59507. configurable: true
  59508. });
  59509. Object.defineProperty(ParticleSystem.prototype, "useRampGradients", {
  59510. /** Gets or sets a boolean indicating that ramp gradients must be used
  59511. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  59512. */
  59513. get: function () {
  59514. return this._useRampGradients;
  59515. },
  59516. set: function (value) {
  59517. if (this._useRampGradients === value) {
  59518. return;
  59519. }
  59520. this._useRampGradients = value;
  59521. this._resetEffect();
  59522. },
  59523. enumerable: true,
  59524. configurable: true
  59525. });
  59526. Object.defineProperty(ParticleSystem.prototype, "particles", {
  59527. //end of Sub-emitter
  59528. /**
  59529. * Gets the current list of active particles
  59530. */
  59531. get: function () {
  59532. return this._particles;
  59533. },
  59534. enumerable: true,
  59535. configurable: true
  59536. });
  59537. /**
  59538. * Returns the string "ParticleSystem"
  59539. * @returns a string containing the class name
  59540. */
  59541. ParticleSystem.prototype.getClassName = function () {
  59542. return "ParticleSystem";
  59543. };
  59544. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  59545. var newGradient = new BABYLON.FactorGradient();
  59546. newGradient.gradient = gradient;
  59547. newGradient.factor1 = factor;
  59548. newGradient.factor2 = factor2;
  59549. factorGradients.push(newGradient);
  59550. factorGradients.sort(function (a, b) {
  59551. if (a.gradient < b.gradient) {
  59552. return -1;
  59553. }
  59554. else if (a.gradient > b.gradient) {
  59555. return 1;
  59556. }
  59557. return 0;
  59558. });
  59559. };
  59560. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  59561. if (!factorGradients) {
  59562. return;
  59563. }
  59564. var index = 0;
  59565. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  59566. var factorGradient = factorGradients_1[_i];
  59567. if (factorGradient.gradient === gradient) {
  59568. factorGradients.splice(index, 1);
  59569. break;
  59570. }
  59571. index++;
  59572. }
  59573. };
  59574. /**
  59575. * Adds a new life time gradient
  59576. * @param gradient defines the gradient to use (between 0 and 1)
  59577. * @param factor defines the life time factor to affect to the specified gradient
  59578. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59579. * @returns the current particle system
  59580. */
  59581. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  59582. if (!this._lifeTimeGradients) {
  59583. this._lifeTimeGradients = [];
  59584. }
  59585. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  59586. return this;
  59587. };
  59588. /**
  59589. * Remove a specific life time gradient
  59590. * @param gradient defines the gradient to remove
  59591. * @returns the current particle system
  59592. */
  59593. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  59594. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  59595. return this;
  59596. };
  59597. /**
  59598. * Adds a new size gradient
  59599. * @param gradient defines the gradient to use (between 0 and 1)
  59600. * @param factor defines the size factor to affect to the specified gradient
  59601. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59602. * @returns the current particle system
  59603. */
  59604. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  59605. if (!this._sizeGradients) {
  59606. this._sizeGradients = [];
  59607. }
  59608. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  59609. return this;
  59610. };
  59611. /**
  59612. * Remove a specific size gradient
  59613. * @param gradient defines the gradient to remove
  59614. * @returns the current particle system
  59615. */
  59616. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  59617. this._removeFactorGradient(this._sizeGradients, gradient);
  59618. return this;
  59619. };
  59620. /**
  59621. * Adds a new color remap gradient
  59622. * @param gradient defines the gradient to use (between 0 and 1)
  59623. * @param min defines the color remap minimal range
  59624. * @param max defines the color remap maximal range
  59625. * @returns the current particle system
  59626. */
  59627. ParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  59628. if (!this._colorRemapGradients) {
  59629. this._colorRemapGradients = [];
  59630. }
  59631. this._addFactorGradient(this._colorRemapGradients, gradient, min, max);
  59632. return this;
  59633. };
  59634. /**
  59635. * Remove a specific color remap gradient
  59636. * @param gradient defines the gradient to remove
  59637. * @returns the current particle system
  59638. */
  59639. ParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  59640. this._removeFactorGradient(this._colorRemapGradients, gradient);
  59641. return this;
  59642. };
  59643. /**
  59644. * Adds a new alpha remap gradient
  59645. * @param gradient defines the gradient to use (between 0 and 1)
  59646. * @param min defines the alpha remap minimal range
  59647. * @param max defines the alpha remap maximal range
  59648. * @returns the current particle system
  59649. */
  59650. ParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  59651. if (!this._alphaRemapGradients) {
  59652. this._alphaRemapGradients = [];
  59653. }
  59654. this._addFactorGradient(this._alphaRemapGradients, gradient, min, max);
  59655. return this;
  59656. };
  59657. /**
  59658. * Remove a specific alpha remap gradient
  59659. * @param gradient defines the gradient to remove
  59660. * @returns the current particle system
  59661. */
  59662. ParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  59663. this._removeFactorGradient(this._alphaRemapGradients, gradient);
  59664. return this;
  59665. };
  59666. /**
  59667. * Adds a new angular speed gradient
  59668. * @param gradient defines the gradient to use (between 0 and 1)
  59669. * @param factor defines the angular speed to affect to the specified gradient
  59670. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59671. * @returns the current particle system
  59672. */
  59673. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  59674. if (!this._angularSpeedGradients) {
  59675. this._angularSpeedGradients = [];
  59676. }
  59677. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  59678. return this;
  59679. };
  59680. /**
  59681. * Remove a specific angular speed gradient
  59682. * @param gradient defines the gradient to remove
  59683. * @returns the current particle system
  59684. */
  59685. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  59686. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  59687. return this;
  59688. };
  59689. /**
  59690. * Adds a new velocity gradient
  59691. * @param gradient defines the gradient to use (between 0 and 1)
  59692. * @param factor defines the velocity to affect to the specified gradient
  59693. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59694. * @returns the current particle system
  59695. */
  59696. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  59697. if (!this._velocityGradients) {
  59698. this._velocityGradients = [];
  59699. }
  59700. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  59701. return this;
  59702. };
  59703. /**
  59704. * Remove a specific velocity gradient
  59705. * @param gradient defines the gradient to remove
  59706. * @returns the current particle system
  59707. */
  59708. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  59709. this._removeFactorGradient(this._velocityGradients, gradient);
  59710. return this;
  59711. };
  59712. /**
  59713. * Adds a new limit velocity gradient
  59714. * @param gradient defines the gradient to use (between 0 and 1)
  59715. * @param factor defines the limit velocity value to affect to the specified gradient
  59716. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59717. * @returns the current particle system
  59718. */
  59719. ParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor, factor2) {
  59720. if (!this._limitVelocityGradients) {
  59721. this._limitVelocityGradients = [];
  59722. }
  59723. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  59724. return this;
  59725. };
  59726. /**
  59727. * Remove a specific limit velocity gradient
  59728. * @param gradient defines the gradient to remove
  59729. * @returns the current particle system
  59730. */
  59731. ParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  59732. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  59733. return this;
  59734. };
  59735. /**
  59736. * Adds a new drag gradient
  59737. * @param gradient defines the gradient to use (between 0 and 1)
  59738. * @param factor defines the drag value to affect to the specified gradient
  59739. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59740. * @returns the current particle system
  59741. */
  59742. ParticleSystem.prototype.addDragGradient = function (gradient, factor, factor2) {
  59743. if (!this._dragGradients) {
  59744. this._dragGradients = [];
  59745. }
  59746. this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
  59747. return this;
  59748. };
  59749. /**
  59750. * Remove a specific drag gradient
  59751. * @param gradient defines the gradient to remove
  59752. * @returns the current particle system
  59753. */
  59754. ParticleSystem.prototype.removeDragGradient = function (gradient) {
  59755. this._removeFactorGradient(this._dragGradients, gradient);
  59756. return this;
  59757. };
  59758. /**
  59759. * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property)
  59760. * @param gradient defines the gradient to use (between 0 and 1)
  59761. * @param factor defines the emit rate value to affect to the specified gradient
  59762. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59763. * @returns the current particle system
  59764. */
  59765. ParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  59766. if (!this._emitRateGradients) {
  59767. this._emitRateGradients = [];
  59768. }
  59769. this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2);
  59770. return this;
  59771. };
  59772. /**
  59773. * Remove a specific emit rate gradient
  59774. * @param gradient defines the gradient to remove
  59775. * @returns the current particle system
  59776. */
  59777. ParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  59778. this._removeFactorGradient(this._emitRateGradients, gradient);
  59779. return this;
  59780. };
  59781. /**
  59782. * Adds a new start size gradient (please note that this will only work if you set the targetStopDuration property)
  59783. * @param gradient defines the gradient to use (between 0 and 1)
  59784. * @param factor defines the start size value to affect to the specified gradient
  59785. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59786. * @returns the current particle system
  59787. */
  59788. ParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  59789. if (!this._startSizeGradients) {
  59790. this._startSizeGradients = [];
  59791. }
  59792. this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2);
  59793. return this;
  59794. };
  59795. /**
  59796. * Remove a specific start size gradient
  59797. * @param gradient defines the gradient to remove
  59798. * @returns the current particle system
  59799. */
  59800. ParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  59801. this._removeFactorGradient(this._emitRateGradients, gradient);
  59802. return this;
  59803. };
  59804. ParticleSystem.prototype._createRampGradientTexture = function () {
  59805. if (!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture) {
  59806. return;
  59807. }
  59808. var data = new Uint8Array(this._rawTextureWidth * 4);
  59809. var tmpColor = BABYLON.Tmp.Color3[0];
  59810. for (var x = 0; x < this._rawTextureWidth; x++) {
  59811. var ratio = x / this._rawTextureWidth;
  59812. BABYLON.Tools.GetCurrentGradient(ratio, this._rampGradients, function (currentGradient, nextGradient, scale) {
  59813. BABYLON.Color3.LerpToRef(currentGradient.color, nextGradient.color, scale, tmpColor);
  59814. data[x * 4] = tmpColor.r * 255;
  59815. data[x * 4 + 1] = tmpColor.g * 255;
  59816. data[x * 4 + 2] = tmpColor.b * 255;
  59817. data[x * 4 + 3] = 255;
  59818. });
  59819. }
  59820. this._rampGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  59821. };
  59822. /**
  59823. * Gets the current list of ramp gradients.
  59824. * You must use addRampGradient and removeRampGradient to udpate this list
  59825. * @returns the list of ramp gradients
  59826. */
  59827. ParticleSystem.prototype.getRampGradients = function () {
  59828. return this._rampGradients;
  59829. };
  59830. /**
  59831. * Adds a new ramp gradient used to remap particle colors
  59832. * @param gradient defines the gradient to use (between 0 and 1)
  59833. * @param color defines the color to affect to the specified gradient
  59834. * @returns the current particle system
  59835. */
  59836. ParticleSystem.prototype.addRampGradient = function (gradient, color) {
  59837. if (!this._rampGradients) {
  59838. this._rampGradients = [];
  59839. }
  59840. var rampGradient = new BABYLON.Color3Gradient();
  59841. rampGradient.gradient = gradient;
  59842. rampGradient.color = color;
  59843. this._rampGradients.push(rampGradient);
  59844. this._rampGradients.sort(function (a, b) {
  59845. if (a.gradient < b.gradient) {
  59846. return -1;
  59847. }
  59848. else if (a.gradient > b.gradient) {
  59849. return 1;
  59850. }
  59851. return 0;
  59852. });
  59853. if (this._rampGradientsTexture) {
  59854. this._rampGradientsTexture.dispose();
  59855. this._rampGradientsTexture = null;
  59856. }
  59857. this._createRampGradientTexture();
  59858. return this;
  59859. };
  59860. /**
  59861. * Remove a specific ramp gradient
  59862. * @param gradient defines the gradient to remove
  59863. * @returns the current particle system
  59864. */
  59865. ParticleSystem.prototype.removeRampGradient = function (gradient) {
  59866. this._removeGradientAndTexture(gradient, this._rampGradients, this._rampGradientsTexture);
  59867. this._rampGradientsTexture = null;
  59868. if (this._rampGradients && this._rampGradients.length > 0) {
  59869. this._createRampGradientTexture();
  59870. }
  59871. return this;
  59872. };
  59873. /**
  59874. * Adds a new color gradient
  59875. * @param gradient defines the gradient to use (between 0 and 1)
  59876. * @param color1 defines the color to affect to the specified gradient
  59877. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  59878. * @returns this particle system
  59879. */
  59880. ParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  59881. if (!this._colorGradients) {
  59882. this._colorGradients = [];
  59883. }
  59884. var colorGradient = new BABYLON.ColorGradient();
  59885. colorGradient.gradient = gradient;
  59886. colorGradient.color1 = color1;
  59887. colorGradient.color2 = color2;
  59888. this._colorGradients.push(colorGradient);
  59889. this._colorGradients.sort(function (a, b) {
  59890. if (a.gradient < b.gradient) {
  59891. return -1;
  59892. }
  59893. else if (a.gradient > b.gradient) {
  59894. return 1;
  59895. }
  59896. return 0;
  59897. });
  59898. return this;
  59899. };
  59900. /**
  59901. * Remove a specific color gradient
  59902. * @param gradient defines the gradient to remove
  59903. * @returns this particle system
  59904. */
  59905. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  59906. if (!this._colorGradients) {
  59907. return this;
  59908. }
  59909. var index = 0;
  59910. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  59911. var colorGradient = _a[_i];
  59912. if (colorGradient.gradient === gradient) {
  59913. this._colorGradients.splice(index, 1);
  59914. break;
  59915. }
  59916. index++;
  59917. }
  59918. return this;
  59919. };
  59920. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  59921. u = Math.abs(u) * 0.5 + 0.5;
  59922. v = Math.abs(v) * 0.5 + 0.5;
  59923. var wrappedU = ((u * width) % width) | 0;
  59924. var wrappedV = ((v * height) % height) | 0;
  59925. var position = (wrappedU + wrappedV * width) * 4;
  59926. return pixels[position] / 255;
  59927. };
  59928. ParticleSystem.prototype._reset = function () {
  59929. this._resetEffect();
  59930. };
  59931. ParticleSystem.prototype._resetEffect = function () {
  59932. if (this._vertexBuffer) {
  59933. this._vertexBuffer.dispose();
  59934. this._vertexBuffer = null;
  59935. }
  59936. if (this._spriteBuffer) {
  59937. this._spriteBuffer.dispose();
  59938. this._spriteBuffer = null;
  59939. }
  59940. this._createVertexBuffers();
  59941. };
  59942. ParticleSystem.prototype._createVertexBuffers = function () {
  59943. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  59944. if (this._isAnimationSheetEnabled) {
  59945. this._vertexBufferSize += 1;
  59946. }
  59947. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  59948. this._vertexBufferSize += 3;
  59949. }
  59950. if (this._useRampGradients) {
  59951. this._vertexBufferSize += 4;
  59952. }
  59953. var engine = this._scene.getEngine();
  59954. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  59955. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  59956. var dataOffset = 0;
  59957. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  59958. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  59959. dataOffset += 3;
  59960. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  59961. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  59962. dataOffset += 4;
  59963. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  59964. this._vertexBuffers["angle"] = options;
  59965. dataOffset += 1;
  59966. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  59967. this._vertexBuffers["size"] = size;
  59968. dataOffset += 2;
  59969. if (this._isAnimationSheetEnabled) {
  59970. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  59971. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  59972. dataOffset += 1;
  59973. }
  59974. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  59975. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  59976. this._vertexBuffers["direction"] = directionBuffer;
  59977. dataOffset += 3;
  59978. }
  59979. if (this._useRampGradients) {
  59980. var rampDataBuffer = this._vertexBuffer.createVertexBuffer("remapData", dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  59981. this._vertexBuffers["remapData"] = rampDataBuffer;
  59982. dataOffset += 4;
  59983. }
  59984. var offsets;
  59985. if (this._useInstancing) {
  59986. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  59987. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  59988. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  59989. }
  59990. else {
  59991. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  59992. dataOffset += 2;
  59993. }
  59994. this._vertexBuffers["offset"] = offsets;
  59995. };
  59996. ParticleSystem.prototype._createIndexBuffer = function () {
  59997. if (this._useInstancing) {
  59998. return;
  59999. }
  60000. var indices = [];
  60001. var index = 0;
  60002. for (var count = 0; count < this._capacity; count++) {
  60003. indices.push(index);
  60004. indices.push(index + 1);
  60005. indices.push(index + 2);
  60006. indices.push(index);
  60007. indices.push(index + 2);
  60008. indices.push(index + 3);
  60009. index += 4;
  60010. }
  60011. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  60012. };
  60013. /**
  60014. * Gets the maximum number of particles active at the same time.
  60015. * @returns The max number of active particles.
  60016. */
  60017. ParticleSystem.prototype.getCapacity = function () {
  60018. return this._capacity;
  60019. };
  60020. /**
  60021. * Gets whether there are still active particles in the system.
  60022. * @returns True if it is alive, otherwise false.
  60023. */
  60024. ParticleSystem.prototype.isAlive = function () {
  60025. return this._alive;
  60026. };
  60027. /**
  60028. * Gets if the system has been started. (Note: this will still be true after stop is called)
  60029. * @returns True if it has been started, otherwise false.
  60030. */
  60031. ParticleSystem.prototype.isStarted = function () {
  60032. return this._started;
  60033. };
  60034. ParticleSystem.prototype._prepareSubEmitterInternalArray = function () {
  60035. var _this = this;
  60036. this._subEmitters = new Array();
  60037. if (this.subEmitters) {
  60038. this.subEmitters.forEach(function (subEmitter) {
  60039. if (subEmitter instanceof ParticleSystem) {
  60040. _this._subEmitters.push([new BABYLON.SubEmitter(subEmitter)]);
  60041. }
  60042. else if (subEmitter instanceof BABYLON.SubEmitter) {
  60043. _this._subEmitters.push([subEmitter]);
  60044. }
  60045. else if (subEmitter instanceof Array) {
  60046. _this._subEmitters.push(subEmitter);
  60047. }
  60048. });
  60049. }
  60050. };
  60051. /**
  60052. * Starts the particle system and begins to emit
  60053. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  60054. */
  60055. ParticleSystem.prototype.start = function (delay) {
  60056. var _this = this;
  60057. if (delay === void 0) { delay = this.startDelay; }
  60058. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  60059. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  60060. }
  60061. if (delay) {
  60062. setTimeout(function () {
  60063. _this.start(0);
  60064. }, delay);
  60065. return;
  60066. }
  60067. // Convert the subEmitters field to the constant type field _subEmitters
  60068. this._prepareSubEmitterInternalArray();
  60069. this._started = true;
  60070. this._stopped = false;
  60071. this._actualFrame = 0;
  60072. if (this._subEmitters && this._subEmitters.length != 0) {
  60073. this.activeSubSystems = new Array();
  60074. }
  60075. // Reset emit gradient so it acts the same on every start
  60076. if (this._emitRateGradients) {
  60077. if (this._emitRateGradients.length > 0) {
  60078. this._currentEmitRateGradient = this._emitRateGradients[0];
  60079. this._currentEmitRate1 = this._currentEmitRateGradient.getFactor();
  60080. this._currentEmitRate2 = this._currentEmitRate1;
  60081. }
  60082. if (this._emitRateGradients.length > 1) {
  60083. this._currentEmitRate2 = this._emitRateGradients[1].getFactor();
  60084. }
  60085. }
  60086. // Reset start size gradient so it acts the same on every start
  60087. if (this._startSizeGradients) {
  60088. if (this._startSizeGradients.length > 0) {
  60089. this._currentStartSizeGradient = this._startSizeGradients[0];
  60090. this._currentStartSize1 = this._currentStartSizeGradient.getFactor();
  60091. this._currentStartSize2 = this._currentStartSize1;
  60092. }
  60093. if (this._startSizeGradients.length > 1) {
  60094. this._currentStartSize2 = this._startSizeGradients[1].getFactor();
  60095. }
  60096. }
  60097. if (this.preWarmCycles) {
  60098. if (this.emitter instanceof BABYLON.AbstractMesh) {
  60099. this.emitter.computeWorldMatrix(true);
  60100. }
  60101. var noiseTextureAsProcedural_1 = this.noiseTexture;
  60102. if (noiseTextureAsProcedural_1 && noiseTextureAsProcedural_1.onGeneratedObservable) {
  60103. noiseTextureAsProcedural_1.onGeneratedObservable.addOnce(function () {
  60104. setTimeout(function () {
  60105. for (var index = 0; index < _this.preWarmCycles; index++) {
  60106. _this.animate(true);
  60107. noiseTextureAsProcedural_1.render();
  60108. }
  60109. });
  60110. });
  60111. }
  60112. else {
  60113. for (var index = 0; index < this.preWarmCycles; index++) {
  60114. this.animate(true);
  60115. }
  60116. }
  60117. }
  60118. // Animations
  60119. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  60120. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  60121. }
  60122. };
  60123. /**
  60124. * Stops the particle system.
  60125. * @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.
  60126. */
  60127. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  60128. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  60129. this._stopped = true;
  60130. if (stopSubEmitters) {
  60131. this._stopSubEmitters();
  60132. }
  60133. };
  60134. // animation sheet
  60135. /**
  60136. * Remove all active particles
  60137. */
  60138. ParticleSystem.prototype.reset = function () {
  60139. this._stockParticles = [];
  60140. this._particles = [];
  60141. };
  60142. /**
  60143. * @hidden (for internal use only)
  60144. */
  60145. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  60146. var offset = index * this._vertexBufferSize;
  60147. this._vertexData[offset++] = particle.position.x;
  60148. this._vertexData[offset++] = particle.position.y;
  60149. this._vertexData[offset++] = particle.position.z;
  60150. this._vertexData[offset++] = particle.color.r;
  60151. this._vertexData[offset++] = particle.color.g;
  60152. this._vertexData[offset++] = particle.color.b;
  60153. this._vertexData[offset++] = particle.color.a;
  60154. this._vertexData[offset++] = particle.angle;
  60155. this._vertexData[offset++] = particle.scale.x * particle.size;
  60156. this._vertexData[offset++] = particle.scale.y * particle.size;
  60157. if (this._isAnimationSheetEnabled) {
  60158. this._vertexData[offset++] = particle.cellIndex;
  60159. }
  60160. if (!this._isBillboardBased) {
  60161. if (particle._initialDirection) {
  60162. this._vertexData[offset++] = particle._initialDirection.x;
  60163. this._vertexData[offset++] = particle._initialDirection.y;
  60164. this._vertexData[offset++] = particle._initialDirection.z;
  60165. }
  60166. else {
  60167. this._vertexData[offset++] = particle.direction.x;
  60168. this._vertexData[offset++] = particle.direction.y;
  60169. this._vertexData[offset++] = particle.direction.z;
  60170. }
  60171. }
  60172. else if (this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  60173. this._vertexData[offset++] = particle.direction.x;
  60174. this._vertexData[offset++] = particle.direction.y;
  60175. this._vertexData[offset++] = particle.direction.z;
  60176. }
  60177. if (this._useRampGradients) {
  60178. this._vertexData[offset++] = particle.remapData.x;
  60179. this._vertexData[offset++] = particle.remapData.y;
  60180. this._vertexData[offset++] = particle.remapData.z;
  60181. this._vertexData[offset++] = particle.remapData.w;
  60182. }
  60183. if (!this._useInstancing) {
  60184. if (this._isAnimationSheetEnabled) {
  60185. if (offsetX === 0) {
  60186. offsetX = this._epsilon;
  60187. }
  60188. else if (offsetX === 1) {
  60189. offsetX = 1 - this._epsilon;
  60190. }
  60191. if (offsetY === 0) {
  60192. offsetY = this._epsilon;
  60193. }
  60194. else if (offsetY === 1) {
  60195. offsetY = 1 - this._epsilon;
  60196. }
  60197. }
  60198. this._vertexData[offset++] = offsetX;
  60199. this._vertexData[offset++] = offsetY;
  60200. }
  60201. };
  60202. ParticleSystem.prototype._stopSubEmitters = function () {
  60203. if (!this.activeSubSystems) {
  60204. return;
  60205. }
  60206. this.activeSubSystems.forEach(function (subSystem) {
  60207. subSystem.stop(true);
  60208. });
  60209. this.activeSubSystems = new Array();
  60210. };
  60211. ParticleSystem.prototype._removeFromRoot = function () {
  60212. if (!this._rootParticleSystem) {
  60213. return;
  60214. }
  60215. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  60216. if (index !== -1) {
  60217. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  60218. }
  60219. this._rootParticleSystem = null;
  60220. };
  60221. // End of sub system methods
  60222. ParticleSystem.prototype._update = function (newParticles) {
  60223. var _this = this;
  60224. // Update current
  60225. this._alive = this._particles.length > 0;
  60226. if (this.emitter.position) {
  60227. var emitterMesh = this.emitter;
  60228. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  60229. }
  60230. else {
  60231. var emitterPosition = this.emitter;
  60232. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  60233. }
  60234. this.updateFunction(this._particles);
  60235. // Add new ones
  60236. var particle;
  60237. var _loop_2 = function () {
  60238. if (this_1._particles.length === this_1._capacity) {
  60239. return "break";
  60240. }
  60241. particle = this_1._createParticle();
  60242. this_1._particles.push(particle);
  60243. // Emitter
  60244. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  60245. if (this_1.startPositionFunction) {
  60246. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  60247. }
  60248. else {
  60249. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  60250. }
  60251. if (this_1.startDirectionFunction) {
  60252. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  60253. }
  60254. else {
  60255. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  60256. }
  60257. if (emitPower === 0) {
  60258. if (!particle._initialDirection) {
  60259. particle._initialDirection = particle.direction.clone();
  60260. }
  60261. else {
  60262. particle._initialDirection.copyFrom(particle.direction);
  60263. }
  60264. }
  60265. else {
  60266. particle._initialDirection = null;
  60267. }
  60268. particle.direction.scaleInPlace(emitPower);
  60269. // Life time
  60270. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  60271. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  60272. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  60273. var factorGradient1 = currentGradient;
  60274. var factorGradient2 = nextGradient;
  60275. var lifeTime1 = factorGradient1.getFactor();
  60276. var lifeTime2 = factorGradient2.getFactor();
  60277. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  60278. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  60279. });
  60280. }
  60281. else {
  60282. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  60283. }
  60284. // Size
  60285. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  60286. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  60287. }
  60288. else {
  60289. particle._currentSizeGradient = this_1._sizeGradients[0];
  60290. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  60291. particle.size = particle._currentSize1;
  60292. if (this_1._sizeGradients.length > 1) {
  60293. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  60294. }
  60295. else {
  60296. particle._currentSize2 = particle._currentSize1;
  60297. }
  60298. }
  60299. // Size and scale
  60300. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  60301. // Adjust scale by start size
  60302. if (this_1._startSizeGradients && this_1._startSizeGradients[0] && this_1.targetStopDuration) {
  60303. var ratio = this_1._actualFrame / this_1.targetStopDuration;
  60304. BABYLON.Tools.GetCurrentGradient(ratio, this_1._startSizeGradients, function (currentGradient, nextGradient, scale) {
  60305. if (currentGradient !== _this._currentStartSizeGradient) {
  60306. _this._currentStartSize1 = _this._currentStartSize2;
  60307. _this._currentStartSize2 = nextGradient.getFactor();
  60308. _this._currentStartSizeGradient = currentGradient;
  60309. }
  60310. var value = BABYLON.Scalar.Lerp(_this._currentStartSize1, _this._currentStartSize2, scale);
  60311. particle.scale.scaleInPlace(value);
  60312. });
  60313. }
  60314. // Angle
  60315. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  60316. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  60317. }
  60318. else {
  60319. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  60320. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  60321. particle._currentAngularSpeed1 = particle.angularSpeed;
  60322. if (this_1._angularSpeedGradients.length > 1) {
  60323. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  60324. }
  60325. else {
  60326. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  60327. }
  60328. }
  60329. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  60330. // Velocity
  60331. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  60332. particle._currentVelocityGradient = this_1._velocityGradients[0];
  60333. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  60334. if (this_1._velocityGradients.length > 1) {
  60335. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  60336. }
  60337. else {
  60338. particle._currentVelocity2 = particle._currentVelocity1;
  60339. }
  60340. }
  60341. // Limit velocity
  60342. if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
  60343. particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
  60344. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  60345. if (this_1._limitVelocityGradients.length > 1) {
  60346. particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
  60347. }
  60348. else {
  60349. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  60350. }
  60351. }
  60352. // Drag
  60353. if (this_1._dragGradients && this_1._dragGradients.length > 0) {
  60354. particle._currentDragGradient = this_1._dragGradients[0];
  60355. particle._currentDrag1 = particle._currentDragGradient.getFactor();
  60356. if (this_1._dragGradients.length > 1) {
  60357. particle._currentDrag2 = this_1._dragGradients[1].getFactor();
  60358. }
  60359. else {
  60360. particle._currentDrag2 = particle._currentDrag1;
  60361. }
  60362. }
  60363. // Color
  60364. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  60365. step = BABYLON.Scalar.RandomRange(0, 1.0);
  60366. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  60367. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  60368. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  60369. }
  60370. else {
  60371. particle._currentColorGradient = this_1._colorGradients[0];
  60372. particle._currentColorGradient.getColorToRef(particle.color);
  60373. particle._currentColor1.copyFrom(particle.color);
  60374. if (this_1._colorGradients.length > 1) {
  60375. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  60376. }
  60377. else {
  60378. particle._currentColor2.copyFrom(particle.color);
  60379. }
  60380. }
  60381. // Sheet
  60382. if (this_1._isAnimationSheetEnabled) {
  60383. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  60384. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  60385. }
  60386. // Inherited Velocity
  60387. particle.direction.addInPlace(this_1._inheritedVelocityOffset);
  60388. // Ramp
  60389. if (this_1._useRampGradients) {
  60390. particle.remapData = new BABYLON.Vector4(0, 1, 0, 1);
  60391. }
  60392. // Noise texture coordinates
  60393. if (this_1.noiseTexture) {
  60394. if (particle._randomNoiseCoordinates1) {
  60395. particle._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random());
  60396. particle._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random());
  60397. }
  60398. else {
  60399. particle._randomNoiseCoordinates1 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  60400. particle._randomNoiseCoordinates2 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  60401. }
  60402. }
  60403. // Update the position of the attached sub-emitters to match their attached particle
  60404. particle._inheritParticleInfoToSubEmitters();
  60405. };
  60406. var this_1 = this, step;
  60407. for (var index = 0; index < newParticles; index++) {
  60408. var state_1 = _loop_2();
  60409. if (state_1 === "break")
  60410. break;
  60411. }
  60412. };
  60413. /** @hidden */
  60414. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased, useRampGradients) {
  60415. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  60416. if (isBillboardBased === void 0) { isBillboardBased = false; }
  60417. if (useRampGradients === void 0) { useRampGradients = false; }
  60418. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  60419. if (isAnimationSheetEnabled) {
  60420. attributeNamesOrOptions.push("cellIndex");
  60421. }
  60422. if (!isBillboardBased) {
  60423. attributeNamesOrOptions.push("direction");
  60424. }
  60425. if (useRampGradients) {
  60426. attributeNamesOrOptions.push("remapData");
  60427. }
  60428. return attributeNamesOrOptions;
  60429. };
  60430. /** @hidden */
  60431. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  60432. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  60433. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
  60434. if (isAnimationSheetEnabled) {
  60435. effectCreationOption.push("particlesInfos");
  60436. }
  60437. return effectCreationOption;
  60438. };
  60439. /** @hidden */
  60440. ParticleSystem.prototype._getEffect = function (blendMode) {
  60441. if (this._customEffect) {
  60442. return this._customEffect;
  60443. }
  60444. var defines = [];
  60445. if (this._scene.clipPlane) {
  60446. defines.push("#define CLIPPLANE");
  60447. }
  60448. if (this._scene.clipPlane2) {
  60449. defines.push("#define CLIPPLANE2");
  60450. }
  60451. if (this._scene.clipPlane3) {
  60452. defines.push("#define CLIPPLANE3");
  60453. }
  60454. if (this._scene.clipPlane4) {
  60455. defines.push("#define CLIPPLANE4");
  60456. }
  60457. if (this._isAnimationSheetEnabled) {
  60458. defines.push("#define ANIMATESHEET");
  60459. }
  60460. if (blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {
  60461. defines.push("#define BLENDMULTIPLYMODE");
  60462. }
  60463. if (this._useRampGradients) {
  60464. defines.push("#define RAMPGRADIENT");
  60465. }
  60466. if (this._isBillboardBased) {
  60467. defines.push("#define BILLBOARD");
  60468. switch (this.billboardMode) {
  60469. case ParticleSystem.BILLBOARDMODE_Y:
  60470. defines.push("#define BILLBOARDY");
  60471. break;
  60472. case ParticleSystem.BILLBOARDMODE_STRETCHED:
  60473. defines.push("#define BILLBOARDSTRETCHED");
  60474. break;
  60475. case ParticleSystem.BILLBOARDMODE_ALL:
  60476. default:
  60477. break;
  60478. }
  60479. }
  60480. if (this._imageProcessingConfiguration) {
  60481. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  60482. defines.push(this._imageProcessingConfigurationDefines.toString());
  60483. }
  60484. // Effect
  60485. var join = defines.join("\n");
  60486. if (this._cachedDefines !== join) {
  60487. this._cachedDefines = join;
  60488. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased && this.billboardMode !== ParticleSystem.BILLBOARDMODE_STRETCHED, this._useRampGradients);
  60489. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  60490. var samplers = ["diffuseSampler", "rampSampler"];
  60491. if (BABYLON.ImageProcessingConfiguration) {
  60492. BABYLON.ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
  60493. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  60494. }
  60495. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, samplers, join);
  60496. }
  60497. return this._effect;
  60498. };
  60499. /**
  60500. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  60501. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  60502. */
  60503. ParticleSystem.prototype.animate = function (preWarmOnly) {
  60504. var _this = this;
  60505. if (preWarmOnly === void 0) { preWarmOnly = false; }
  60506. if (!this._started) {
  60507. return;
  60508. }
  60509. if (!preWarmOnly) {
  60510. // Check
  60511. if (!this.isReady()) {
  60512. return;
  60513. }
  60514. if (this._currentRenderId === this._scene.getRenderId()) {
  60515. return;
  60516. }
  60517. this._currentRenderId = this._scene.getRenderId();
  60518. }
  60519. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  60520. // Determine the number of particles we need to create
  60521. var newParticles;
  60522. if (this.manualEmitCount > -1) {
  60523. newParticles = this.manualEmitCount;
  60524. this._newPartsExcess = 0;
  60525. this.manualEmitCount = 0;
  60526. }
  60527. else {
  60528. var rate_1 = this.emitRate;
  60529. if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {
  60530. var ratio = this._actualFrame / this.targetStopDuration;
  60531. BABYLON.Tools.GetCurrentGradient(ratio, this._emitRateGradients, function (currentGradient, nextGradient, scale) {
  60532. if (currentGradient !== _this._currentEmitRateGradient) {
  60533. _this._currentEmitRate1 = _this._currentEmitRate2;
  60534. _this._currentEmitRate2 = nextGradient.getFactor();
  60535. _this._currentEmitRateGradient = currentGradient;
  60536. }
  60537. rate_1 = BABYLON.Scalar.Lerp(_this._currentEmitRate1, _this._currentEmitRate2, scale);
  60538. });
  60539. }
  60540. newParticles = ((rate_1 * this._scaledUpdateSpeed) >> 0);
  60541. this._newPartsExcess += rate_1 * this._scaledUpdateSpeed - newParticles;
  60542. }
  60543. if (this._newPartsExcess > 1.0) {
  60544. newParticles += this._newPartsExcess >> 0;
  60545. this._newPartsExcess -= this._newPartsExcess >> 0;
  60546. }
  60547. this._alive = false;
  60548. if (!this._stopped) {
  60549. this._actualFrame += this._scaledUpdateSpeed;
  60550. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  60551. this.stop();
  60552. }
  60553. }
  60554. else {
  60555. newParticles = 0;
  60556. }
  60557. this._update(newParticles);
  60558. // Stopped?
  60559. if (this._stopped) {
  60560. if (!this._alive) {
  60561. this._started = false;
  60562. if (this.onAnimationEnd) {
  60563. this.onAnimationEnd();
  60564. }
  60565. if (this.disposeOnStop) {
  60566. this._scene._toBeDisposed.push(this);
  60567. }
  60568. }
  60569. }
  60570. if (!preWarmOnly) {
  60571. // Update VBO
  60572. var offset = 0;
  60573. for (var index = 0; index < this._particles.length; index++) {
  60574. var particle = this._particles[index];
  60575. this._appendParticleVertices(offset, particle);
  60576. offset += this._useInstancing ? 1 : 4;
  60577. }
  60578. if (this._vertexBuffer) {
  60579. this._vertexBuffer.update(this._vertexData);
  60580. }
  60581. }
  60582. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  60583. this.stop();
  60584. }
  60585. };
  60586. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  60587. this._appendParticleVertex(offset++, particle, 0, 0);
  60588. if (!this._useInstancing) {
  60589. this._appendParticleVertex(offset++, particle, 1, 0);
  60590. this._appendParticleVertex(offset++, particle, 1, 1);
  60591. this._appendParticleVertex(offset++, particle, 0, 1);
  60592. }
  60593. };
  60594. /**
  60595. * Rebuilds the particle system.
  60596. */
  60597. ParticleSystem.prototype.rebuild = function () {
  60598. this._createIndexBuffer();
  60599. if (this._vertexBuffer) {
  60600. this._vertexBuffer._rebuild();
  60601. }
  60602. };
  60603. /**
  60604. * Is this system ready to be used/rendered
  60605. * @return true if the system is ready
  60606. */
  60607. ParticleSystem.prototype.isReady = function () {
  60608. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  60609. return false;
  60610. }
  60611. if (this.blendMode !== ParticleSystem.BLENDMODE_MULTIPLYADD) {
  60612. if (!this._getEffect(this.blendMode).isReady()) {
  60613. return false;
  60614. }
  60615. }
  60616. else {
  60617. if (!this._getEffect(ParticleSystem.BLENDMODE_MULTIPLY).isReady()) {
  60618. return false;
  60619. }
  60620. if (!this._getEffect(ParticleSystem.BLENDMODE_ADD).isReady()) {
  60621. return false;
  60622. }
  60623. }
  60624. return true;
  60625. };
  60626. ParticleSystem.prototype._render = function (blendMode) {
  60627. var effect = this._getEffect(blendMode);
  60628. var engine = this._scene.getEngine();
  60629. // Render
  60630. engine.enableEffect(effect);
  60631. var viewMatrix = this._scene.getViewMatrix();
  60632. effect.setTexture("diffuseSampler", this.particleTexture);
  60633. effect.setMatrix("view", viewMatrix);
  60634. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  60635. if (this._isAnimationSheetEnabled && this.particleTexture) {
  60636. var baseSize = this.particleTexture.getBaseSize();
  60637. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  60638. }
  60639. effect.setVector2("translationPivot", this.translationPivot);
  60640. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  60641. if (this._isBillboardBased) {
  60642. var camera = this._scene.activeCamera;
  60643. effect.setVector3("eyePosition", camera.globalPosition);
  60644. }
  60645. if (this._rampGradientsTexture) {
  60646. effect.setTexture("rampSampler", this._rampGradientsTexture);
  60647. }
  60648. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  60649. var invView = viewMatrix.clone();
  60650. invView.invert();
  60651. effect.setMatrix("invView", invView);
  60652. BABYLON.MaterialHelper.BindClipPlane(effect, this._scene);
  60653. }
  60654. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  60655. // image processing
  60656. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  60657. this._imageProcessingConfiguration.bind(effect);
  60658. }
  60659. // Draw order
  60660. switch (blendMode) {
  60661. case ParticleSystem.BLENDMODE_ADD:
  60662. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  60663. break;
  60664. case ParticleSystem.BLENDMODE_ONEONE:
  60665. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  60666. break;
  60667. case ParticleSystem.BLENDMODE_STANDARD:
  60668. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  60669. break;
  60670. case ParticleSystem.BLENDMODE_MULTIPLY:
  60671. engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  60672. break;
  60673. }
  60674. if (this._useInstancing) {
  60675. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  60676. }
  60677. else {
  60678. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  60679. }
  60680. return this._particles.length;
  60681. };
  60682. /**
  60683. * Renders the particle system in its current state.
  60684. * @returns the current number of particles
  60685. */
  60686. ParticleSystem.prototype.render = function () {
  60687. // Check
  60688. if (!this.isReady() || !this._particles.length) {
  60689. return 0;
  60690. }
  60691. var engine = this._scene.getEngine();
  60692. engine.setState(false);
  60693. if (this.forceDepthWrite) {
  60694. engine.setDepthWrite(true);
  60695. }
  60696. var outparticles = 0;
  60697. if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLYADD) {
  60698. outparticles = this._render(ParticleSystem.BLENDMODE_MULTIPLY) + this._render(ParticleSystem.BLENDMODE_ADD);
  60699. }
  60700. outparticles = this._render(this.blendMode);
  60701. engine.unbindInstanceAttributes();
  60702. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  60703. return outparticles;
  60704. };
  60705. /**
  60706. * Disposes the particle system and free the associated resources
  60707. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  60708. */
  60709. ParticleSystem.prototype.dispose = function (disposeTexture) {
  60710. if (disposeTexture === void 0) { disposeTexture = true; }
  60711. if (this._vertexBuffer) {
  60712. this._vertexBuffer.dispose();
  60713. this._vertexBuffer = null;
  60714. }
  60715. if (this._spriteBuffer) {
  60716. this._spriteBuffer.dispose();
  60717. this._spriteBuffer = null;
  60718. }
  60719. if (this._indexBuffer) {
  60720. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  60721. this._indexBuffer = null;
  60722. }
  60723. if (disposeTexture && this.particleTexture) {
  60724. this.particleTexture.dispose();
  60725. this.particleTexture = null;
  60726. }
  60727. if (disposeTexture && this.noiseTexture) {
  60728. this.noiseTexture.dispose();
  60729. this.noiseTexture = null;
  60730. }
  60731. if (this._rampGradientsTexture) {
  60732. this._rampGradientsTexture.dispose();
  60733. this._rampGradientsTexture = null;
  60734. }
  60735. this._removeFromRoot();
  60736. if (this._subEmitters && this._subEmitters.length) {
  60737. for (var index = 0; index < this._subEmitters.length; index++) {
  60738. for (var _i = 0, _a = this._subEmitters[index]; _i < _a.length; _i++) {
  60739. var subEmitter = _a[_i];
  60740. subEmitter.dispose();
  60741. }
  60742. }
  60743. this._subEmitters = [];
  60744. this.subEmitters = [];
  60745. }
  60746. if (this._disposeEmitterOnDispose && this.emitter && this.emitter.dispose) {
  60747. this.emitter.dispose(true);
  60748. }
  60749. // Remove from scene
  60750. var index = this._scene.particleSystems.indexOf(this);
  60751. if (index > -1) {
  60752. this._scene.particleSystems.splice(index, 1);
  60753. }
  60754. this._scene._activeParticleSystems.dispose();
  60755. // Callback
  60756. this.onDisposeObservable.notifyObservers(this);
  60757. this.onDisposeObservable.clear();
  60758. this.reset();
  60759. };
  60760. // Clone
  60761. /**
  60762. * Clones the particle system.
  60763. * @param name The name of the cloned object
  60764. * @param newEmitter The new emitter to use
  60765. * @returns the cloned particle system
  60766. */
  60767. ParticleSystem.prototype.clone = function (name, newEmitter) {
  60768. var custom = null;
  60769. var program = null;
  60770. if (this.customShader != null) {
  60771. program = this.customShader;
  60772. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  60773. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  60774. }
  60775. else if (this._customEffect) {
  60776. custom = this._customEffect;
  60777. }
  60778. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  60779. result.customShader = program;
  60780. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader", "noiseTexture"]);
  60781. if (newEmitter === undefined) {
  60782. newEmitter = this.emitter;
  60783. }
  60784. result.noiseTexture = this.noiseTexture;
  60785. result.emitter = newEmitter;
  60786. if (this.particleTexture) {
  60787. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  60788. }
  60789. // Clone gradients
  60790. if (this._colorGradients) {
  60791. this._colorGradients.forEach(function (v) {
  60792. result.addColorGradient(v.gradient, v.color1, v.color2);
  60793. });
  60794. }
  60795. if (this._dragGradients) {
  60796. this._dragGradients.forEach(function (v) {
  60797. result.addDragGradient(v.gradient, v.factor1, v.factor2);
  60798. });
  60799. }
  60800. if (this._angularSpeedGradients) {
  60801. this._angularSpeedGradients.forEach(function (v) {
  60802. result.addAngularSpeedGradient(v.gradient, v.factor1, v.factor2);
  60803. });
  60804. }
  60805. if (this._emitRateGradients) {
  60806. this._emitRateGradients.forEach(function (v) {
  60807. result.addEmitRateGradient(v.gradient, v.factor1, v.factor2);
  60808. });
  60809. }
  60810. if (this._lifeTimeGradients) {
  60811. this._lifeTimeGradients.forEach(function (v) {
  60812. result.addLifeTimeGradient(v.gradient, v.factor1, v.factor2);
  60813. });
  60814. }
  60815. if (this._limitVelocityGradients) {
  60816. this._limitVelocityGradients.forEach(function (v) {
  60817. result.addLimitVelocityGradient(v.gradient, v.factor1, v.factor2);
  60818. });
  60819. }
  60820. if (this._sizeGradients) {
  60821. this._sizeGradients.forEach(function (v) {
  60822. result.addSizeGradient(v.gradient, v.factor1, v.factor2);
  60823. });
  60824. }
  60825. if (this._startSizeGradients) {
  60826. this._startSizeGradients.forEach(function (v) {
  60827. result.addStartSizeGradient(v.gradient, v.factor1, v.factor2);
  60828. });
  60829. }
  60830. if (this._velocityGradients) {
  60831. this._velocityGradients.forEach(function (v) {
  60832. result.addVelocityGradient(v.gradient, v.factor1, v.factor2);
  60833. });
  60834. }
  60835. if (this._rampGradients) {
  60836. this._rampGradients.forEach(function (v) {
  60837. result.addRampGradient(v.gradient, v.color);
  60838. });
  60839. }
  60840. if (this._colorRemapGradients) {
  60841. this._colorRemapGradients.forEach(function (v) {
  60842. result.addColorRemapGradient(v.gradient, v.factor1, v.factor2);
  60843. });
  60844. }
  60845. if (this._alphaRemapGradients) {
  60846. this._alphaRemapGradients.forEach(function (v) {
  60847. result.addAlphaRemapGradient(v.gradient, v.factor1, v.factor2);
  60848. });
  60849. }
  60850. if (!this.preventAutoStart) {
  60851. result.start();
  60852. }
  60853. return result;
  60854. };
  60855. /**
  60856. * Serializes the particle system to a JSON object.
  60857. * @returns the JSON object
  60858. */
  60859. ParticleSystem.prototype.serialize = function () {
  60860. var serializationObject = {};
  60861. ParticleSystem._Serialize(serializationObject, this);
  60862. serializationObject.textureMask = this.textureMask.asArray();
  60863. serializationObject.customShader = this.customShader;
  60864. serializationObject.preventAutoStart = this.preventAutoStart;
  60865. // SubEmitters
  60866. if (this.subEmitters) {
  60867. serializationObject.subEmitters = [];
  60868. if (!this._subEmitters) {
  60869. this._prepareSubEmitterInternalArray();
  60870. }
  60871. for (var _i = 0, _a = this._subEmitters; _i < _a.length; _i++) {
  60872. var subs = _a[_i];
  60873. var cell = [];
  60874. for (var _b = 0, subs_1 = subs; _b < subs_1.length; _b++) {
  60875. var sub = subs_1[_b];
  60876. cell.push(sub.serialize());
  60877. }
  60878. serializationObject.subEmitters.push(cell);
  60879. }
  60880. }
  60881. return serializationObject;
  60882. };
  60883. /** @hidden */
  60884. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  60885. serializationObject.name = particleSystem.name;
  60886. serializationObject.id = particleSystem.id;
  60887. serializationObject.capacity = particleSystem.getCapacity();
  60888. // Emitter
  60889. if (particleSystem.emitter.position) {
  60890. var emitterMesh = particleSystem.emitter;
  60891. serializationObject.emitterId = emitterMesh.id;
  60892. }
  60893. else {
  60894. var emitterPosition = particleSystem.emitter;
  60895. serializationObject.emitter = emitterPosition.asArray();
  60896. }
  60897. // Emitter
  60898. if (particleSystem.particleEmitterType) {
  60899. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  60900. }
  60901. if (particleSystem.particleTexture) {
  60902. serializationObject.textureName = particleSystem.particleTexture.name;
  60903. serializationObject.invertY = particleSystem.particleTexture._invertY;
  60904. }
  60905. // Animations
  60906. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  60907. serializationObject.beginAnimationOnStart = particleSystem.beginAnimationOnStart;
  60908. serializationObject.beginAnimationFrom = particleSystem.beginAnimationFrom;
  60909. serializationObject.beginAnimationTo = particleSystem.beginAnimationTo;
  60910. serializationObject.beginAnimationLoop = particleSystem.beginAnimationLoop;
  60911. // Particle system
  60912. serializationObject.startDelay = particleSystem.startDelay;
  60913. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  60914. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  60915. serializationObject.billboardMode = particleSystem.billboardMode;
  60916. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  60917. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  60918. serializationObject.minSize = particleSystem.minSize;
  60919. serializationObject.maxSize = particleSystem.maxSize;
  60920. serializationObject.minScaleX = particleSystem.minScaleX;
  60921. serializationObject.maxScaleX = particleSystem.maxScaleX;
  60922. serializationObject.minScaleY = particleSystem.minScaleY;
  60923. serializationObject.maxScaleY = particleSystem.maxScaleY;
  60924. serializationObject.minEmitPower = particleSystem.minEmitPower;
  60925. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  60926. serializationObject.minLifeTime = particleSystem.minLifeTime;
  60927. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  60928. serializationObject.emitRate = particleSystem.emitRate;
  60929. serializationObject.gravity = particleSystem.gravity.asArray();
  60930. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  60931. serializationObject.color1 = particleSystem.color1.asArray();
  60932. serializationObject.color2 = particleSystem.color2.asArray();
  60933. serializationObject.colorDead = particleSystem.colorDead.asArray();
  60934. serializationObject.updateSpeed = particleSystem.updateSpeed;
  60935. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  60936. serializationObject.blendMode = particleSystem.blendMode;
  60937. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  60938. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  60939. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  60940. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  60941. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  60942. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  60943. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  60944. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  60945. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  60946. serializationObject.spriteRandomStartCell = particleSystem.spriteRandomStartCell;
  60947. serializationObject.isAnimationSheetEnabled = particleSystem.isAnimationSheetEnabled;
  60948. var colorGradients = particleSystem.getColorGradients();
  60949. if (colorGradients) {
  60950. serializationObject.colorGradients = [];
  60951. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  60952. var colorGradient = colorGradients_1[_i];
  60953. var serializedGradient = {
  60954. gradient: colorGradient.gradient,
  60955. color1: colorGradient.color1.asArray()
  60956. };
  60957. if (colorGradient.color2) {
  60958. serializedGradient.color2 = colorGradient.color2.asArray();
  60959. }
  60960. serializationObject.colorGradients.push(serializedGradient);
  60961. }
  60962. }
  60963. var rampGradients = particleSystem.getRampGradients();
  60964. if (rampGradients) {
  60965. serializationObject.rampGradients = [];
  60966. for (var _a = 0, rampGradients_1 = rampGradients; _a < rampGradients_1.length; _a++) {
  60967. var rampGradient = rampGradients_1[_a];
  60968. var serializedGradient = {
  60969. gradient: rampGradient.gradient,
  60970. color: rampGradient.color.asArray()
  60971. };
  60972. serializationObject.rampGradients.push(serializedGradient);
  60973. }
  60974. serializationObject.useRampGradients = particleSystem.useRampGradients;
  60975. }
  60976. var colorRemapGradients = particleSystem.getColorRemapGradients();
  60977. if (colorRemapGradients) {
  60978. serializationObject.colorRemapGradients = [];
  60979. for (var _b = 0, colorRemapGradients_1 = colorRemapGradients; _b < colorRemapGradients_1.length; _b++) {
  60980. var colorRemapGradient = colorRemapGradients_1[_b];
  60981. var serializedGradient = {
  60982. gradient: colorRemapGradient.gradient,
  60983. factor1: colorRemapGradient.factor1
  60984. };
  60985. if (colorRemapGradient.factor2 !== undefined) {
  60986. serializedGradient.factor2 = colorRemapGradient.factor2;
  60987. }
  60988. serializationObject.colorRemapGradients.push(serializedGradient);
  60989. }
  60990. }
  60991. var alphaRemapGradients = particleSystem.getAlphaRemapGradients();
  60992. if (alphaRemapGradients) {
  60993. serializationObject.alphaRemapGradients = [];
  60994. for (var _c = 0, alphaRemapGradients_1 = alphaRemapGradients; _c < alphaRemapGradients_1.length; _c++) {
  60995. var alphaRemapGradient = alphaRemapGradients_1[_c];
  60996. var serializedGradient = {
  60997. gradient: alphaRemapGradient.gradient,
  60998. factor1: alphaRemapGradient.factor1
  60999. };
  61000. if (alphaRemapGradient.factor2 !== undefined) {
  61001. serializedGradient.factor2 = alphaRemapGradient.factor2;
  61002. }
  61003. serializationObject.alphaRemapGradients.push(serializedGradient);
  61004. }
  61005. }
  61006. var sizeGradients = particleSystem.getSizeGradients();
  61007. if (sizeGradients) {
  61008. serializationObject.sizeGradients = [];
  61009. for (var _d = 0, sizeGradients_1 = sizeGradients; _d < sizeGradients_1.length; _d++) {
  61010. var sizeGradient = sizeGradients_1[_d];
  61011. var serializedGradient = {
  61012. gradient: sizeGradient.gradient,
  61013. factor1: sizeGradient.factor1
  61014. };
  61015. if (sizeGradient.factor2 !== undefined) {
  61016. serializedGradient.factor2 = sizeGradient.factor2;
  61017. }
  61018. serializationObject.sizeGradients.push(serializedGradient);
  61019. }
  61020. }
  61021. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  61022. if (angularSpeedGradients) {
  61023. serializationObject.angularSpeedGradients = [];
  61024. for (var _e = 0, angularSpeedGradients_1 = angularSpeedGradients; _e < angularSpeedGradients_1.length; _e++) {
  61025. var angularSpeedGradient = angularSpeedGradients_1[_e];
  61026. var serializedGradient = {
  61027. gradient: angularSpeedGradient.gradient,
  61028. factor1: angularSpeedGradient.factor1
  61029. };
  61030. if (angularSpeedGradient.factor2 !== undefined) {
  61031. serializedGradient.factor2 = angularSpeedGradient.factor2;
  61032. }
  61033. serializationObject.angularSpeedGradients.push(serializedGradient);
  61034. }
  61035. }
  61036. var velocityGradients = particleSystem.getVelocityGradients();
  61037. if (velocityGradients) {
  61038. serializationObject.velocityGradients = [];
  61039. for (var _f = 0, velocityGradients_1 = velocityGradients; _f < velocityGradients_1.length; _f++) {
  61040. var velocityGradient = velocityGradients_1[_f];
  61041. var serializedGradient = {
  61042. gradient: velocityGradient.gradient,
  61043. factor1: velocityGradient.factor1
  61044. };
  61045. if (velocityGradient.factor2 !== undefined) {
  61046. serializedGradient.factor2 = velocityGradient.factor2;
  61047. }
  61048. serializationObject.velocityGradients.push(serializedGradient);
  61049. }
  61050. }
  61051. var dragGradients = particleSystem.getDragGradients();
  61052. if (dragGradients) {
  61053. serializationObject.dragyGradients = [];
  61054. for (var _g = 0, dragGradients_1 = dragGradients; _g < dragGradients_1.length; _g++) {
  61055. var dragGradient = dragGradients_1[_g];
  61056. var serializedGradient = {
  61057. gradient: dragGradient.gradient,
  61058. factor1: dragGradient.factor1
  61059. };
  61060. if (dragGradient.factor2 !== undefined) {
  61061. serializedGradient.factor2 = dragGradient.factor2;
  61062. }
  61063. serializationObject.dragGradients.push(serializedGradient);
  61064. }
  61065. }
  61066. var emitRateGradients = particleSystem.getEmitRateGradients();
  61067. if (emitRateGradients) {
  61068. serializationObject.emitRateGradients = [];
  61069. for (var _h = 0, emitRateGradients_1 = emitRateGradients; _h < emitRateGradients_1.length; _h++) {
  61070. var emitRateGradient = emitRateGradients_1[_h];
  61071. var serializedGradient = {
  61072. gradient: emitRateGradient.gradient,
  61073. factor1: emitRateGradient.factor1
  61074. };
  61075. if (emitRateGradient.factor2 !== undefined) {
  61076. serializedGradient.factor2 = emitRateGradient.factor2;
  61077. }
  61078. serializationObject.emitRateGradients.push(serializedGradient);
  61079. }
  61080. }
  61081. var startSizeGradients = particleSystem.getStartSizeGradients();
  61082. if (startSizeGradients) {
  61083. serializationObject.startSizeGradients = [];
  61084. for (var _j = 0, startSizeGradients_1 = startSizeGradients; _j < startSizeGradients_1.length; _j++) {
  61085. var startSizeGradient = startSizeGradients_1[_j];
  61086. var serializedGradient = {
  61087. gradient: startSizeGradient.gradient,
  61088. factor1: startSizeGradient.factor1
  61089. };
  61090. if (startSizeGradient.factor2 !== undefined) {
  61091. serializedGradient.factor2 = startSizeGradient.factor2;
  61092. }
  61093. serializationObject.startSizeGradients.push(serializedGradient);
  61094. }
  61095. }
  61096. var lifeTimeGradients = particleSystem.getLifeTimeGradients();
  61097. if (lifeTimeGradients) {
  61098. serializationObject.lifeTimeGradients = [];
  61099. for (var _k = 0, lifeTimeGradients_1 = lifeTimeGradients; _k < lifeTimeGradients_1.length; _k++) {
  61100. var lifeTimeGradient = lifeTimeGradients_1[_k];
  61101. var serializedGradient = {
  61102. gradient: lifeTimeGradient.gradient,
  61103. factor1: lifeTimeGradient.factor1
  61104. };
  61105. if (lifeTimeGradient.factor2 !== undefined) {
  61106. serializedGradient.factor2 = lifeTimeGradient.factor2;
  61107. }
  61108. serializationObject.lifeTimeGradients.push(serializedGradient);
  61109. }
  61110. }
  61111. var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  61112. if (limitVelocityGradients) {
  61113. serializationObject.limitVelocityGradients = [];
  61114. for (var _l = 0, limitVelocityGradients_1 = limitVelocityGradients; _l < limitVelocityGradients_1.length; _l++) {
  61115. var limitVelocityGradient = limitVelocityGradients_1[_l];
  61116. var serializedGradient = {
  61117. gradient: limitVelocityGradient.gradient,
  61118. factor1: limitVelocityGradient.factor1
  61119. };
  61120. if (limitVelocityGradient.factor2 !== undefined) {
  61121. serializedGradient.factor2 = limitVelocityGradient.factor2;
  61122. }
  61123. serializationObject.limitVelocityGradients.push(serializedGradient);
  61124. }
  61125. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  61126. }
  61127. if (particleSystem.noiseTexture) {
  61128. serializationObject.noiseTexture = particleSystem.noiseTexture.serialize();
  61129. }
  61130. };
  61131. /** @hidden */
  61132. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  61133. // Texture
  61134. if (parsedParticleSystem.textureName) {
  61135. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene, false, parsedParticleSystem.invertY !== undefined ? parsedParticleSystem.invertY : true);
  61136. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  61137. }
  61138. // Emitter
  61139. if (!parsedParticleSystem.emitterId && parsedParticleSystem.emitterId !== 0 && parsedParticleSystem.emitter === undefined) {
  61140. particleSystem.emitter = BABYLON.Vector3.Zero();
  61141. }
  61142. else if (parsedParticleSystem.emitterId) {
  61143. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  61144. }
  61145. else {
  61146. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  61147. }
  61148. // Misc.
  61149. if (parsedParticleSystem.renderingGroupId !== undefined) {
  61150. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  61151. }
  61152. if (parsedParticleSystem.isBillboardBased !== undefined) {
  61153. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  61154. }
  61155. if (parsedParticleSystem.billboardMode !== undefined) {
  61156. particleSystem.billboardMode = parsedParticleSystem.billboardMode;
  61157. }
  61158. // Animations
  61159. if (parsedParticleSystem.animations) {
  61160. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  61161. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  61162. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  61163. }
  61164. particleSystem.beginAnimationOnStart = parsedParticleSystem.beginAnimationOnStart;
  61165. particleSystem.beginAnimationFrom = parsedParticleSystem.beginAnimationFrom;
  61166. particleSystem.beginAnimationTo = parsedParticleSystem.beginAnimationTo;
  61167. particleSystem.beginAnimationLoop = parsedParticleSystem.beginAnimationLoop;
  61168. }
  61169. if (parsedParticleSystem.autoAnimate) {
  61170. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  61171. }
  61172. // Particle system
  61173. particleSystem.startDelay = parsedParticleSystem.startDelay | 0;
  61174. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  61175. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  61176. particleSystem.minSize = parsedParticleSystem.minSize;
  61177. particleSystem.maxSize = parsedParticleSystem.maxSize;
  61178. if (parsedParticleSystem.minScaleX) {
  61179. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  61180. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  61181. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  61182. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  61183. }
  61184. if (parsedParticleSystem.preWarmCycles !== undefined) {
  61185. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  61186. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  61187. }
  61188. if (parsedParticleSystem.minInitialRotation !== undefined) {
  61189. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  61190. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  61191. }
  61192. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  61193. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  61194. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  61195. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  61196. particleSystem.emitRate = parsedParticleSystem.emitRate;
  61197. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  61198. if (parsedParticleSystem.noiseStrength) {
  61199. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  61200. }
  61201. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  61202. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  61203. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  61204. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  61205. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  61206. particleSystem.blendMode = parsedParticleSystem.blendMode;
  61207. if (parsedParticleSystem.colorGradients) {
  61208. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  61209. var colorGradient = _a[_i];
  61210. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  61211. }
  61212. }
  61213. if (parsedParticleSystem.rampGradients) {
  61214. for (var _b = 0, _c = parsedParticleSystem.rampGradients; _b < _c.length; _b++) {
  61215. var rampGradient = _c[_b];
  61216. particleSystem.addRampGradient(rampGradient.gradient, BABYLON.Color3.FromArray(rampGradient.color));
  61217. }
  61218. particleSystem.useRampGradients = parsedParticleSystem.useRampGradients;
  61219. }
  61220. if (parsedParticleSystem.colorRemapGradients) {
  61221. for (var _d = 0, _e = parsedParticleSystem.colorRemapGradients; _d < _e.length; _d++) {
  61222. var colorRemapGradient = _e[_d];
  61223. particleSystem.addColorRemapGradient(colorRemapGradient.gradient, colorRemapGradient.factor1 !== undefined ? colorRemapGradient.factor1 : colorRemapGradient.factor, colorRemapGradient.factor2);
  61224. }
  61225. }
  61226. if (parsedParticleSystem.alphaRemapGradients) {
  61227. for (var _f = 0, _g = parsedParticleSystem.alphaRemapGradients; _f < _g.length; _f++) {
  61228. var alphaRemapGradient = _g[_f];
  61229. particleSystem.addAlphaRemapGradient(alphaRemapGradient.gradient, alphaRemapGradient.factor1 !== undefined ? alphaRemapGradient.factor1 : alphaRemapGradient.factor, alphaRemapGradient.factor2);
  61230. }
  61231. }
  61232. if (parsedParticleSystem.sizeGradients) {
  61233. for (var _h = 0, _j = parsedParticleSystem.sizeGradients; _h < _j.length; _h++) {
  61234. var sizeGradient = _j[_h];
  61235. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  61236. }
  61237. }
  61238. if (parsedParticleSystem.sizeGradients) {
  61239. for (var _k = 0, _l = parsedParticleSystem.sizeGradients; _k < _l.length; _k++) {
  61240. var sizeGradient = _l[_k];
  61241. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  61242. }
  61243. }
  61244. if (parsedParticleSystem.angularSpeedGradients) {
  61245. for (var _m = 0, _o = parsedParticleSystem.angularSpeedGradients; _m < _o.length; _m++) {
  61246. var angularSpeedGradient = _o[_m];
  61247. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  61248. }
  61249. }
  61250. if (parsedParticleSystem.velocityGradients) {
  61251. for (var _p = 0, _q = parsedParticleSystem.velocityGradients; _p < _q.length; _p++) {
  61252. var velocityGradient = _q[_p];
  61253. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  61254. }
  61255. }
  61256. if (parsedParticleSystem.dragGradients) {
  61257. for (var _r = 0, _s = parsedParticleSystem.dragGradients; _r < _s.length; _r++) {
  61258. var dragGradient = _s[_r];
  61259. particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== undefined ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2);
  61260. }
  61261. }
  61262. if (parsedParticleSystem.emitRateGradients) {
  61263. for (var _t = 0, _u = parsedParticleSystem.emitRateGradients; _t < _u.length; _t++) {
  61264. var emitRateGradient = _u[_t];
  61265. particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== undefined ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2);
  61266. }
  61267. }
  61268. if (parsedParticleSystem.startSizeGradients) {
  61269. for (var _v = 0, _w = parsedParticleSystem.startSizeGradients; _v < _w.length; _v++) {
  61270. var startSizeGradient = _w[_v];
  61271. particleSystem.addStartSizeGradient(startSizeGradient.gradient, startSizeGradient.factor1 !== undefined ? startSizeGradient.factor1 : startSizeGradient.factor, startSizeGradient.factor2);
  61272. }
  61273. }
  61274. if (parsedParticleSystem.lifeTimeGradients) {
  61275. for (var _x = 0, _y = parsedParticleSystem.lifeTimeGradients; _x < _y.length; _x++) {
  61276. var lifeTimeGradient = _y[_x];
  61277. particleSystem.addLifeTimeGradient(lifeTimeGradient.gradient, lifeTimeGradient.factor1 !== undefined ? lifeTimeGradient.factor1 : lifeTimeGradient.factor, lifeTimeGradient.factor2);
  61278. }
  61279. }
  61280. if (parsedParticleSystem.limitVelocityGradients) {
  61281. for (var _z = 0, _0 = parsedParticleSystem.limitVelocityGradients; _z < _0.length; _z++) {
  61282. var limitVelocityGradient = _0[_z];
  61283. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  61284. }
  61285. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  61286. }
  61287. if (parsedParticleSystem.noiseTexture) {
  61288. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  61289. }
  61290. // Emitter
  61291. var emitterType;
  61292. if (parsedParticleSystem.particleEmitterType) {
  61293. switch (parsedParticleSystem.particleEmitterType.type) {
  61294. case "SphereParticleEmitter":
  61295. emitterType = new BABYLON.SphereParticleEmitter();
  61296. break;
  61297. case "SphereDirectedParticleEmitter":
  61298. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  61299. break;
  61300. case "ConeEmitter":
  61301. case "ConeParticleEmitter":
  61302. emitterType = new BABYLON.ConeParticleEmitter();
  61303. break;
  61304. case "CylinderParticleEmitter":
  61305. emitterType = new BABYLON.CylinderParticleEmitter();
  61306. break;
  61307. case "HemisphericParticleEmitter":
  61308. emitterType = new BABYLON.HemisphericParticleEmitter();
  61309. break;
  61310. case "BoxEmitter":
  61311. case "BoxParticleEmitter":
  61312. default:
  61313. emitterType = new BABYLON.BoxParticleEmitter();
  61314. break;
  61315. }
  61316. emitterType.parse(parsedParticleSystem.particleEmitterType);
  61317. }
  61318. else {
  61319. emitterType = new BABYLON.BoxParticleEmitter();
  61320. emitterType.parse(parsedParticleSystem);
  61321. }
  61322. particleSystem.particleEmitterType = emitterType;
  61323. // Animation sheet
  61324. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  61325. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  61326. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  61327. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  61328. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  61329. particleSystem.spriteRandomStartCell = parsedParticleSystem.spriteRandomStartCell;
  61330. };
  61331. /**
  61332. * Parses a JSON object to create a particle system.
  61333. * @param parsedParticleSystem The JSON object to parse
  61334. * @param scene The scene to create the particle system in
  61335. * @param rootUrl The root url to use to load external dependencies like texture
  61336. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  61337. * @returns the Parsed particle system
  61338. */
  61339. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  61340. if (doNotStart === void 0) { doNotStart = false; }
  61341. var name = parsedParticleSystem.name;
  61342. var custom = null;
  61343. var program = null;
  61344. if (parsedParticleSystem.customShader) {
  61345. program = parsedParticleSystem.customShader;
  61346. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  61347. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  61348. }
  61349. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  61350. particleSystem.customShader = program;
  61351. if (parsedParticleSystem.id) {
  61352. particleSystem.id = parsedParticleSystem.id;
  61353. }
  61354. // SubEmitters
  61355. if (parsedParticleSystem.subEmitters) {
  61356. particleSystem.subEmitters = [];
  61357. for (var _i = 0, _a = parsedParticleSystem.subEmitters; _i < _a.length; _i++) {
  61358. var cell = _a[_i];
  61359. var cellArray = [];
  61360. for (var _b = 0, cell_1 = cell; _b < cell_1.length; _b++) {
  61361. var sub = cell_1[_b];
  61362. cellArray.push(BABYLON.SubEmitter.Parse(sub, scene, rootUrl));
  61363. }
  61364. particleSystem.subEmitters.push(cellArray);
  61365. }
  61366. }
  61367. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  61368. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  61369. // Auto start
  61370. if (parsedParticleSystem.preventAutoStart) {
  61371. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  61372. }
  61373. if (!doNotStart && !particleSystem.preventAutoStart) {
  61374. particleSystem.start();
  61375. }
  61376. return particleSystem;
  61377. };
  61378. /**
  61379. * Billboard mode will only apply to Y axis
  61380. */
  61381. ParticleSystem.BILLBOARDMODE_Y = 2;
  61382. /**
  61383. * Billboard mode will apply to all axes
  61384. */
  61385. ParticleSystem.BILLBOARDMODE_ALL = 7;
  61386. /**
  61387. * Special billboard mode where the particle will be biilboard to the camera but rotated to align with direction
  61388. */
  61389. ParticleSystem.BILLBOARDMODE_STRETCHED = 8;
  61390. return ParticleSystem;
  61391. }(BABYLON.BaseParticleSystem));
  61392. BABYLON.ParticleSystem = ParticleSystem;
  61393. })(BABYLON || (BABYLON = {}));
  61394. //# sourceMappingURL=babylon.particleSystem.js.map
  61395. var BABYLON;
  61396. (function (BABYLON) {
  61397. /**
  61398. * Particle emitter emitting particles from the inside of a box.
  61399. * It emits the particles randomly between 2 given directions.
  61400. */
  61401. var BoxParticleEmitter = /** @class */ (function () {
  61402. /**
  61403. * Creates a new instance BoxParticleEmitter
  61404. */
  61405. function BoxParticleEmitter() {
  61406. /**
  61407. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  61408. */
  61409. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  61410. /**
  61411. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  61412. */
  61413. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  61414. /**
  61415. * 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.
  61416. */
  61417. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  61418. /**
  61419. * 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.
  61420. */
  61421. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  61422. }
  61423. /**
  61424. * Called by the particle System when the direction is computed for the created particle.
  61425. * @param worldMatrix is the world matrix of the particle system
  61426. * @param directionToUpdate is the direction vector to update with the result
  61427. * @param particle is the particle we are computed the direction for
  61428. */
  61429. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61430. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  61431. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  61432. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  61433. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  61434. };
  61435. /**
  61436. * Called by the particle System when the position is computed for the created particle.
  61437. * @param worldMatrix is the world matrix of the particle system
  61438. * @param positionToUpdate is the position vector to update with the result
  61439. * @param particle is the particle we are computed the position for
  61440. */
  61441. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  61442. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  61443. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  61444. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  61445. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  61446. };
  61447. /**
  61448. * Clones the current emitter and returns a copy of it
  61449. * @returns the new emitter
  61450. */
  61451. BoxParticleEmitter.prototype.clone = function () {
  61452. var newOne = new BoxParticleEmitter();
  61453. BABYLON.Tools.DeepCopy(this, newOne);
  61454. return newOne;
  61455. };
  61456. /**
  61457. * Called by the GPUParticleSystem to setup the update shader
  61458. * @param effect defines the update shader
  61459. */
  61460. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  61461. effect.setVector3("direction1", this.direction1);
  61462. effect.setVector3("direction2", this.direction2);
  61463. effect.setVector3("minEmitBox", this.minEmitBox);
  61464. effect.setVector3("maxEmitBox", this.maxEmitBox);
  61465. };
  61466. /**
  61467. * Returns a string to use to update the GPU particles update shader
  61468. * @returns a string containng the defines string
  61469. */
  61470. BoxParticleEmitter.prototype.getEffectDefines = function () {
  61471. return "#define BOXEMITTER";
  61472. };
  61473. /**
  61474. * Returns the string "BoxParticleEmitter"
  61475. * @returns a string containing the class name
  61476. */
  61477. BoxParticleEmitter.prototype.getClassName = function () {
  61478. return "BoxParticleEmitter";
  61479. };
  61480. /**
  61481. * Serializes the particle system to a JSON object.
  61482. * @returns the JSON object
  61483. */
  61484. BoxParticleEmitter.prototype.serialize = function () {
  61485. var serializationObject = {};
  61486. serializationObject.type = this.getClassName();
  61487. serializationObject.direction1 = this.direction1.asArray();
  61488. serializationObject.direction2 = this.direction2.asArray();
  61489. serializationObject.minEmitBox = this.minEmitBox.asArray();
  61490. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  61491. return serializationObject;
  61492. };
  61493. /**
  61494. * Parse properties from a JSON object
  61495. * @param serializationObject defines the JSON object
  61496. */
  61497. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  61498. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  61499. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  61500. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  61501. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  61502. };
  61503. return BoxParticleEmitter;
  61504. }());
  61505. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  61506. })(BABYLON || (BABYLON = {}));
  61507. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  61508. var BABYLON;
  61509. (function (BABYLON) {
  61510. /**
  61511. * Particle emitter emitting particles from the inside of a cylinder.
  61512. * It emits the particles alongside the cylinder radius. The emission direction might be randomized.
  61513. */
  61514. var CylinderParticleEmitter = /** @class */ (function () {
  61515. /**
  61516. * Creates a new instance CylinderParticleEmitter
  61517. * @param radius the radius of the emission cylinder (1 by default)
  61518. * @param height the height of the emission cylinder (1 by default)
  61519. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  61520. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  61521. */
  61522. function CylinderParticleEmitter(
  61523. /**
  61524. * The radius of the emission cylinder.
  61525. */
  61526. radius,
  61527. /**
  61528. * The height of the emission cylinder.
  61529. */
  61530. height,
  61531. /**
  61532. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  61533. */
  61534. radiusRange,
  61535. /**
  61536. * How much to randomize the particle direction [0-1].
  61537. */
  61538. directionRandomizer) {
  61539. if (radius === void 0) { radius = 1; }
  61540. if (height === void 0) { height = 1; }
  61541. if (radiusRange === void 0) { radiusRange = 1; }
  61542. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  61543. this.radius = radius;
  61544. this.height = height;
  61545. this.radiusRange = radiusRange;
  61546. this.directionRandomizer = directionRandomizer;
  61547. }
  61548. /**
  61549. * Called by the particle System when the direction is computed for the created particle.
  61550. * @param worldMatrix is the world matrix of the particle system
  61551. * @param directionToUpdate is the direction vector to update with the result
  61552. * @param particle is the particle we are computed the direction for
  61553. */
  61554. CylinderParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61555. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  61556. var randY = BABYLON.Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2);
  61557. var angle = Math.atan2(direction.x, direction.z);
  61558. angle += BABYLON.Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer;
  61559. direction.y = randY; // set direction y to rand y to mirror normal of cylinder surface
  61560. direction.x = Math.sin(angle);
  61561. direction.z = Math.cos(angle);
  61562. direction.normalize();
  61563. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  61564. };
  61565. /**
  61566. * Called by the particle System when the position is computed for the created particle.
  61567. * @param worldMatrix is the world matrix of the particle system
  61568. * @param positionToUpdate is the position vector to update with the result
  61569. * @param particle is the particle we are computed the position for
  61570. */
  61571. CylinderParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  61572. var yPos = BABYLON.Scalar.RandomRange(-this.height / 2, this.height / 2);
  61573. var angle = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  61574. // Pick a properly distributed point within the circle https://programming.guide/random-point-within-circle.html
  61575. var radiusDistribution = BABYLON.Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1);
  61576. var positionRadius = Math.sqrt(radiusDistribution) * this.radius;
  61577. var xPos = positionRadius * Math.cos(angle);
  61578. var zPos = positionRadius * Math.sin(angle);
  61579. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate);
  61580. };
  61581. /**
  61582. * Clones the current emitter and returns a copy of it
  61583. * @returns the new emitter
  61584. */
  61585. CylinderParticleEmitter.prototype.clone = function () {
  61586. var newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer);
  61587. BABYLON.Tools.DeepCopy(this, newOne);
  61588. return newOne;
  61589. };
  61590. /**
  61591. * Called by the GPUParticleSystem to setup the update shader
  61592. * @param effect defines the update shader
  61593. */
  61594. CylinderParticleEmitter.prototype.applyToShader = function (effect) {
  61595. effect.setFloat("radius", this.radius);
  61596. effect.setFloat("height", this.height);
  61597. effect.setFloat("radiusRange", this.radiusRange);
  61598. effect.setFloat("directionRandomizer", this.directionRandomizer);
  61599. };
  61600. /**
  61601. * Returns a string to use to update the GPU particles update shader
  61602. * @returns a string containng the defines string
  61603. */
  61604. CylinderParticleEmitter.prototype.getEffectDefines = function () {
  61605. return "#define CYLINDEREMITTER";
  61606. };
  61607. /**
  61608. * Returns the string "CylinderParticleEmitter"
  61609. * @returns a string containing the class name
  61610. */
  61611. CylinderParticleEmitter.prototype.getClassName = function () {
  61612. return "CylinderParticleEmitter";
  61613. };
  61614. /**
  61615. * Serializes the particle system to a JSON object.
  61616. * @returns the JSON object
  61617. */
  61618. CylinderParticleEmitter.prototype.serialize = function () {
  61619. var serializationObject = {};
  61620. serializationObject.type = this.getClassName();
  61621. serializationObject.radius = this.radius;
  61622. serializationObject.height = this.height;
  61623. serializationObject.radiusRange = this.radiusRange;
  61624. serializationObject.directionRandomizer = this.directionRandomizer;
  61625. return serializationObject;
  61626. };
  61627. /**
  61628. * Parse properties from a JSON object
  61629. * @param serializationObject defines the JSON object
  61630. */
  61631. CylinderParticleEmitter.prototype.parse = function (serializationObject) {
  61632. this.radius = serializationObject.radius;
  61633. this.height = serializationObject.height;
  61634. this.radiusRange = serializationObject.radiusRange;
  61635. this.directionRandomizer = serializationObject.directionRandomizer;
  61636. };
  61637. return CylinderParticleEmitter;
  61638. }());
  61639. BABYLON.CylinderParticleEmitter = CylinderParticleEmitter;
  61640. /**
  61641. * Particle emitter emitting particles from the inside of a cylinder.
  61642. * It emits the particles randomly between two vectors.
  61643. */
  61644. var CylinderDirectedParticleEmitter = /** @class */ (function (_super) {
  61645. __extends(CylinderDirectedParticleEmitter, _super);
  61646. /**
  61647. * Creates a new instance CylinderDirectedParticleEmitter
  61648. * @param radius the radius of the emission cylinder (1 by default)
  61649. * @param height the height of the emission cylinder (1 by default)
  61650. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  61651. * @param direction1 the min limit of the emission direction (up vector by default)
  61652. * @param direction2 the max limit of the emission direction (up vector by default)
  61653. */
  61654. function CylinderDirectedParticleEmitter(radius, height, radiusRange,
  61655. /**
  61656. * The min limit of the emission direction.
  61657. */
  61658. direction1,
  61659. /**
  61660. * The max limit of the emission direction.
  61661. */
  61662. direction2) {
  61663. if (radius === void 0) { radius = 1; }
  61664. if (height === void 0) { height = 1; }
  61665. if (radiusRange === void 0) { radiusRange = 1; }
  61666. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  61667. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  61668. var _this = _super.call(this, radius, height, radiusRange) || this;
  61669. _this.direction1 = direction1;
  61670. _this.direction2 = direction2;
  61671. return _this;
  61672. }
  61673. /**
  61674. * Called by the particle System when the direction is computed for the created particle.
  61675. * @param worldMatrix is the world matrix of the particle system
  61676. * @param directionToUpdate is the direction vector to update with the result
  61677. * @param particle is the particle we are computed the direction for
  61678. */
  61679. CylinderDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61680. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  61681. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  61682. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  61683. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  61684. };
  61685. /**
  61686. * Clones the current emitter and returns a copy of it
  61687. * @returns the new emitter
  61688. */
  61689. CylinderDirectedParticleEmitter.prototype.clone = function () {
  61690. var newOne = new CylinderDirectedParticleEmitter(this.radius, this.height, this.radiusRange, this.direction1, this.direction2);
  61691. BABYLON.Tools.DeepCopy(this, newOne);
  61692. return newOne;
  61693. };
  61694. /**
  61695. * Called by the GPUParticleSystem to setup the update shader
  61696. * @param effect defines the update shader
  61697. */
  61698. CylinderDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  61699. effect.setFloat("radius", this.radius);
  61700. effect.setFloat("height", this.height);
  61701. effect.setFloat("radiusRange", this.radiusRange);
  61702. effect.setVector3("direction1", this.direction1);
  61703. effect.setVector3("direction2", this.direction2);
  61704. };
  61705. /**
  61706. * Returns a string to use to update the GPU particles update shader
  61707. * @returns a string containng the defines string
  61708. */
  61709. CylinderDirectedParticleEmitter.prototype.getEffectDefines = function () {
  61710. return "#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER";
  61711. };
  61712. /**
  61713. * Returns the string "CylinderDirectedParticleEmitter"
  61714. * @returns a string containing the class name
  61715. */
  61716. CylinderDirectedParticleEmitter.prototype.getClassName = function () {
  61717. return "CylinderDirectedParticleEmitter";
  61718. };
  61719. /**
  61720. * Serializes the particle system to a JSON object.
  61721. * @returns the JSON object
  61722. */
  61723. CylinderDirectedParticleEmitter.prototype.serialize = function () {
  61724. var serializationObject = _super.prototype.serialize.call(this);
  61725. serializationObject.direction1 = this.direction1.asArray();
  61726. serializationObject.direction2 = this.direction2.asArray();
  61727. return serializationObject;
  61728. };
  61729. /**
  61730. * Parse properties from a JSON object
  61731. * @param serializationObject defines the JSON object
  61732. */
  61733. CylinderDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  61734. _super.prototype.parse.call(this, serializationObject);
  61735. this.direction1.copyFrom(serializationObject.direction1);
  61736. this.direction2.copyFrom(serializationObject.direction2);
  61737. };
  61738. return CylinderDirectedParticleEmitter;
  61739. }(CylinderParticleEmitter));
  61740. BABYLON.CylinderDirectedParticleEmitter = CylinderDirectedParticleEmitter;
  61741. })(BABYLON || (BABYLON = {}));
  61742. //# sourceMappingURL=babylon.cylinderParticleEmitter.js.map
  61743. var BABYLON;
  61744. (function (BABYLON) {
  61745. /**
  61746. * Particle emitter emitting particles from the inside of a cone.
  61747. * It emits the particles alongside the cone volume from the base to the particle.
  61748. * The emission direction might be randomized.
  61749. */
  61750. var ConeParticleEmitter = /** @class */ (function () {
  61751. /**
  61752. * Creates a new instance ConeParticleEmitter
  61753. * @param radius the radius of the emission cone (1 by default)
  61754. * @param angles the cone base angle (PI by default)
  61755. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  61756. */
  61757. function ConeParticleEmitter(radius, angle,
  61758. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  61759. directionRandomizer) {
  61760. if (radius === void 0) { radius = 1; }
  61761. if (angle === void 0) { angle = Math.PI; }
  61762. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  61763. this.directionRandomizer = directionRandomizer;
  61764. /**
  61765. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  61766. */
  61767. this.radiusRange = 1;
  61768. /**
  61769. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  61770. */
  61771. this.heightRange = 1;
  61772. /**
  61773. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  61774. */
  61775. this.emitFromSpawnPointOnly = false;
  61776. this.angle = angle;
  61777. this.radius = radius;
  61778. }
  61779. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  61780. /**
  61781. * Gets or sets the radius of the emission cone
  61782. */
  61783. get: function () {
  61784. return this._radius;
  61785. },
  61786. set: function (value) {
  61787. this._radius = value;
  61788. this._buildHeight();
  61789. },
  61790. enumerable: true,
  61791. configurable: true
  61792. });
  61793. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  61794. /**
  61795. * Gets or sets the angle of the emission cone
  61796. */
  61797. get: function () {
  61798. return this._angle;
  61799. },
  61800. set: function (value) {
  61801. this._angle = value;
  61802. this._buildHeight();
  61803. },
  61804. enumerable: true,
  61805. configurable: true
  61806. });
  61807. ConeParticleEmitter.prototype._buildHeight = function () {
  61808. if (this._angle !== 0) {
  61809. this._height = this._radius / Math.tan(this._angle / 2);
  61810. }
  61811. else {
  61812. this._height = 1;
  61813. }
  61814. };
  61815. /**
  61816. * Called by the particle System when the direction is computed for the created particle.
  61817. * @param worldMatrix is the world matrix of the particle system
  61818. * @param directionToUpdate is the direction vector to update with the result
  61819. * @param particle is the particle we are computed the direction for
  61820. */
  61821. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61822. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  61823. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  61824. }
  61825. else {
  61826. // measure the direction Vector from the emitter to the particle.
  61827. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  61828. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61829. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61830. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61831. direction.x += randX;
  61832. direction.y += randY;
  61833. direction.z += randZ;
  61834. direction.normalize();
  61835. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  61836. }
  61837. };
  61838. /**
  61839. * Called by the particle System when the position is computed for the created particle.
  61840. * @param worldMatrix is the world matrix of the particle system
  61841. * @param positionToUpdate is the position vector to update with the result
  61842. * @param particle is the particle we are computed the position for
  61843. */
  61844. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  61845. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  61846. var h;
  61847. if (!this.emitFromSpawnPointOnly) {
  61848. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  61849. // Better distribution in a cone at normal angles.
  61850. h = 1 - h * h;
  61851. }
  61852. else {
  61853. h = 0.0001;
  61854. }
  61855. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  61856. radius = radius * h;
  61857. var randX = radius * Math.sin(s);
  61858. var randZ = radius * Math.cos(s);
  61859. var randY = h * this._height;
  61860. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  61861. };
  61862. /**
  61863. * Clones the current emitter and returns a copy of it
  61864. * @returns the new emitter
  61865. */
  61866. ConeParticleEmitter.prototype.clone = function () {
  61867. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  61868. BABYLON.Tools.DeepCopy(this, newOne);
  61869. return newOne;
  61870. };
  61871. /**
  61872. * Called by the GPUParticleSystem to setup the update shader
  61873. * @param effect defines the update shader
  61874. */
  61875. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  61876. effect.setFloat2("radius", this._radius, this.radiusRange);
  61877. effect.setFloat("coneAngle", this._angle);
  61878. effect.setFloat2("height", this._height, this.heightRange);
  61879. effect.setFloat("directionRandomizer", this.directionRandomizer);
  61880. };
  61881. /**
  61882. * Returns a string to use to update the GPU particles update shader
  61883. * @returns a string containng the defines string
  61884. */
  61885. ConeParticleEmitter.prototype.getEffectDefines = function () {
  61886. var defines = "#define CONEEMITTER";
  61887. if (this.emitFromSpawnPointOnly) {
  61888. defines += "\n#define CONEEMITTERSPAWNPOINT";
  61889. }
  61890. return defines;
  61891. };
  61892. /**
  61893. * Returns the string "ConeParticleEmitter"
  61894. * @returns a string containing the class name
  61895. */
  61896. ConeParticleEmitter.prototype.getClassName = function () {
  61897. return "ConeParticleEmitter";
  61898. };
  61899. /**
  61900. * Serializes the particle system to a JSON object.
  61901. * @returns the JSON object
  61902. */
  61903. ConeParticleEmitter.prototype.serialize = function () {
  61904. var serializationObject = {};
  61905. serializationObject.type = this.getClassName();
  61906. serializationObject.radius = this._radius;
  61907. serializationObject.angle = this._angle;
  61908. serializationObject.directionRandomizer = this.directionRandomizer;
  61909. return serializationObject;
  61910. };
  61911. /**
  61912. * Parse properties from a JSON object
  61913. * @param serializationObject defines the JSON object
  61914. */
  61915. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  61916. this.radius = serializationObject.radius;
  61917. this.angle = serializationObject.angle;
  61918. this.directionRandomizer = serializationObject.directionRandomizer;
  61919. };
  61920. return ConeParticleEmitter;
  61921. }());
  61922. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  61923. })(BABYLON || (BABYLON = {}));
  61924. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  61925. var BABYLON;
  61926. (function (BABYLON) {
  61927. /**
  61928. * Particle emitter emitting particles from the inside of a sphere.
  61929. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  61930. */
  61931. var SphereParticleEmitter = /** @class */ (function () {
  61932. /**
  61933. * Creates a new instance SphereParticleEmitter
  61934. * @param radius the radius of the emission sphere (1 by default)
  61935. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  61936. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  61937. */
  61938. function SphereParticleEmitter(
  61939. /**
  61940. * The radius of the emission sphere.
  61941. */
  61942. radius,
  61943. /**
  61944. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  61945. */
  61946. radiusRange,
  61947. /**
  61948. * How much to randomize the particle direction [0-1].
  61949. */
  61950. directionRandomizer) {
  61951. if (radius === void 0) { radius = 1; }
  61952. if (radiusRange === void 0) { radiusRange = 1; }
  61953. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  61954. this.radius = radius;
  61955. this.radiusRange = radiusRange;
  61956. this.directionRandomizer = directionRandomizer;
  61957. }
  61958. /**
  61959. * Called by the particle System when the direction is computed for the created particle.
  61960. * @param worldMatrix is the world matrix of the particle system
  61961. * @param directionToUpdate is the direction vector to update with the result
  61962. * @param particle is the particle we are computed the direction for
  61963. */
  61964. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61965. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  61966. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61967. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61968. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61969. direction.x += randX;
  61970. direction.y += randY;
  61971. direction.z += randZ;
  61972. direction.normalize();
  61973. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  61974. };
  61975. /**
  61976. * Called by the particle System when the position is computed for the created particle.
  61977. * @param worldMatrix is the world matrix of the particle system
  61978. * @param positionToUpdate is the position vector to update with the result
  61979. * @param particle is the particle we are computed the position for
  61980. */
  61981. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  61982. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  61983. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  61984. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  61985. var theta = Math.acos(2 * v - 1);
  61986. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  61987. var randY = randRadius * Math.cos(theta);
  61988. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  61989. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  61990. };
  61991. /**
  61992. * Clones the current emitter and returns a copy of it
  61993. * @returns the new emitter
  61994. */
  61995. SphereParticleEmitter.prototype.clone = function () {
  61996. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  61997. BABYLON.Tools.DeepCopy(this, newOne);
  61998. return newOne;
  61999. };
  62000. /**
  62001. * Called by the GPUParticleSystem to setup the update shader
  62002. * @param effect defines the update shader
  62003. */
  62004. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  62005. effect.setFloat("radius", this.radius);
  62006. effect.setFloat("radiusRange", this.radiusRange);
  62007. effect.setFloat("directionRandomizer", this.directionRandomizer);
  62008. };
  62009. /**
  62010. * Returns a string to use to update the GPU particles update shader
  62011. * @returns a string containng the defines string
  62012. */
  62013. SphereParticleEmitter.prototype.getEffectDefines = function () {
  62014. return "#define SPHEREEMITTER";
  62015. };
  62016. /**
  62017. * Returns the string "SphereParticleEmitter"
  62018. * @returns a string containing the class name
  62019. */
  62020. SphereParticleEmitter.prototype.getClassName = function () {
  62021. return "SphereParticleEmitter";
  62022. };
  62023. /**
  62024. * Serializes the particle system to a JSON object.
  62025. * @returns the JSON object
  62026. */
  62027. SphereParticleEmitter.prototype.serialize = function () {
  62028. var serializationObject = {};
  62029. serializationObject.type = this.getClassName();
  62030. serializationObject.radius = this.radius;
  62031. serializationObject.radiusRange = this.radiusRange;
  62032. serializationObject.directionRandomizer = this.directionRandomizer;
  62033. return serializationObject;
  62034. };
  62035. /**
  62036. * Parse properties from a JSON object
  62037. * @param serializationObject defines the JSON object
  62038. */
  62039. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  62040. this.radius = serializationObject.radius;
  62041. this.radiusRange = serializationObject.radiusRange;
  62042. this.directionRandomizer = serializationObject.directionRandomizer;
  62043. };
  62044. return SphereParticleEmitter;
  62045. }());
  62046. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  62047. /**
  62048. * Particle emitter emitting particles from the inside of a sphere.
  62049. * It emits the particles randomly between two vectors.
  62050. */
  62051. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  62052. __extends(SphereDirectedParticleEmitter, _super);
  62053. /**
  62054. * Creates a new instance SphereDirectedParticleEmitter
  62055. * @param radius the radius of the emission sphere (1 by default)
  62056. * @param direction1 the min limit of the emission direction (up vector by default)
  62057. * @param direction2 the max limit of the emission direction (up vector by default)
  62058. */
  62059. function SphereDirectedParticleEmitter(radius,
  62060. /**
  62061. * The min limit of the emission direction.
  62062. */
  62063. direction1,
  62064. /**
  62065. * The max limit of the emission direction.
  62066. */
  62067. direction2) {
  62068. if (radius === void 0) { radius = 1; }
  62069. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  62070. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  62071. var _this = _super.call(this, radius) || this;
  62072. _this.direction1 = direction1;
  62073. _this.direction2 = direction2;
  62074. return _this;
  62075. }
  62076. /**
  62077. * Called by the particle System when the direction is computed for the created particle.
  62078. * @param worldMatrix is the world matrix of the particle system
  62079. * @param directionToUpdate is the direction vector to update with the result
  62080. * @param particle is the particle we are computed the direction for
  62081. */
  62082. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  62083. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  62084. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  62085. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  62086. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  62087. };
  62088. /**
  62089. * Clones the current emitter and returns a copy of it
  62090. * @returns the new emitter
  62091. */
  62092. SphereDirectedParticleEmitter.prototype.clone = function () {
  62093. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  62094. BABYLON.Tools.DeepCopy(this, newOne);
  62095. return newOne;
  62096. };
  62097. /**
  62098. * Called by the GPUParticleSystem to setup the update shader
  62099. * @param effect defines the update shader
  62100. */
  62101. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  62102. effect.setFloat("radius", this.radius);
  62103. effect.setFloat("radiusRange", this.radiusRange);
  62104. effect.setVector3("direction1", this.direction1);
  62105. effect.setVector3("direction2", this.direction2);
  62106. };
  62107. /**
  62108. * Returns a string to use to update the GPU particles update shader
  62109. * @returns a string containng the defines string
  62110. */
  62111. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  62112. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  62113. };
  62114. /**
  62115. * Returns the string "SphereDirectedParticleEmitter"
  62116. * @returns a string containing the class name
  62117. */
  62118. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  62119. return "SphereDirectedParticleEmitter";
  62120. };
  62121. /**
  62122. * Serializes the particle system to a JSON object.
  62123. * @returns the JSON object
  62124. */
  62125. SphereDirectedParticleEmitter.prototype.serialize = function () {
  62126. var serializationObject = _super.prototype.serialize.call(this);
  62127. serializationObject.direction1 = this.direction1.asArray();
  62128. serializationObject.direction2 = this.direction2.asArray();
  62129. return serializationObject;
  62130. };
  62131. /**
  62132. * Parse properties from a JSON object
  62133. * @param serializationObject defines the JSON object
  62134. */
  62135. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  62136. _super.prototype.parse.call(this, serializationObject);
  62137. this.direction1.copyFrom(serializationObject.direction1);
  62138. this.direction2.copyFrom(serializationObject.direction2);
  62139. };
  62140. return SphereDirectedParticleEmitter;
  62141. }(SphereParticleEmitter));
  62142. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  62143. })(BABYLON || (BABYLON = {}));
  62144. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  62145. var BABYLON;
  62146. (function (BABYLON) {
  62147. /**
  62148. * Particle emitter emitting particles from the inside of a hemisphere.
  62149. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  62150. */
  62151. var HemisphericParticleEmitter = /** @class */ (function () {
  62152. /**
  62153. * Creates a new instance HemisphericParticleEmitter
  62154. * @param radius the radius of the emission hemisphere (1 by default)
  62155. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  62156. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  62157. */
  62158. function HemisphericParticleEmitter(
  62159. /**
  62160. * The radius of the emission hemisphere.
  62161. */
  62162. radius,
  62163. /**
  62164. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  62165. */
  62166. radiusRange,
  62167. /**
  62168. * How much to randomize the particle direction [0-1].
  62169. */
  62170. directionRandomizer) {
  62171. if (radius === void 0) { radius = 1; }
  62172. if (radiusRange === void 0) { radiusRange = 1; }
  62173. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  62174. this.radius = radius;
  62175. this.radiusRange = radiusRange;
  62176. this.directionRandomizer = directionRandomizer;
  62177. }
  62178. /**
  62179. * Called by the particle System when the direction is computed for the created particle.
  62180. * @param worldMatrix is the world matrix of the particle system
  62181. * @param directionToUpdate is the direction vector to update with the result
  62182. * @param particle is the particle we are computed the direction for
  62183. */
  62184. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  62185. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  62186. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  62187. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  62188. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  62189. direction.x += randX;
  62190. direction.y += randY;
  62191. direction.z += randZ;
  62192. direction.normalize();
  62193. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  62194. };
  62195. /**
  62196. * Called by the particle System when the position is computed for the created particle.
  62197. * @param worldMatrix is the world matrix of the particle system
  62198. * @param positionToUpdate is the position vector to update with the result
  62199. * @param particle is the particle we are computed the position for
  62200. */
  62201. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  62202. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  62203. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  62204. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  62205. var theta = Math.acos(2 * v - 1);
  62206. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  62207. var randY = randRadius * Math.cos(theta);
  62208. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  62209. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  62210. };
  62211. /**
  62212. * Clones the current emitter and returns a copy of it
  62213. * @returns the new emitter
  62214. */
  62215. HemisphericParticleEmitter.prototype.clone = function () {
  62216. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  62217. BABYLON.Tools.DeepCopy(this, newOne);
  62218. return newOne;
  62219. };
  62220. /**
  62221. * Called by the GPUParticleSystem to setup the update shader
  62222. * @param effect defines the update shader
  62223. */
  62224. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  62225. effect.setFloat("radius", this.radius);
  62226. effect.setFloat("radiusRange", this.radiusRange);
  62227. effect.setFloat("directionRandomizer", this.directionRandomizer);
  62228. };
  62229. /**
  62230. * Returns a string to use to update the GPU particles update shader
  62231. * @returns a string containng the defines string
  62232. */
  62233. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  62234. return "#define HEMISPHERICEMITTER";
  62235. };
  62236. /**
  62237. * Returns the string "HemisphericParticleEmitter"
  62238. * @returns a string containing the class name
  62239. */
  62240. HemisphericParticleEmitter.prototype.getClassName = function () {
  62241. return "HemisphericParticleEmitter";
  62242. };
  62243. /**
  62244. * Serializes the particle system to a JSON object.
  62245. * @returns the JSON object
  62246. */
  62247. HemisphericParticleEmitter.prototype.serialize = function () {
  62248. var serializationObject = {};
  62249. serializationObject.type = this.getClassName();
  62250. serializationObject.radius = this.radius;
  62251. serializationObject.radiusRange = this.radiusRange;
  62252. serializationObject.directionRandomizer = this.directionRandomizer;
  62253. return serializationObject;
  62254. };
  62255. /**
  62256. * Parse properties from a JSON object
  62257. * @param serializationObject defines the JSON object
  62258. */
  62259. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  62260. this.radius = serializationObject.radius;
  62261. this.radiusRange = serializationObject.radiusRange;
  62262. this.directionRandomizer = serializationObject.directionRandomizer;
  62263. };
  62264. return HemisphericParticleEmitter;
  62265. }());
  62266. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  62267. })(BABYLON || (BABYLON = {}));
  62268. //# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map
  62269. var BABYLON;
  62270. (function (BABYLON) {
  62271. /**
  62272. * Particle emitter emitting particles from a point.
  62273. * It emits the particles randomly between 2 given directions.
  62274. */
  62275. var PointParticleEmitter = /** @class */ (function () {
  62276. /**
  62277. * Creates a new instance PointParticleEmitter
  62278. */
  62279. function PointParticleEmitter() {
  62280. /**
  62281. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  62282. */
  62283. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  62284. /**
  62285. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  62286. */
  62287. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  62288. }
  62289. /**
  62290. * Called by the particle System when the direction is computed for the created particle.
  62291. * @param worldMatrix is the world matrix of the particle system
  62292. * @param directionToUpdate is the direction vector to update with the result
  62293. * @param particle is the particle we are computed the direction for
  62294. */
  62295. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  62296. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  62297. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  62298. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  62299. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  62300. };
  62301. /**
  62302. * Called by the particle System when the position is computed for the created particle.
  62303. * @param worldMatrix is the world matrix of the particle system
  62304. * @param positionToUpdate is the position vector to update with the result
  62305. * @param particle is the particle we are computed the position for
  62306. */
  62307. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  62308. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  62309. };
  62310. /**
  62311. * Clones the current emitter and returns a copy of it
  62312. * @returns the new emitter
  62313. */
  62314. PointParticleEmitter.prototype.clone = function () {
  62315. var newOne = new PointParticleEmitter();
  62316. BABYLON.Tools.DeepCopy(this, newOne);
  62317. return newOne;
  62318. };
  62319. /**
  62320. * Called by the GPUParticleSystem to setup the update shader
  62321. * @param effect defines the update shader
  62322. */
  62323. PointParticleEmitter.prototype.applyToShader = function (effect) {
  62324. effect.setVector3("direction1", this.direction1);
  62325. effect.setVector3("direction2", this.direction2);
  62326. };
  62327. /**
  62328. * Returns a string to use to update the GPU particles update shader
  62329. * @returns a string containng the defines string
  62330. */
  62331. PointParticleEmitter.prototype.getEffectDefines = function () {
  62332. return "#define POINTEMITTER";
  62333. };
  62334. /**
  62335. * Returns the string "PointParticleEmitter"
  62336. * @returns a string containing the class name
  62337. */
  62338. PointParticleEmitter.prototype.getClassName = function () {
  62339. return "PointParticleEmitter";
  62340. };
  62341. /**
  62342. * Serializes the particle system to a JSON object.
  62343. * @returns the JSON object
  62344. */
  62345. PointParticleEmitter.prototype.serialize = function () {
  62346. var serializationObject = {};
  62347. serializationObject.type = this.getClassName();
  62348. serializationObject.direction1 = this.direction1.asArray();
  62349. serializationObject.direction2 = this.direction2.asArray();
  62350. return serializationObject;
  62351. };
  62352. /**
  62353. * Parse properties from a JSON object
  62354. * @param serializationObject defines the JSON object
  62355. */
  62356. PointParticleEmitter.prototype.parse = function (serializationObject) {
  62357. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  62358. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  62359. };
  62360. return PointParticleEmitter;
  62361. }());
  62362. BABYLON.PointParticleEmitter = PointParticleEmitter;
  62363. })(BABYLON || (BABYLON = {}));
  62364. //# sourceMappingURL=babylon.pointParticleEmitter.js.map
  62365. var BABYLON;
  62366. (function (BABYLON) {
  62367. // Adds the parsers to the scene parsers.
  62368. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  62369. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  62370. if (!individualParser) {
  62371. return;
  62372. }
  62373. // Particles Systems
  62374. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  62375. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  62376. var parsedParticleSystem = parsedData.particleSystems[index];
  62377. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  62378. }
  62379. }
  62380. });
  62381. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  62382. if (parsedParticleSystem.activeParticleCount) {
  62383. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  62384. return ps;
  62385. }
  62386. else {
  62387. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  62388. return ps;
  62389. }
  62390. });
  62391. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  62392. if (uniformsNames === void 0) { uniformsNames = []; }
  62393. if (samplers === void 0) { samplers = []; }
  62394. if (defines === void 0) { defines = ""; }
  62395. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  62396. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  62397. if (defines.indexOf(" BILLBOARD") === -1) {
  62398. defines += "\n#define BILLBOARD\n";
  62399. }
  62400. if (samplers.indexOf("diffuseSampler") === -1) {
  62401. samplers.push("diffuseSampler");
  62402. }
  62403. return this.createEffect({
  62404. vertex: "particles",
  62405. fragmentElement: fragmentName
  62406. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  62407. };
  62408. BABYLON.Mesh.prototype.getEmittedParticleSystems = function () {
  62409. var results = new Array();
  62410. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  62411. var particleSystem = this.getScene().particleSystems[index];
  62412. if (particleSystem.emitter === this) {
  62413. results.push(particleSystem);
  62414. }
  62415. }
  62416. return results;
  62417. };
  62418. BABYLON.Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  62419. var results = new Array();
  62420. var descendants = this.getDescendants();
  62421. descendants.push(this);
  62422. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  62423. var particleSystem = this.getScene().particleSystems[index];
  62424. var emitter = particleSystem.emitter;
  62425. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  62426. results.push(particleSystem);
  62427. }
  62428. }
  62429. return results;
  62430. };
  62431. })(BABYLON || (BABYLON = {}));
  62432. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  62433. var BABYLON;
  62434. (function (BABYLON) {
  62435. /**
  62436. * Type of sub emitter
  62437. */
  62438. var SubEmitterType;
  62439. (function (SubEmitterType) {
  62440. /**
  62441. * Attached to the particle over it's lifetime
  62442. */
  62443. SubEmitterType[SubEmitterType["ATTACHED"] = 0] = "ATTACHED";
  62444. /**
  62445. * Created when the particle dies
  62446. */
  62447. SubEmitterType[SubEmitterType["END"] = 1] = "END";
  62448. })(SubEmitterType = BABYLON.SubEmitterType || (BABYLON.SubEmitterType = {}));
  62449. /**
  62450. * Sub emitter class used to emit particles from an existing particle
  62451. */
  62452. var SubEmitter = /** @class */ (function () {
  62453. /**
  62454. * Creates a sub emitter
  62455. * @param particleSystem the particle system to be used by the sub emitter
  62456. */
  62457. function SubEmitter(
  62458. /**
  62459. * the particle system to be used by the sub emitter
  62460. */
  62461. particleSystem) {
  62462. this.particleSystem = particleSystem;
  62463. /**
  62464. * Type of the submitter (Default: END)
  62465. */
  62466. this.type = SubEmitterType.END;
  62467. /**
  62468. * 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)
  62469. * Note: This only is supported when using an emitter of type Mesh
  62470. */
  62471. this.inheritDirection = false;
  62472. /**
  62473. * How much of the attached particles speed should be added to the sub emitted particle (default: 0)
  62474. */
  62475. this.inheritedVelocityAmount = 0;
  62476. // Create mesh as emitter to support rotation
  62477. if (!particleSystem.emitter || !particleSystem.emitter.dispose) {
  62478. particleSystem.emitter = new BABYLON.AbstractMesh("SubemitterSystemEmitter", particleSystem.getScene());
  62479. }
  62480. // Automatically dispose of subemitter when system is disposed
  62481. particleSystem.onDisposeObservable.add(function () {
  62482. if (particleSystem.emitter && particleSystem.emitter.dispose) {
  62483. particleSystem.emitter.dispose();
  62484. }
  62485. });
  62486. }
  62487. /**
  62488. * Clones the sub emitter
  62489. * @returns the cloned sub emitter
  62490. */
  62491. SubEmitter.prototype.clone = function () {
  62492. // Clone particle system
  62493. var emitter = this.particleSystem.emitter;
  62494. if (!emitter) {
  62495. emitter = new BABYLON.Vector3();
  62496. }
  62497. else if (emitter instanceof BABYLON.Vector3) {
  62498. emitter = emitter.clone();
  62499. }
  62500. else if (emitter instanceof BABYLON.AbstractMesh) {
  62501. emitter = new BABYLON.Mesh("", emitter.getScene());
  62502. emitter.isVisible = false;
  62503. }
  62504. var clone = new SubEmitter(this.particleSystem.clone("", emitter));
  62505. // Clone properties
  62506. clone.type = this.type;
  62507. clone.inheritDirection = this.inheritDirection;
  62508. clone.inheritedVelocityAmount = this.inheritedVelocityAmount;
  62509. clone.particleSystem._disposeEmitterOnDispose = true;
  62510. clone.particleSystem.disposeOnStop = true;
  62511. return clone;
  62512. };
  62513. /**
  62514. * Serialize current object to a JSON object
  62515. * @returns the serialized object
  62516. */
  62517. SubEmitter.prototype.serialize = function () {
  62518. var serializationObject = {};
  62519. serializationObject.type = this.type;
  62520. serializationObject.inheritDirection = this.inheritDirection;
  62521. serializationObject.inheritedVelocityAmount = this.inheritedVelocityAmount;
  62522. serializationObject.particleSystem = this.particleSystem.serialize();
  62523. return serializationObject;
  62524. };
  62525. /**
  62526. * Creates a new SubEmitter from a serialized JSON version
  62527. * @param serializationObject defines the JSON object to read from
  62528. * @param scene defines the hosting scene
  62529. * @param rootUrl defines the rootUrl for data loading
  62530. * @returns a new SubEmitter
  62531. */
  62532. SubEmitter.Parse = function (serializationObject, scene, rootUrl) {
  62533. var system = serializationObject.particleSystem;
  62534. var subEmitter = new SubEmitter(BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  62535. subEmitter.type = serializationObject.type;
  62536. subEmitter.inheritDirection = serializationObject.inheritDirection;
  62537. subEmitter.inheritedVelocityAmount = serializationObject.inheritedVelocityAmount;
  62538. subEmitter.particleSystem._isSubEmitter = true;
  62539. return subEmitter;
  62540. };
  62541. /** Release associated resources */
  62542. SubEmitter.prototype.dispose = function () {
  62543. this.particleSystem.dispose();
  62544. };
  62545. return SubEmitter;
  62546. }());
  62547. BABYLON.SubEmitter = SubEmitter;
  62548. })(BABYLON || (BABYLON = {}));
  62549. //# sourceMappingURL=babylon.subEmitter.js.map
  62550. var BABYLON;
  62551. (function (BABYLON) {
  62552. /**
  62553. * 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.
  62554. *
  62555. * This returned material effects how the mesh will look based on the code in the shaders.
  62556. *
  62557. * @see http://doc.babylonjs.com/how_to/shader_material
  62558. */
  62559. var ShaderMaterial = /** @class */ (function (_super) {
  62560. __extends(ShaderMaterial, _super);
  62561. /**
  62562. * Instantiate a new shader material.
  62563. * 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.
  62564. * This returned material effects how the mesh will look based on the code in the shaders.
  62565. * @see http://doc.babylonjs.com/how_to/shader_material
  62566. * @param name Define the name of the material in the scene
  62567. * @param scene Define the scene the material belongs to
  62568. * @param shaderPath Defines the route to the shader code in one of three ways:
  62569. * - object - { vertex: "custom", fragment: "custom" }, used with BABYLON.Effect.ShadersStore["customVertexShader"] and BABYLON.Effect.ShadersStore["customFragmentShader"]
  62570. * - object - { vertexElement: "vertexShaderCode", fragmentElement: "fragmentShaderCode" }, used with shader code in <script> tags
  62571. * - string - "./COMMON_NAME", used with external files COMMON_NAME.vertex.fx and COMMON_NAME.fragment.fx in index.html folder.
  62572. * @param options Define the options used to create the shader
  62573. */
  62574. function ShaderMaterial(name, scene, shaderPath, options) {
  62575. if (options === void 0) { options = {}; }
  62576. var _this = _super.call(this, name, scene) || this;
  62577. _this._textures = {};
  62578. _this._textureArrays = {};
  62579. _this._floats = {};
  62580. _this._ints = {};
  62581. _this._floatsArrays = {};
  62582. _this._colors3 = {};
  62583. _this._colors3Arrays = {};
  62584. _this._colors4 = {};
  62585. _this._vectors2 = {};
  62586. _this._vectors3 = {};
  62587. _this._vectors4 = {};
  62588. _this._matrices = {};
  62589. _this._matrices3x3 = {};
  62590. _this._matrices2x2 = {};
  62591. _this._vectors2Arrays = {};
  62592. _this._vectors3Arrays = {};
  62593. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  62594. _this._shaderPath = shaderPath;
  62595. _this._options = __assign({ needAlphaBlending: false, needAlphaTesting: false, attributes: ["position", "normal", "uv"], uniforms: ["worldViewProjection"], uniformBuffers: [], samplers: [], defines: [] }, options);
  62596. return _this;
  62597. }
  62598. /**
  62599. * Gets the current class name of the material e.g. "ShaderMaterial"
  62600. * Mainly use in serialization.
  62601. * @returns the class name
  62602. */
  62603. ShaderMaterial.prototype.getClassName = function () {
  62604. return "ShaderMaterial";
  62605. };
  62606. /**
  62607. * Specifies if the material will require alpha blending
  62608. * @returns a boolean specifying if alpha blending is needed
  62609. */
  62610. ShaderMaterial.prototype.needAlphaBlending = function () {
  62611. return (this.alpha < 1.0) || this._options.needAlphaBlending;
  62612. };
  62613. /**
  62614. * Specifies if this material should be rendered in alpha test mode
  62615. * @returns a boolean specifying if an alpha test is needed.
  62616. */
  62617. ShaderMaterial.prototype.needAlphaTesting = function () {
  62618. return this._options.needAlphaTesting;
  62619. };
  62620. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  62621. if (this._options.uniforms.indexOf(uniformName) === -1) {
  62622. this._options.uniforms.push(uniformName);
  62623. }
  62624. };
  62625. /**
  62626. * Set a texture in the shader.
  62627. * @param name Define the name of the uniform samplers as defined in the shader
  62628. * @param texture Define the texture to bind to this sampler
  62629. * @return the material itself allowing "fluent" like uniform updates
  62630. */
  62631. ShaderMaterial.prototype.setTexture = function (name, texture) {
  62632. if (this._options.samplers.indexOf(name) === -1) {
  62633. this._options.samplers.push(name);
  62634. }
  62635. this._textures[name] = texture;
  62636. return this;
  62637. };
  62638. /**
  62639. * Set a texture array in the shader.
  62640. * @param name Define the name of the uniform sampler array as defined in the shader
  62641. * @param textures Define the list of textures to bind to this sampler
  62642. * @return the material itself allowing "fluent" like uniform updates
  62643. */
  62644. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  62645. if (this._options.samplers.indexOf(name) === -1) {
  62646. this._options.samplers.push(name);
  62647. }
  62648. this._checkUniform(name);
  62649. this._textureArrays[name] = textures;
  62650. return this;
  62651. };
  62652. /**
  62653. * Set a float in the shader.
  62654. * @param name Define the name of the uniform as defined in the shader
  62655. * @param value Define the value to give to the uniform
  62656. * @return the material itself allowing "fluent" like uniform updates
  62657. */
  62658. ShaderMaterial.prototype.setFloat = function (name, value) {
  62659. this._checkUniform(name);
  62660. this._floats[name] = value;
  62661. return this;
  62662. };
  62663. /**
  62664. * Set a int in the shader.
  62665. * @param name Define the name of the uniform as defined in the shader
  62666. * @param value Define the value to give to the uniform
  62667. * @return the material itself allowing "fluent" like uniform updates
  62668. */
  62669. ShaderMaterial.prototype.setInt = function (name, value) {
  62670. this._checkUniform(name);
  62671. this._ints[name] = value;
  62672. return this;
  62673. };
  62674. /**
  62675. * Set an array of floats in the shader.
  62676. * @param name Define the name of the uniform as defined in the shader
  62677. * @param value Define the value to give to the uniform
  62678. * @return the material itself allowing "fluent" like uniform updates
  62679. */
  62680. ShaderMaterial.prototype.setFloats = function (name, value) {
  62681. this._checkUniform(name);
  62682. this._floatsArrays[name] = value;
  62683. return this;
  62684. };
  62685. /**
  62686. * Set a vec3 in the shader from a Color3.
  62687. * @param name Define the name of the uniform as defined in the shader
  62688. * @param value Define the value to give to the uniform
  62689. * @return the material itself allowing "fluent" like uniform updates
  62690. */
  62691. ShaderMaterial.prototype.setColor3 = function (name, value) {
  62692. this._checkUniform(name);
  62693. this._colors3[name] = value;
  62694. return this;
  62695. };
  62696. /**
  62697. * Set a vec3 array in the shader from a Color3 array.
  62698. * @param name Define the name of the uniform as defined in the shader
  62699. * @param value Define the value to give to the uniform
  62700. * @return the material itself allowing "fluent" like uniform updates
  62701. */
  62702. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  62703. this._checkUniform(name);
  62704. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  62705. color.toArray(arr, arr.length);
  62706. return arr;
  62707. }, []);
  62708. return this;
  62709. };
  62710. /**
  62711. * Set a vec4 in the shader from a Color4.
  62712. * @param name Define the name of the uniform as defined in the shader
  62713. * @param value Define the value to give to the uniform
  62714. * @return the material itself allowing "fluent" like uniform updates
  62715. */
  62716. ShaderMaterial.prototype.setColor4 = function (name, value) {
  62717. this._checkUniform(name);
  62718. this._colors4[name] = value;
  62719. return this;
  62720. };
  62721. /**
  62722. * Set a vec2 in the shader from a Vector2.
  62723. * @param name Define the name of the uniform as defined in the shader
  62724. * @param value Define the value to give to the uniform
  62725. * @return the material itself allowing "fluent" like uniform updates
  62726. */
  62727. ShaderMaterial.prototype.setVector2 = function (name, value) {
  62728. this._checkUniform(name);
  62729. this._vectors2[name] = value;
  62730. return this;
  62731. };
  62732. /**
  62733. * Set a vec3 in the shader from a Vector3.
  62734. * @param name Define the name of the uniform as defined in the shader
  62735. * @param value Define the value to give to the uniform
  62736. * @return the material itself allowing "fluent" like uniform updates
  62737. */
  62738. ShaderMaterial.prototype.setVector3 = function (name, value) {
  62739. this._checkUniform(name);
  62740. this._vectors3[name] = value;
  62741. return this;
  62742. };
  62743. /**
  62744. * Set a vec4 in the shader from a Vector4.
  62745. * @param name Define the name of the uniform as defined in the shader
  62746. * @param value Define the value to give to the uniform
  62747. * @return the material itself allowing "fluent" like uniform updates
  62748. */
  62749. ShaderMaterial.prototype.setVector4 = function (name, value) {
  62750. this._checkUniform(name);
  62751. this._vectors4[name] = value;
  62752. return this;
  62753. };
  62754. /**
  62755. * Set a mat4 in the shader from a Matrix.
  62756. * @param name Define the name of the uniform as defined in the shader
  62757. * @param value Define the value to give to the uniform
  62758. * @return the material itself allowing "fluent" like uniform updates
  62759. */
  62760. ShaderMaterial.prototype.setMatrix = function (name, value) {
  62761. this._checkUniform(name);
  62762. this._matrices[name] = value;
  62763. return this;
  62764. };
  62765. /**
  62766. * Set a mat3 in the shader from a Float32Array.
  62767. * @param name Define the name of the uniform as defined in the shader
  62768. * @param value Define the value to give to the uniform
  62769. * @return the material itself allowing "fluent" like uniform updates
  62770. */
  62771. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  62772. this._checkUniform(name);
  62773. this._matrices3x3[name] = value;
  62774. return this;
  62775. };
  62776. /**
  62777. * Set a mat2 in the shader from a Float32Array.
  62778. * @param name Define the name of the uniform as defined in the shader
  62779. * @param value Define the value to give to the uniform
  62780. * @return the material itself allowing "fluent" like uniform updates
  62781. */
  62782. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  62783. this._checkUniform(name);
  62784. this._matrices2x2[name] = value;
  62785. return this;
  62786. };
  62787. /**
  62788. * Set a vec2 array in the shader from a number array.
  62789. * @param name Define the name of the uniform as defined in the shader
  62790. * @param value Define the value to give to the uniform
  62791. * @return the material itself allowing "fluent" like uniform updates
  62792. */
  62793. ShaderMaterial.prototype.setArray2 = function (name, value) {
  62794. this._checkUniform(name);
  62795. this._vectors2Arrays[name] = value;
  62796. return this;
  62797. };
  62798. /**
  62799. * Set a vec3 array in the shader from a number array.
  62800. * @param name Define the name of the uniform as defined in the shader
  62801. * @param value Define the value to give to the uniform
  62802. * @return the material itself allowing "fluent" like uniform updates
  62803. */
  62804. ShaderMaterial.prototype.setArray3 = function (name, value) {
  62805. this._checkUniform(name);
  62806. this._vectors3Arrays[name] = value;
  62807. return this;
  62808. };
  62809. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  62810. if (!mesh) {
  62811. return true;
  62812. }
  62813. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  62814. return false;
  62815. }
  62816. return false;
  62817. };
  62818. /**
  62819. * Checks if the material is ready to render the requested mesh
  62820. * @param mesh Define the mesh to render
  62821. * @param useInstances Define whether or not the material is used with instances
  62822. * @returns true if ready, otherwise false
  62823. */
  62824. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  62825. var scene = this.getScene();
  62826. var engine = scene.getEngine();
  62827. if (!this.checkReadyOnEveryCall) {
  62828. if (this._renderId === scene.getRenderId()) {
  62829. if (this._checkCache(scene, mesh, useInstances)) {
  62830. return true;
  62831. }
  62832. }
  62833. }
  62834. // Instances
  62835. var defines = [];
  62836. var attribs = [];
  62837. var fallbacks = new BABYLON.EffectFallbacks();
  62838. for (var index = 0; index < this._options.defines.length; index++) {
  62839. defines.push(this._options.defines[index]);
  62840. }
  62841. for (var index = 0; index < this._options.attributes.length; index++) {
  62842. attribs.push(this._options.attributes[index]);
  62843. }
  62844. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  62845. attribs.push(BABYLON.VertexBuffer.ColorKind);
  62846. defines.push("#define VERTEXCOLOR");
  62847. }
  62848. if (useInstances) {
  62849. defines.push("#define INSTANCES");
  62850. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  62851. }
  62852. // Bones
  62853. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  62854. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  62855. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  62856. if (mesh.numBoneInfluencers > 4) {
  62857. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  62858. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  62859. }
  62860. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  62861. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  62862. fallbacks.addCPUSkinningFallback(0, mesh);
  62863. if (this._options.uniforms.indexOf("mBones") === -1) {
  62864. this._options.uniforms.push("mBones");
  62865. }
  62866. }
  62867. else {
  62868. defines.push("#define NUM_BONE_INFLUENCERS 0");
  62869. }
  62870. // Textures
  62871. for (var name in this._textures) {
  62872. if (!this._textures[name].isReady()) {
  62873. return false;
  62874. }
  62875. }
  62876. // Alpha test
  62877. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  62878. defines.push("#define ALPHATEST");
  62879. }
  62880. var previousEffect = this._effect;
  62881. var join = defines.join("\n");
  62882. this._effect = engine.createEffect(this._shaderPath, {
  62883. attributes: attribs,
  62884. uniformsNames: this._options.uniforms,
  62885. uniformBuffersNames: this._options.uniformBuffers,
  62886. samplers: this._options.samplers,
  62887. defines: join,
  62888. fallbacks: fallbacks,
  62889. onCompiled: this.onCompiled,
  62890. onError: this.onError
  62891. }, engine);
  62892. if (!this._effect.isReady()) {
  62893. return false;
  62894. }
  62895. if (previousEffect !== this._effect) {
  62896. scene.resetCachedMaterial();
  62897. }
  62898. this._renderId = scene.getRenderId();
  62899. return true;
  62900. };
  62901. /**
  62902. * Binds the world matrix to the material
  62903. * @param world defines the world transformation matrix
  62904. */
  62905. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  62906. var scene = this.getScene();
  62907. if (!this._effect) {
  62908. return;
  62909. }
  62910. if (this._options.uniforms.indexOf("world") !== -1) {
  62911. this._effect.setMatrix("world", world);
  62912. }
  62913. if (this._options.uniforms.indexOf("worldView") !== -1) {
  62914. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  62915. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  62916. }
  62917. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  62918. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  62919. }
  62920. };
  62921. /**
  62922. * Binds the material to the mesh
  62923. * @param world defines the world transformation matrix
  62924. * @param mesh defines the mesh to bind the material to
  62925. */
  62926. ShaderMaterial.prototype.bind = function (world, mesh) {
  62927. // Std values
  62928. this.bindOnlyWorldMatrix(world);
  62929. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  62930. if (this._options.uniforms.indexOf("view") !== -1) {
  62931. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  62932. }
  62933. if (this._options.uniforms.indexOf("projection") !== -1) {
  62934. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  62935. }
  62936. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  62937. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  62938. }
  62939. // Bones
  62940. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  62941. var name;
  62942. // Texture
  62943. for (name in this._textures) {
  62944. this._effect.setTexture(name, this._textures[name]);
  62945. }
  62946. // Texture arrays
  62947. for (name in this._textureArrays) {
  62948. this._effect.setTextureArray(name, this._textureArrays[name]);
  62949. }
  62950. // Int
  62951. for (name in this._ints) {
  62952. this._effect.setInt(name, this._ints[name]);
  62953. }
  62954. // Float
  62955. for (name in this._floats) {
  62956. this._effect.setFloat(name, this._floats[name]);
  62957. }
  62958. // Floats
  62959. for (name in this._floatsArrays) {
  62960. this._effect.setArray(name, this._floatsArrays[name]);
  62961. }
  62962. // Color3
  62963. for (name in this._colors3) {
  62964. this._effect.setColor3(name, this._colors3[name]);
  62965. }
  62966. for (name in this._colors3Arrays) {
  62967. this._effect.setArray3(name, this._colors3Arrays[name]);
  62968. }
  62969. // Color4
  62970. for (name in this._colors4) {
  62971. var color = this._colors4[name];
  62972. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  62973. }
  62974. // Vector2
  62975. for (name in this._vectors2) {
  62976. this._effect.setVector2(name, this._vectors2[name]);
  62977. }
  62978. // Vector3
  62979. for (name in this._vectors3) {
  62980. this._effect.setVector3(name, this._vectors3[name]);
  62981. }
  62982. // Vector4
  62983. for (name in this._vectors4) {
  62984. this._effect.setVector4(name, this._vectors4[name]);
  62985. }
  62986. // Matrix
  62987. for (name in this._matrices) {
  62988. this._effect.setMatrix(name, this._matrices[name]);
  62989. }
  62990. // Matrix 3x3
  62991. for (name in this._matrices3x3) {
  62992. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  62993. }
  62994. // Matrix 2x2
  62995. for (name in this._matrices2x2) {
  62996. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  62997. }
  62998. // Vector2Array
  62999. for (name in this._vectors2Arrays) {
  63000. this._effect.setArray2(name, this._vectors2Arrays[name]);
  63001. }
  63002. // Vector3Array
  63003. for (name in this._vectors3Arrays) {
  63004. this._effect.setArray3(name, this._vectors3Arrays[name]);
  63005. }
  63006. }
  63007. this._afterBind(mesh);
  63008. };
  63009. /**
  63010. * Gets the active textures from the material
  63011. * @returns an array of textures
  63012. */
  63013. ShaderMaterial.prototype.getActiveTextures = function () {
  63014. var activeTextures = _super.prototype.getActiveTextures.call(this);
  63015. for (var name in this._textures) {
  63016. activeTextures.push(this._textures[name]);
  63017. }
  63018. for (var name in this._textureArrays) {
  63019. var array = this._textureArrays[name];
  63020. for (var index = 0; index < array.length; index++) {
  63021. activeTextures.push(array[index]);
  63022. }
  63023. }
  63024. return activeTextures;
  63025. };
  63026. /**
  63027. * Specifies if the material uses a texture
  63028. * @param texture defines the texture to check against the material
  63029. * @returns a boolean specifying if the material uses the texture
  63030. */
  63031. ShaderMaterial.prototype.hasTexture = function (texture) {
  63032. if (_super.prototype.hasTexture.call(this, texture)) {
  63033. return true;
  63034. }
  63035. for (var name in this._textures) {
  63036. if (this._textures[name] === texture) {
  63037. return true;
  63038. }
  63039. }
  63040. for (var name in this._textureArrays) {
  63041. var array = this._textureArrays[name];
  63042. for (var index = 0; index < array.length; index++) {
  63043. if (array[index] === texture) {
  63044. return true;
  63045. }
  63046. }
  63047. }
  63048. return false;
  63049. };
  63050. /**
  63051. * Makes a duplicate of the material, and gives it a new name
  63052. * @param name defines the new name for the duplicated material
  63053. * @returns the cloned material
  63054. */
  63055. ShaderMaterial.prototype.clone = function (name) {
  63056. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  63057. return newShaderMaterial;
  63058. };
  63059. /**
  63060. * Disposes the material
  63061. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  63062. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  63063. */
  63064. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  63065. if (forceDisposeTextures) {
  63066. var name;
  63067. for (name in this._textures) {
  63068. this._textures[name].dispose();
  63069. }
  63070. for (name in this._textureArrays) {
  63071. var array = this._textureArrays[name];
  63072. for (var index = 0; index < array.length; index++) {
  63073. array[index].dispose();
  63074. }
  63075. }
  63076. }
  63077. this._textures = {};
  63078. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  63079. };
  63080. /**
  63081. * Serializes this material in a JSON representation
  63082. * @returns the serialized material object
  63083. */
  63084. ShaderMaterial.prototype.serialize = function () {
  63085. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  63086. serializationObject.customType = "BABYLON.ShaderMaterial";
  63087. serializationObject.options = this._options;
  63088. serializationObject.shaderPath = this._shaderPath;
  63089. var name;
  63090. // Texture
  63091. serializationObject.textures = {};
  63092. for (name in this._textures) {
  63093. serializationObject.textures[name] = this._textures[name].serialize();
  63094. }
  63095. // Texture arrays
  63096. serializationObject.textureArrays = {};
  63097. for (name in this._textureArrays) {
  63098. serializationObject.textureArrays[name] = [];
  63099. var array = this._textureArrays[name];
  63100. for (var index = 0; index < array.length; index++) {
  63101. serializationObject.textureArrays[name].push(array[index].serialize());
  63102. }
  63103. }
  63104. // Float
  63105. serializationObject.floats = {};
  63106. for (name in this._floats) {
  63107. serializationObject.floats[name] = this._floats[name];
  63108. }
  63109. // Float s
  63110. serializationObject.FloatArrays = {};
  63111. for (name in this._floatsArrays) {
  63112. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  63113. }
  63114. // Color3
  63115. serializationObject.colors3 = {};
  63116. for (name in this._colors3) {
  63117. serializationObject.colors3[name] = this._colors3[name].asArray();
  63118. }
  63119. // Color3 array
  63120. serializationObject.colors3Arrays = {};
  63121. for (name in this._colors3Arrays) {
  63122. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  63123. }
  63124. // Color4
  63125. serializationObject.colors4 = {};
  63126. for (name in this._colors4) {
  63127. serializationObject.colors4[name] = this._colors4[name].asArray();
  63128. }
  63129. // Vector2
  63130. serializationObject.vectors2 = {};
  63131. for (name in this._vectors2) {
  63132. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  63133. }
  63134. // Vector3
  63135. serializationObject.vectors3 = {};
  63136. for (name in this._vectors3) {
  63137. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  63138. }
  63139. // Vector4
  63140. serializationObject.vectors4 = {};
  63141. for (name in this._vectors4) {
  63142. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  63143. }
  63144. // Matrix
  63145. serializationObject.matrices = {};
  63146. for (name in this._matrices) {
  63147. serializationObject.matrices[name] = this._matrices[name].asArray();
  63148. }
  63149. // Matrix 3x3
  63150. serializationObject.matrices3x3 = {};
  63151. for (name in this._matrices3x3) {
  63152. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  63153. }
  63154. // Matrix 2x2
  63155. serializationObject.matrices2x2 = {};
  63156. for (name in this._matrices2x2) {
  63157. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  63158. }
  63159. // Vector2Array
  63160. serializationObject.vectors2Arrays = {};
  63161. for (name in this._vectors2Arrays) {
  63162. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  63163. }
  63164. // Vector3Array
  63165. serializationObject.vectors3Arrays = {};
  63166. for (name in this._vectors3Arrays) {
  63167. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  63168. }
  63169. return serializationObject;
  63170. };
  63171. /**
  63172. * Creates a shader material from parsed shader material data
  63173. * @param source defines the JSON represnetation of the material
  63174. * @param scene defines the hosting scene
  63175. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  63176. * @returns a new material
  63177. */
  63178. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  63179. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  63180. var name;
  63181. // Texture
  63182. for (name in source.textures) {
  63183. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  63184. }
  63185. // Texture arrays
  63186. for (name in source.textureArrays) {
  63187. var array = source.textureArrays[name];
  63188. var textureArray = new Array();
  63189. for (var index = 0; index < array.length; index++) {
  63190. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  63191. }
  63192. material.setTextureArray(name, textureArray);
  63193. }
  63194. // Float
  63195. for (name in source.floats) {
  63196. material.setFloat(name, source.floats[name]);
  63197. }
  63198. // Float s
  63199. for (name in source.floatsArrays) {
  63200. material.setFloats(name, source.floatsArrays[name]);
  63201. }
  63202. // Color3
  63203. for (name in source.colors3) {
  63204. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  63205. }
  63206. // Color3 arrays
  63207. for (name in source.colors3Arrays) {
  63208. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  63209. if (i % 3 === 0) {
  63210. arr.push([num]);
  63211. }
  63212. else {
  63213. arr[arr.length - 1].push(num);
  63214. }
  63215. return arr;
  63216. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  63217. material.setColor3Array(name, colors);
  63218. }
  63219. // Color4
  63220. for (name in source.colors4) {
  63221. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  63222. }
  63223. // Vector2
  63224. for (name in source.vectors2) {
  63225. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  63226. }
  63227. // Vector3
  63228. for (name in source.vectors3) {
  63229. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  63230. }
  63231. // Vector4
  63232. for (name in source.vectors4) {
  63233. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  63234. }
  63235. // Matrix
  63236. for (name in source.matrices) {
  63237. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  63238. }
  63239. // Matrix 3x3
  63240. for (name in source.matrices3x3) {
  63241. material.setMatrix3x3(name, source.matrices3x3[name]);
  63242. }
  63243. // Matrix 2x2
  63244. for (name in source.matrices2x2) {
  63245. material.setMatrix2x2(name, source.matrices2x2[name]);
  63246. }
  63247. // Vector2Array
  63248. for (name in source.vectors2Arrays) {
  63249. material.setArray2(name, source.vectors2Arrays[name]);
  63250. }
  63251. // Vector3Array
  63252. for (name in source.vectors3Arrays) {
  63253. material.setArray3(name, source.vectors3Arrays[name]);
  63254. }
  63255. return material;
  63256. };
  63257. return ShaderMaterial;
  63258. }(BABYLON.Material));
  63259. BABYLON.ShaderMaterial = ShaderMaterial;
  63260. })(BABYLON || (BABYLON = {}));
  63261. //# sourceMappingURL=babylon.shaderMaterial.js.map
  63262. var BABYLON;
  63263. (function (BABYLON) {
  63264. /**
  63265. * Mesh representing the gorund
  63266. */
  63267. var GroundMesh = /** @class */ (function (_super) {
  63268. __extends(GroundMesh, _super);
  63269. function GroundMesh(name, scene) {
  63270. var _this = _super.call(this, name, scene) || this;
  63271. /** If octree should be generated */
  63272. _this.generateOctree = false;
  63273. return _this;
  63274. }
  63275. /**
  63276. * "GroundMesh"
  63277. * @returns "GroundMesh"
  63278. */
  63279. GroundMesh.prototype.getClassName = function () {
  63280. return "GroundMesh";
  63281. };
  63282. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  63283. /**
  63284. * The minimum of x and y subdivisions
  63285. */
  63286. get: function () {
  63287. return Math.min(this._subdivisionsX, this._subdivisionsY);
  63288. },
  63289. enumerable: true,
  63290. configurable: true
  63291. });
  63292. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  63293. /**
  63294. * X subdivisions
  63295. */
  63296. get: function () {
  63297. return this._subdivisionsX;
  63298. },
  63299. enumerable: true,
  63300. configurable: true
  63301. });
  63302. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  63303. /**
  63304. * Y subdivisions
  63305. */
  63306. get: function () {
  63307. return this._subdivisionsY;
  63308. },
  63309. enumerable: true,
  63310. configurable: true
  63311. });
  63312. /**
  63313. * This function will update an octree to help to select the right submeshes for rendering, picking and collision computations.
  63314. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  63315. * @param chunksCount the number of subdivisions for x and y
  63316. * @param octreeBlocksSize (Default: 32)
  63317. */
  63318. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  63319. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  63320. this._subdivisionsX = chunksCount;
  63321. this._subdivisionsY = chunksCount;
  63322. this.subdivide(chunksCount);
  63323. // Call the octree system optimization if it is defined.
  63324. var thisAsAny = this;
  63325. if (thisAsAny.createOrUpdateSubmeshesOctree) {
  63326. thisAsAny.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  63327. }
  63328. };
  63329. /**
  63330. * Returns a height (y) value in the Worl system :
  63331. * the ground altitude at the coordinates (x, z) expressed in the World system.
  63332. * @param x x coordinate
  63333. * @param z z coordinate
  63334. * @returns the ground y position if (x, z) are outside the ground surface.
  63335. */
  63336. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  63337. var world = this.getWorldMatrix();
  63338. var invMat = BABYLON.Tmp.Matrix[5];
  63339. world.invertToRef(invMat);
  63340. var tmpVect = BABYLON.Tmp.Vector3[8];
  63341. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  63342. x = tmpVect.x;
  63343. z = tmpVect.z;
  63344. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  63345. return this.position.y;
  63346. }
  63347. if (!this._heightQuads || this._heightQuads.length == 0) {
  63348. this._initHeightQuads();
  63349. this._computeHeightQuads();
  63350. }
  63351. var facet = this._getFacetAt(x, z);
  63352. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  63353. // return y in the World system
  63354. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  63355. return tmpVect.y;
  63356. };
  63357. /**
  63358. * Returns a normalized vector (Vector3) orthogonal to the ground
  63359. * at the ground coordinates (x, z) expressed in the World system.
  63360. * @param x x coordinate
  63361. * @param z z coordinate
  63362. * @returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  63363. */
  63364. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  63365. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  63366. this.getNormalAtCoordinatesToRef(x, z, normal);
  63367. return normal;
  63368. };
  63369. /**
  63370. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  63371. * at the ground coordinates (x, z) expressed in the World system.
  63372. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  63373. * @param x x coordinate
  63374. * @param z z coordinate
  63375. * @param ref vector to store the result
  63376. * @returns the GroundMesh.
  63377. */
  63378. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  63379. var world = this.getWorldMatrix();
  63380. var tmpMat = BABYLON.Tmp.Matrix[5];
  63381. world.invertToRef(tmpMat);
  63382. var tmpVect = BABYLON.Tmp.Vector3[8];
  63383. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  63384. x = tmpVect.x;
  63385. z = tmpVect.z;
  63386. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  63387. return this;
  63388. }
  63389. if (!this._heightQuads || this._heightQuads.length == 0) {
  63390. this._initHeightQuads();
  63391. this._computeHeightQuads();
  63392. }
  63393. var facet = this._getFacetAt(x, z);
  63394. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  63395. return this;
  63396. };
  63397. /**
  63398. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  63399. * if the ground has been updated.
  63400. * This can be used in the render loop.
  63401. * @returns the GroundMesh.
  63402. */
  63403. GroundMesh.prototype.updateCoordinateHeights = function () {
  63404. if (!this._heightQuads || this._heightQuads.length == 0) {
  63405. this._initHeightQuads();
  63406. }
  63407. this._computeHeightQuads();
  63408. return this;
  63409. };
  63410. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  63411. GroundMesh.prototype._getFacetAt = function (x, z) {
  63412. // retrieve col and row from x, z coordinates in the ground local system
  63413. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  63414. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  63415. var quad = this._heightQuads[row * this._subdivisionsX + col];
  63416. var facet;
  63417. if (z < quad.slope.x * x + quad.slope.y) {
  63418. facet = quad.facet1;
  63419. }
  63420. else {
  63421. facet = quad.facet2;
  63422. }
  63423. return facet;
  63424. };
  63425. // Creates and populates the heightMap array with "facet" elements :
  63426. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  63427. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  63428. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  63429. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  63430. // Returns the GroundMesh.
  63431. GroundMesh.prototype._initHeightQuads = function () {
  63432. var subdivisionsX = this._subdivisionsX;
  63433. var subdivisionsY = this._subdivisionsY;
  63434. this._heightQuads = new Array();
  63435. for (var row = 0; row < subdivisionsY; row++) {
  63436. for (var col = 0; col < subdivisionsX; col++) {
  63437. 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) };
  63438. this._heightQuads[row * subdivisionsX + col] = quad;
  63439. }
  63440. }
  63441. return this;
  63442. };
  63443. // Compute each quad element values and update the the heightMap array :
  63444. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  63445. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  63446. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  63447. // Returns the GroundMesh.
  63448. GroundMesh.prototype._computeHeightQuads = function () {
  63449. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63450. if (!positions) {
  63451. return this;
  63452. }
  63453. var v1 = BABYLON.Tmp.Vector3[3];
  63454. var v2 = BABYLON.Tmp.Vector3[2];
  63455. var v3 = BABYLON.Tmp.Vector3[1];
  63456. var v4 = BABYLON.Tmp.Vector3[0];
  63457. var v1v2 = BABYLON.Tmp.Vector3[4];
  63458. var v1v3 = BABYLON.Tmp.Vector3[5];
  63459. var v1v4 = BABYLON.Tmp.Vector3[6];
  63460. var norm1 = BABYLON.Tmp.Vector3[7];
  63461. var norm2 = BABYLON.Tmp.Vector3[8];
  63462. var i = 0;
  63463. var j = 0;
  63464. var k = 0;
  63465. var cd = 0; // 2D slope coefficient : z = cd * x + h
  63466. var h = 0;
  63467. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  63468. var d2 = 0;
  63469. var subdivisionsX = this._subdivisionsX;
  63470. var subdivisionsY = this._subdivisionsY;
  63471. for (var row = 0; row < subdivisionsY; row++) {
  63472. for (var col = 0; col < subdivisionsX; col++) {
  63473. i = col * 3;
  63474. j = row * (subdivisionsX + 1) * 3;
  63475. k = (row + 1) * (subdivisionsX + 1) * 3;
  63476. v1.x = positions[j + i];
  63477. v1.y = positions[j + i + 1];
  63478. v1.z = positions[j + i + 2];
  63479. v2.x = positions[j + i + 3];
  63480. v2.y = positions[j + i + 4];
  63481. v2.z = positions[j + i + 5];
  63482. v3.x = positions[k + i];
  63483. v3.y = positions[k + i + 1];
  63484. v3.z = positions[k + i + 2];
  63485. v4.x = positions[k + i + 3];
  63486. v4.y = positions[k + i + 4];
  63487. v4.z = positions[k + i + 5];
  63488. // 2D slope V1V4
  63489. cd = (v4.z - v1.z) / (v4.x - v1.x);
  63490. h = v1.z - cd * v1.x; // v1 belongs to the slope
  63491. // facet equations :
  63492. // we compute each facet normal vector
  63493. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  63494. // we compute the value d by applying the equation to v1 which belongs to the plane
  63495. // then we store the facet equation in a Vector4
  63496. v2.subtractToRef(v1, v1v2);
  63497. v3.subtractToRef(v1, v1v3);
  63498. v4.subtractToRef(v1, v1v4);
  63499. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  63500. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  63501. norm1.normalize();
  63502. norm2.normalize();
  63503. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  63504. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  63505. var quad = this._heightQuads[row * subdivisionsX + col];
  63506. quad.slope.copyFromFloats(cd, h);
  63507. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  63508. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  63509. }
  63510. }
  63511. return this;
  63512. };
  63513. /**
  63514. * Serializes this ground mesh
  63515. * @param serializationObject object to write serialization to
  63516. */
  63517. GroundMesh.prototype.serialize = function (serializationObject) {
  63518. _super.prototype.serialize.call(this, serializationObject);
  63519. serializationObject.subdivisionsX = this._subdivisionsX;
  63520. serializationObject.subdivisionsY = this._subdivisionsY;
  63521. serializationObject.minX = this._minX;
  63522. serializationObject.maxX = this._maxX;
  63523. serializationObject.minZ = this._minZ;
  63524. serializationObject.maxZ = this._maxZ;
  63525. serializationObject.width = this._width;
  63526. serializationObject.height = this._height;
  63527. };
  63528. /**
  63529. * Parses a serialized ground mesh
  63530. * @param parsedMesh the serialized mesh
  63531. * @param scene the scene to create the ground mesh in
  63532. * @returns the created ground mesh
  63533. */
  63534. GroundMesh.Parse = function (parsedMesh, scene) {
  63535. var result = new GroundMesh(parsedMesh.name, scene);
  63536. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  63537. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  63538. result._minX = parsedMesh.minX;
  63539. result._maxX = parsedMesh.maxX;
  63540. result._minZ = parsedMesh.minZ;
  63541. result._maxZ = parsedMesh.maxZ;
  63542. result._width = parsedMesh.width;
  63543. result._height = parsedMesh.height;
  63544. return result;
  63545. };
  63546. return GroundMesh;
  63547. }(BABYLON.Mesh));
  63548. BABYLON.GroundMesh = GroundMesh;
  63549. })(BABYLON || (BABYLON = {}));
  63550. //# sourceMappingURL=babylon.groundMesh.js.map
  63551. var BABYLON;
  63552. (function (BABYLON) {
  63553. /**
  63554. * Creates an instance based on a source mesh.
  63555. */
  63556. var InstancedMesh = /** @class */ (function (_super) {
  63557. __extends(InstancedMesh, _super);
  63558. function InstancedMesh(name, source) {
  63559. var _this = _super.call(this, name, source.getScene()) || this;
  63560. source.instances.push(_this);
  63561. _this._sourceMesh = source;
  63562. _this.position.copyFrom(source.position);
  63563. _this.rotation.copyFrom(source.rotation);
  63564. _this.scaling.copyFrom(source.scaling);
  63565. if (source.rotationQuaternion) {
  63566. _this.rotationQuaternion = source.rotationQuaternion.clone();
  63567. }
  63568. _this.infiniteDistance = source.infiniteDistance;
  63569. _this.setPivotMatrix(source.getPivotMatrix());
  63570. _this.refreshBoundingInfo();
  63571. _this._syncSubMeshes();
  63572. return _this;
  63573. }
  63574. /**
  63575. * Returns the string "InstancedMesh".
  63576. */
  63577. InstancedMesh.prototype.getClassName = function () {
  63578. return "InstancedMesh";
  63579. };
  63580. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  63581. // Methods
  63582. /**
  63583. * If the source mesh receives shadows
  63584. */
  63585. get: function () {
  63586. return this._sourceMesh.receiveShadows;
  63587. },
  63588. enumerable: true,
  63589. configurable: true
  63590. });
  63591. Object.defineProperty(InstancedMesh.prototype, "material", {
  63592. /**
  63593. * The material of the source mesh
  63594. */
  63595. get: function () {
  63596. return this._sourceMesh.material;
  63597. },
  63598. enumerable: true,
  63599. configurable: true
  63600. });
  63601. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  63602. /**
  63603. * Visibility of the source mesh
  63604. */
  63605. get: function () {
  63606. return this._sourceMesh.visibility;
  63607. },
  63608. enumerable: true,
  63609. configurable: true
  63610. });
  63611. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  63612. /**
  63613. * Skeleton of the source mesh
  63614. */
  63615. get: function () {
  63616. return this._sourceMesh.skeleton;
  63617. },
  63618. enumerable: true,
  63619. configurable: true
  63620. });
  63621. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  63622. /**
  63623. * Rendering ground id of the source mesh
  63624. */
  63625. get: function () {
  63626. return this._sourceMesh.renderingGroupId;
  63627. },
  63628. set: function (value) {
  63629. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  63630. return;
  63631. }
  63632. //no-op with warning
  63633. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  63634. },
  63635. enumerable: true,
  63636. configurable: true
  63637. });
  63638. /**
  63639. * Returns the total number of vertices (integer).
  63640. */
  63641. InstancedMesh.prototype.getTotalVertices = function () {
  63642. return this._sourceMesh.getTotalVertices();
  63643. };
  63644. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  63645. /**
  63646. * The source mesh of the instance
  63647. */
  63648. get: function () {
  63649. return this._sourceMesh;
  63650. },
  63651. enumerable: true,
  63652. configurable: true
  63653. });
  63654. /**
  63655. * Is this node ready to be used/rendered
  63656. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  63657. * @return {boolean} is it ready
  63658. */
  63659. InstancedMesh.prototype.isReady = function (completeCheck) {
  63660. if (completeCheck === void 0) { completeCheck = false; }
  63661. return this._sourceMesh.isReady(completeCheck, true);
  63662. };
  63663. /**
  63664. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  63665. * @param kind kind of verticies to retreive (eg. positons, normals, uvs, etc.)
  63666. * @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.
  63667. * @returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  63668. */
  63669. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  63670. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  63671. };
  63672. /**
  63673. * Sets the vertex data of the mesh geometry for the requested `kind`.
  63674. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  63675. * The `data` are either a numeric array either a Float32Array.
  63676. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  63677. * 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).
  63678. * Note that a new underlying VertexBuffer object is created each call.
  63679. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  63680. *
  63681. * Possible `kind` values :
  63682. * - BABYLON.VertexBuffer.PositionKind
  63683. * - BABYLON.VertexBuffer.UVKind
  63684. * - BABYLON.VertexBuffer.UV2Kind
  63685. * - BABYLON.VertexBuffer.UV3Kind
  63686. * - BABYLON.VertexBuffer.UV4Kind
  63687. * - BABYLON.VertexBuffer.UV5Kind
  63688. * - BABYLON.VertexBuffer.UV6Kind
  63689. * - BABYLON.VertexBuffer.ColorKind
  63690. * - BABYLON.VertexBuffer.MatricesIndicesKind
  63691. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  63692. * - BABYLON.VertexBuffer.MatricesWeightsKind
  63693. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  63694. *
  63695. * Returns the Mesh.
  63696. */
  63697. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  63698. if (this.sourceMesh) {
  63699. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  63700. }
  63701. return this.sourceMesh;
  63702. };
  63703. /**
  63704. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  63705. * If the mesh has no geometry, it is simply returned as it is.
  63706. * The `data` are either a numeric array either a Float32Array.
  63707. * No new underlying VertexBuffer object is created.
  63708. * 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.
  63709. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  63710. *
  63711. * Possible `kind` values :
  63712. * - BABYLON.VertexBuffer.PositionKind
  63713. * - BABYLON.VertexBuffer.UVKind
  63714. * - BABYLON.VertexBuffer.UV2Kind
  63715. * - BABYLON.VertexBuffer.UV3Kind
  63716. * - BABYLON.VertexBuffer.UV4Kind
  63717. * - BABYLON.VertexBuffer.UV5Kind
  63718. * - BABYLON.VertexBuffer.UV6Kind
  63719. * - BABYLON.VertexBuffer.ColorKind
  63720. * - BABYLON.VertexBuffer.MatricesIndicesKind
  63721. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  63722. * - BABYLON.VertexBuffer.MatricesWeightsKind
  63723. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  63724. *
  63725. * Returns the Mesh.
  63726. */
  63727. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  63728. if (this.sourceMesh) {
  63729. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  63730. }
  63731. return this.sourceMesh;
  63732. };
  63733. /**
  63734. * Sets the mesh indices.
  63735. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  63736. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  63737. * This method creates a new index buffer each call.
  63738. * Returns the Mesh.
  63739. */
  63740. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  63741. if (totalVertices === void 0) { totalVertices = null; }
  63742. if (this.sourceMesh) {
  63743. this.sourceMesh.setIndices(indices, totalVertices);
  63744. }
  63745. return this.sourceMesh;
  63746. };
  63747. /**
  63748. * Boolean : True if the mesh owns the requested kind of data.
  63749. */
  63750. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  63751. return this._sourceMesh.isVerticesDataPresent(kind);
  63752. };
  63753. /**
  63754. * Returns an array of indices (IndicesArray).
  63755. */
  63756. InstancedMesh.prototype.getIndices = function () {
  63757. return this._sourceMesh.getIndices();
  63758. };
  63759. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  63760. get: function () {
  63761. return this._sourceMesh._positions;
  63762. },
  63763. enumerable: true,
  63764. configurable: true
  63765. });
  63766. /**
  63767. * Sets a new updated BoundingInfo to the mesh.
  63768. * @returns the mesh.
  63769. */
  63770. InstancedMesh.prototype.refreshBoundingInfo = function () {
  63771. var meshBB = this._sourceMesh.getBoundingInfo();
  63772. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  63773. this._updateBoundingInfo();
  63774. return this;
  63775. };
  63776. /** @hidden */
  63777. InstancedMesh.prototype._preActivate = function () {
  63778. if (this._currentLOD) {
  63779. this._currentLOD._preActivate();
  63780. }
  63781. return this;
  63782. };
  63783. /** @hidden */
  63784. InstancedMesh.prototype._activate = function (renderId) {
  63785. if (this._currentLOD) {
  63786. this._currentLOD._registerInstanceForRenderId(this, renderId);
  63787. }
  63788. return this;
  63789. };
  63790. /**
  63791. * Returns the current associated LOD AbstractMesh.
  63792. */
  63793. InstancedMesh.prototype.getLOD = function (camera) {
  63794. if (!camera) {
  63795. return this;
  63796. }
  63797. var boundingInfo = this.getBoundingInfo();
  63798. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  63799. if (this._currentLOD === this.sourceMesh) {
  63800. return this;
  63801. }
  63802. return this._currentLOD;
  63803. };
  63804. /** @hidden */
  63805. InstancedMesh.prototype._syncSubMeshes = function () {
  63806. this.releaseSubMeshes();
  63807. if (this._sourceMesh.subMeshes) {
  63808. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  63809. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  63810. }
  63811. }
  63812. return this;
  63813. };
  63814. /** @hidden */
  63815. InstancedMesh.prototype._generatePointsArray = function () {
  63816. return this._sourceMesh._generatePointsArray();
  63817. };
  63818. /**
  63819. * Creates a new InstancedMesh from the current mesh.
  63820. * - name (string) : the cloned mesh name
  63821. * - newParent (optional Node) : the optional Node to parent the clone to.
  63822. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  63823. *
  63824. * Returns the clone.
  63825. */
  63826. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  63827. var result = this._sourceMesh.createInstance(name);
  63828. // Deep copy
  63829. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  63830. // Bounding info
  63831. this.refreshBoundingInfo();
  63832. // Parent
  63833. if (newParent) {
  63834. result.parent = newParent;
  63835. }
  63836. if (!doNotCloneChildren) {
  63837. // Children
  63838. for (var index = 0; index < this.getScene().meshes.length; index++) {
  63839. var mesh = this.getScene().meshes[index];
  63840. if (mesh.parent === this) {
  63841. mesh.clone(mesh.name, result);
  63842. }
  63843. }
  63844. }
  63845. result.computeWorldMatrix(true);
  63846. return result;
  63847. };
  63848. /**
  63849. * Disposes the InstancedMesh.
  63850. * Returns nothing.
  63851. */
  63852. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  63853. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  63854. // Remove from mesh
  63855. var index = this._sourceMesh.instances.indexOf(this);
  63856. this._sourceMesh.instances.splice(index, 1);
  63857. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  63858. };
  63859. return InstancedMesh;
  63860. }(BABYLON.AbstractMesh));
  63861. BABYLON.InstancedMesh = InstancedMesh;
  63862. })(BABYLON || (BABYLON = {}));
  63863. //# sourceMappingURL=babylon.instancedMesh.js.map
  63864. var BABYLON;
  63865. (function (BABYLON) {
  63866. /**
  63867. * Line mesh
  63868. * @see https://doc.babylonjs.com/babylon101/parametric_shapes
  63869. */
  63870. var LinesMesh = /** @class */ (function (_super) {
  63871. __extends(LinesMesh, _super);
  63872. /**
  63873. * Creates a new LinesMesh
  63874. * @param name defines the name
  63875. * @param scene defines the hosting scene
  63876. * @param parent defines the parent mesh if any
  63877. * @param source defines the optional source LinesMesh used to clone data from
  63878. * @param doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  63879. * When false, achieved by calling a clone(), also passing False.
  63880. * This will make creation of children, recursive.
  63881. * @param useVertexColor defines if this LinesMesh supports vertex color
  63882. * @param useVertexAlpha defines if this LinesMesh supports vertex alpha
  63883. */
  63884. function LinesMesh(name, scene, parent, source, doNotCloneChildren,
  63885. /**
  63886. * If vertex color should be applied to the mesh
  63887. */
  63888. useVertexColor,
  63889. /**
  63890. * If vertex alpha should be applied to the mesh
  63891. */
  63892. useVertexAlpha) {
  63893. if (scene === void 0) { scene = null; }
  63894. if (parent === void 0) { parent = null; }
  63895. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  63896. _this.useVertexColor = useVertexColor;
  63897. _this.useVertexAlpha = useVertexAlpha;
  63898. /**
  63899. * Color of the line (Default: White)
  63900. */
  63901. _this.color = new BABYLON.Color3(1, 1, 1);
  63902. /**
  63903. * Alpha of the line (Default: 1)
  63904. */
  63905. _this.alpha = 1;
  63906. if (source) {
  63907. _this.color = source.color.clone();
  63908. _this.alpha = source.alpha;
  63909. _this.useVertexColor = source.useVertexColor;
  63910. _this.useVertexAlpha = source.useVertexAlpha;
  63911. }
  63912. _this._intersectionThreshold = 0.1;
  63913. var defines = [];
  63914. var options = {
  63915. attributes: [BABYLON.VertexBuffer.PositionKind, "world0", "world1", "world2", "world3"],
  63916. uniforms: ["world", "viewProjection"],
  63917. needAlphaBlending: true,
  63918. defines: defines
  63919. };
  63920. if (useVertexAlpha === false) {
  63921. options.needAlphaBlending = false;
  63922. }
  63923. if (!useVertexColor) {
  63924. options.uniforms.push("color");
  63925. }
  63926. else {
  63927. options.defines.push("#define VERTEXCOLOR");
  63928. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  63929. }
  63930. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  63931. return _this;
  63932. }
  63933. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  63934. /**
  63935. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  63936. * This margin is expressed in world space coordinates, so its value may vary.
  63937. * Default value is 0.1
  63938. * @returns the intersection Threshold value.
  63939. */
  63940. get: function () {
  63941. return this._intersectionThreshold;
  63942. },
  63943. /**
  63944. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  63945. * This margin is expressed in world space coordinates, so its value may vary.
  63946. */
  63947. set: function (value) {
  63948. if (this._intersectionThreshold === value) {
  63949. return;
  63950. }
  63951. this._intersectionThreshold = value;
  63952. if (this.geometry) {
  63953. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  63954. }
  63955. },
  63956. enumerable: true,
  63957. configurable: true
  63958. });
  63959. /**
  63960. * Returns the string "LineMesh"
  63961. */
  63962. LinesMesh.prototype.getClassName = function () {
  63963. return "LinesMesh";
  63964. };
  63965. Object.defineProperty(LinesMesh.prototype, "material", {
  63966. /**
  63967. * @hidden
  63968. */
  63969. get: function () {
  63970. return this._colorShader;
  63971. },
  63972. /**
  63973. * @hidden
  63974. */
  63975. set: function (value) {
  63976. // Do nothing
  63977. },
  63978. enumerable: true,
  63979. configurable: true
  63980. });
  63981. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  63982. /**
  63983. * @hidden
  63984. */
  63985. get: function () {
  63986. return false;
  63987. },
  63988. enumerable: true,
  63989. configurable: true
  63990. });
  63991. /** @hidden */
  63992. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  63993. if (!this._geometry) {
  63994. return this;
  63995. }
  63996. // VBOs
  63997. this._geometry._bind(this._colorShader.getEffect());
  63998. // Color
  63999. if (!this.useVertexColor) {
  64000. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  64001. }
  64002. return this;
  64003. };
  64004. /** @hidden */
  64005. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  64006. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  64007. return this;
  64008. }
  64009. var engine = this.getScene().getEngine();
  64010. // Draw order
  64011. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  64012. return this;
  64013. };
  64014. /**
  64015. * Disposes of the line mesh
  64016. * @param doNotRecurse If children should be disposed
  64017. */
  64018. LinesMesh.prototype.dispose = function (doNotRecurse) {
  64019. this._colorShader.dispose();
  64020. _super.prototype.dispose.call(this, doNotRecurse);
  64021. };
  64022. /**
  64023. * Returns a new LineMesh object cloned from the current one.
  64024. */
  64025. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  64026. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  64027. };
  64028. return LinesMesh;
  64029. }(BABYLON.Mesh));
  64030. BABYLON.LinesMesh = LinesMesh;
  64031. })(BABYLON || (BABYLON = {}));
  64032. //# sourceMappingURL=babylon.linesMesh.js.map
  64033. var BABYLON;
  64034. (function (BABYLON) {
  64035. /**
  64036. * This class implement a typical dictionary using a string as key and the generic type T as value.
  64037. * The underlying implementation relies on an associative array to ensure the best performances.
  64038. * The value can be anything including 'null' but except 'undefined'
  64039. */
  64040. var StringDictionary = /** @class */ (function () {
  64041. function StringDictionary() {
  64042. this._count = 0;
  64043. this._data = {};
  64044. }
  64045. /**
  64046. * This will clear this dictionary and copy the content from the 'source' one.
  64047. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  64048. * @param source the dictionary to take the content from and copy to this dictionary
  64049. */
  64050. StringDictionary.prototype.copyFrom = function (source) {
  64051. var _this = this;
  64052. this.clear();
  64053. source.forEach(function (t, v) { return _this.add(t, v); });
  64054. };
  64055. /**
  64056. * Get a value based from its key
  64057. * @param key the given key to get the matching value from
  64058. * @return the value if found, otherwise undefined is returned
  64059. */
  64060. StringDictionary.prototype.get = function (key) {
  64061. var val = this._data[key];
  64062. if (val !== undefined) {
  64063. return val;
  64064. }
  64065. return undefined;
  64066. };
  64067. /**
  64068. * Get a value from its key or add it if it doesn't exist.
  64069. * This method will ensure you that a given key/data will be present in the dictionary.
  64070. * @param key the given key to get the matching value from
  64071. * @param factory the factory that will create the value if the key is not present in the dictionary.
  64072. * The factory will only be invoked if there's no data for the given key.
  64073. * @return the value corresponding to the key.
  64074. */
  64075. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  64076. var val = this.get(key);
  64077. if (val !== undefined) {
  64078. return val;
  64079. }
  64080. val = factory(key);
  64081. if (val) {
  64082. this.add(key, val);
  64083. }
  64084. return val;
  64085. };
  64086. /**
  64087. * Get a value from its key if present in the dictionary otherwise add it
  64088. * @param key the key to get the value from
  64089. * @param val if there's no such key/value pair in the dictionary add it with this value
  64090. * @return the value corresponding to the key
  64091. */
  64092. StringDictionary.prototype.getOrAdd = function (key, val) {
  64093. var curVal = this.get(key);
  64094. if (curVal !== undefined) {
  64095. return curVal;
  64096. }
  64097. this.add(key, val);
  64098. return val;
  64099. };
  64100. /**
  64101. * Check if there's a given key in the dictionary
  64102. * @param key the key to check for
  64103. * @return true if the key is present, false otherwise
  64104. */
  64105. StringDictionary.prototype.contains = function (key) {
  64106. return this._data[key] !== undefined;
  64107. };
  64108. /**
  64109. * Add a new key and its corresponding value
  64110. * @param key the key to add
  64111. * @param value the value corresponding to the key
  64112. * @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
  64113. */
  64114. StringDictionary.prototype.add = function (key, value) {
  64115. if (this._data[key] !== undefined) {
  64116. return false;
  64117. }
  64118. this._data[key] = value;
  64119. ++this._count;
  64120. return true;
  64121. };
  64122. /**
  64123. * Update a specific value associated to a key
  64124. * @param key defines the key to use
  64125. * @param value defines the value to store
  64126. * @returns true if the value was updated (or false if the key was not found)
  64127. */
  64128. StringDictionary.prototype.set = function (key, value) {
  64129. if (this._data[key] === undefined) {
  64130. return false;
  64131. }
  64132. this._data[key] = value;
  64133. return true;
  64134. };
  64135. /**
  64136. * Get the element of the given key and remove it from the dictionary
  64137. * @param key defines the key to search
  64138. * @returns the value associated with the key or null if not found
  64139. */
  64140. StringDictionary.prototype.getAndRemove = function (key) {
  64141. var val = this.get(key);
  64142. if (val !== undefined) {
  64143. delete this._data[key];
  64144. --this._count;
  64145. return val;
  64146. }
  64147. return null;
  64148. };
  64149. /**
  64150. * Remove a key/value from the dictionary.
  64151. * @param key the key to remove
  64152. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  64153. */
  64154. StringDictionary.prototype.remove = function (key) {
  64155. if (this.contains(key)) {
  64156. delete this._data[key];
  64157. --this._count;
  64158. return true;
  64159. }
  64160. return false;
  64161. };
  64162. /**
  64163. * Clear the whole content of the dictionary
  64164. */
  64165. StringDictionary.prototype.clear = function () {
  64166. this._data = {};
  64167. this._count = 0;
  64168. };
  64169. Object.defineProperty(StringDictionary.prototype, "count", {
  64170. /**
  64171. * Gets the current count
  64172. */
  64173. get: function () {
  64174. return this._count;
  64175. },
  64176. enumerable: true,
  64177. configurable: true
  64178. });
  64179. /**
  64180. * Execute a callback on each key/val of the dictionary.
  64181. * Note that you can remove any element in this dictionary in the callback implementation
  64182. * @param callback the callback to execute on a given key/value pair
  64183. */
  64184. StringDictionary.prototype.forEach = function (callback) {
  64185. for (var cur in this._data) {
  64186. var val = this._data[cur];
  64187. callback(cur, val);
  64188. }
  64189. };
  64190. /**
  64191. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  64192. * If the callback returns null or undefined the method will iterate to the next key/value pair
  64193. * Note that you can remove any element in this dictionary in the callback implementation
  64194. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  64195. * @returns the first item
  64196. */
  64197. StringDictionary.prototype.first = function (callback) {
  64198. for (var cur in this._data) {
  64199. var val = this._data[cur];
  64200. var res = callback(cur, val);
  64201. if (res) {
  64202. return res;
  64203. }
  64204. }
  64205. return null;
  64206. };
  64207. return StringDictionary;
  64208. }());
  64209. BABYLON.StringDictionary = StringDictionary;
  64210. })(BABYLON || (BABYLON = {}));
  64211. //# sourceMappingURL=babylon.stringDictionary.js.map
  64212. var BABYLON;
  64213. (function (BABYLON) {
  64214. var Debug;
  64215. (function (Debug) {
  64216. /**
  64217. * Class used to render a debug view of a given skeleton
  64218. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  64219. */
  64220. var SkeletonViewer = /** @class */ (function () {
  64221. /**
  64222. * Creates a new SkeletonViewer
  64223. * @param skeleton defines the skeleton to render
  64224. * @param mesh defines the mesh attached to the skeleton
  64225. * @param scene defines the hosting scene
  64226. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  64227. * @param renderingGroupId defines the rendering group id to use with the viewer
  64228. */
  64229. function SkeletonViewer(
  64230. /** defines the skeleton to render */
  64231. skeleton,
  64232. /** defines the mesh attached to the skeleton */
  64233. mesh, scene,
  64234. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  64235. autoUpdateBonesMatrices,
  64236. /** defines the rendering group id to use with the viewer */
  64237. renderingGroupId) {
  64238. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  64239. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  64240. this.skeleton = skeleton;
  64241. this.mesh = mesh;
  64242. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  64243. this.renderingGroupId = renderingGroupId;
  64244. /** Gets or sets the color used to render the skeleton */
  64245. this.color = BABYLON.Color3.White();
  64246. this._debugLines = new Array();
  64247. this._isEnabled = false;
  64248. this._scene = scene;
  64249. this.update();
  64250. this._renderFunction = this.update.bind(this);
  64251. }
  64252. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  64253. get: function () {
  64254. return this._isEnabled;
  64255. },
  64256. /** Gets or sets a boolean indicating if the viewer is enabled */
  64257. set: function (value) {
  64258. if (this._isEnabled === value) {
  64259. return;
  64260. }
  64261. this._isEnabled = value;
  64262. if (value) {
  64263. this._scene.registerBeforeRender(this._renderFunction);
  64264. }
  64265. else {
  64266. this._scene.unregisterBeforeRender(this._renderFunction);
  64267. }
  64268. },
  64269. enumerable: true,
  64270. configurable: true
  64271. });
  64272. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  64273. if (x === void 0) { x = 0; }
  64274. if (y === void 0) { y = 0; }
  64275. if (z === void 0) { z = 0; }
  64276. var tmat = BABYLON.Tmp.Matrix[0];
  64277. var parentBone = bone.getParent();
  64278. tmat.copyFrom(bone.getLocalMatrix());
  64279. if (x !== 0 || y !== 0 || z !== 0) {
  64280. var tmat2 = BABYLON.Tmp.Matrix[1];
  64281. BABYLON.Matrix.IdentityToRef(tmat2);
  64282. tmat2.m[12] = x;
  64283. tmat2.m[13] = y;
  64284. tmat2.m[14] = z;
  64285. tmat2.multiplyToRef(tmat, tmat);
  64286. }
  64287. if (parentBone) {
  64288. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  64289. }
  64290. tmat.multiplyToRef(meshMat, tmat);
  64291. position.x = tmat.m[12];
  64292. position.y = tmat.m[13];
  64293. position.z = tmat.m[14];
  64294. };
  64295. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  64296. var len = bones.length;
  64297. var meshPos = this.mesh.position;
  64298. for (var i = 0; i < len; i++) {
  64299. var bone = bones[i];
  64300. var points = this._debugLines[i];
  64301. if (!points) {
  64302. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64303. this._debugLines[i] = points;
  64304. }
  64305. this._getBonePosition(points[0], bone, meshMat);
  64306. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  64307. points[0].subtractInPlace(meshPos);
  64308. points[1].subtractInPlace(meshPos);
  64309. }
  64310. };
  64311. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  64312. var len = bones.length;
  64313. var boneNum = 0;
  64314. var meshPos = this.mesh.position;
  64315. for (var i = len - 1; i >= 0; i--) {
  64316. var childBone = bones[i];
  64317. var parentBone = childBone.getParent();
  64318. if (!parentBone) {
  64319. continue;
  64320. }
  64321. var points = this._debugLines[boneNum];
  64322. if (!points) {
  64323. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64324. this._debugLines[boneNum] = points;
  64325. }
  64326. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  64327. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  64328. points[0].subtractInPlace(meshPos);
  64329. points[1].subtractInPlace(meshPos);
  64330. boneNum++;
  64331. }
  64332. };
  64333. /** Update the viewer to sync with current skeleton state */
  64334. SkeletonViewer.prototype.update = function () {
  64335. if (this.autoUpdateBonesMatrices) {
  64336. this.skeleton.computeAbsoluteTransforms();
  64337. }
  64338. if (this.skeleton.bones[0].length === undefined) {
  64339. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  64340. }
  64341. else {
  64342. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  64343. }
  64344. if (!this._debugMesh) {
  64345. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  64346. this._debugMesh.renderingGroupId = this.renderingGroupId;
  64347. }
  64348. else {
  64349. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  64350. }
  64351. this._debugMesh.position.copyFrom(this.mesh.position);
  64352. this._debugMesh.color = this.color;
  64353. };
  64354. /** Release associated resources */
  64355. SkeletonViewer.prototype.dispose = function () {
  64356. if (this._debugMesh) {
  64357. this.isEnabled = false;
  64358. this._debugMesh.dispose();
  64359. this._debugMesh = null;
  64360. }
  64361. };
  64362. return SkeletonViewer;
  64363. }());
  64364. Debug.SkeletonViewer = SkeletonViewer;
  64365. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  64366. })(BABYLON || (BABYLON = {}));
  64367. //# sourceMappingURL=babylon.skeletonViewer.js.map
  64368. /**
  64369. * Module Debug contains the (visual) components to debug a scene correctly
  64370. */
  64371. var BABYLON;
  64372. (function (BABYLON) {
  64373. var Debug;
  64374. (function (Debug) {
  64375. /**
  64376. * The Axes viewer will show 3 axes in a specific point in space
  64377. */
  64378. var AxesViewer = /** @class */ (function () {
  64379. /**
  64380. * Creates a new AxesViewer
  64381. * @param scene defines the hosting scene
  64382. * @param scaleLines defines a number used to scale line length (1 by default)
  64383. */
  64384. function AxesViewer(scene, scaleLines) {
  64385. if (scaleLines === void 0) { scaleLines = 1; }
  64386. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64387. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64388. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64389. /**
  64390. * Gets or sets a number used to scale line length
  64391. */
  64392. this.scaleLines = 1;
  64393. this.scaleLines = scaleLines;
  64394. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  64395. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  64396. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  64397. this._xmesh.renderingGroupId = 2;
  64398. this._ymesh.renderingGroupId = 2;
  64399. this._zmesh.renderingGroupId = 2;
  64400. this._xmesh.material.checkReadyOnlyOnce = true;
  64401. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  64402. this._ymesh.material.checkReadyOnlyOnce = true;
  64403. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  64404. this._zmesh.material.checkReadyOnlyOnce = true;
  64405. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  64406. this.scene = scene;
  64407. }
  64408. /**
  64409. * Force the viewer to update
  64410. * @param position defines the position of the viewer
  64411. * @param xaxis defines the x axis of the viewer
  64412. * @param yaxis defines the y axis of the viewer
  64413. * @param zaxis defines the z axis of the viewer
  64414. */
  64415. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  64416. var scaleLines = this.scaleLines;
  64417. if (this._xmesh) {
  64418. this._xmesh.position.copyFrom(position);
  64419. }
  64420. if (this._ymesh) {
  64421. this._ymesh.position.copyFrom(position);
  64422. }
  64423. if (this._zmesh) {
  64424. this._zmesh.position.copyFrom(position);
  64425. }
  64426. var point2 = this._xline[1];
  64427. point2.x = xaxis.x * scaleLines;
  64428. point2.y = xaxis.y * scaleLines;
  64429. point2.z = xaxis.z * scaleLines;
  64430. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  64431. point2 = this._yline[1];
  64432. point2.x = yaxis.x * scaleLines;
  64433. point2.y = yaxis.y * scaleLines;
  64434. point2.z = yaxis.z * scaleLines;
  64435. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  64436. point2 = this._zline[1];
  64437. point2.x = zaxis.x * scaleLines;
  64438. point2.y = zaxis.y * scaleLines;
  64439. point2.z = zaxis.z * scaleLines;
  64440. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  64441. };
  64442. /** Releases resources */
  64443. AxesViewer.prototype.dispose = function () {
  64444. if (this._xmesh) {
  64445. this._xmesh.dispose();
  64446. }
  64447. if (this._ymesh) {
  64448. this._ymesh.dispose();
  64449. }
  64450. if (this._zmesh) {
  64451. this._zmesh.dispose();
  64452. }
  64453. this._xmesh = null;
  64454. this._ymesh = null;
  64455. this._zmesh = null;
  64456. this.scene = null;
  64457. };
  64458. return AxesViewer;
  64459. }());
  64460. Debug.AxesViewer = AxesViewer;
  64461. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  64462. })(BABYLON || (BABYLON = {}));
  64463. //# sourceMappingURL=babylon.axesViewer.js.map
  64464. var BABYLON;
  64465. (function (BABYLON) {
  64466. var Debug;
  64467. (function (Debug) {
  64468. /**
  64469. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  64470. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  64471. */
  64472. var BoneAxesViewer = /** @class */ (function (_super) {
  64473. __extends(BoneAxesViewer, _super);
  64474. /**
  64475. * Creates a new BoneAxesViewer
  64476. * @param scene defines the hosting scene
  64477. * @param bone defines the target bone
  64478. * @param mesh defines the target mesh
  64479. * @param scaleLines defines a scaling factor for line length (1 by default)
  64480. */
  64481. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  64482. if (scaleLines === void 0) { scaleLines = 1; }
  64483. var _this = _super.call(this, scene, scaleLines) || this;
  64484. /** Gets current position */
  64485. _this.pos = BABYLON.Vector3.Zero();
  64486. /** Gets direction of X axis */
  64487. _this.xaxis = BABYLON.Vector3.Zero();
  64488. /** Gets direction of Y axis */
  64489. _this.yaxis = BABYLON.Vector3.Zero();
  64490. /** Gets direction of Z axis */
  64491. _this.zaxis = BABYLON.Vector3.Zero();
  64492. _this.mesh = mesh;
  64493. _this.bone = bone;
  64494. return _this;
  64495. }
  64496. /**
  64497. * Force the viewer to update
  64498. */
  64499. BoneAxesViewer.prototype.update = function () {
  64500. if (!this.mesh || !this.bone) {
  64501. return;
  64502. }
  64503. var bone = this.bone;
  64504. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  64505. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  64506. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  64507. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  64508. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  64509. };
  64510. /** Releases resources */
  64511. BoneAxesViewer.prototype.dispose = function () {
  64512. if (this.mesh) {
  64513. this.mesh = null;
  64514. this.bone = null;
  64515. _super.prototype.dispose.call(this);
  64516. }
  64517. };
  64518. return BoneAxesViewer;
  64519. }(Debug.AxesViewer));
  64520. Debug.BoneAxesViewer = BoneAxesViewer;
  64521. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  64522. })(BABYLON || (BABYLON = {}));
  64523. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  64524. var BABYLON;
  64525. (function (BABYLON) {
  64526. /**
  64527. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  64528. * in order to better appreciate the issue one might have.
  64529. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  64530. */
  64531. var RayHelper = /** @class */ (function () {
  64532. /**
  64533. * Instantiate a new ray helper.
  64534. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  64535. * in order to better appreciate the issue one might have.
  64536. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  64537. * @param ray Defines the ray we are currently tryin to visualize
  64538. */
  64539. function RayHelper(ray) {
  64540. this.ray = ray;
  64541. }
  64542. /**
  64543. * Helper function to create a colored helper in a scene in one line.
  64544. * @param ray Defines the ray we are currently tryin to visualize
  64545. * @param scene Defines the scene the ray is used in
  64546. * @param color Defines the color we want to see the ray in
  64547. * @returns The newly created ray helper.
  64548. */
  64549. RayHelper.CreateAndShow = function (ray, scene, color) {
  64550. var helper = new RayHelper(ray);
  64551. helper.show(scene, color);
  64552. return helper;
  64553. };
  64554. /**
  64555. * Shows the ray we are willing to debug.
  64556. * @param scene Defines the scene the ray needs to be rendered in
  64557. * @param color Defines the color the ray needs to be rendered in
  64558. */
  64559. RayHelper.prototype.show = function (scene, color) {
  64560. if (!this._renderFunction && this.ray) {
  64561. var ray = this.ray;
  64562. this._renderFunction = this._render.bind(this);
  64563. this._scene = scene;
  64564. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  64565. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  64566. if (this._renderFunction) {
  64567. this._scene.registerBeforeRender(this._renderFunction);
  64568. }
  64569. }
  64570. if (color && this._renderLine) {
  64571. this._renderLine.color.copyFrom(color);
  64572. }
  64573. };
  64574. /**
  64575. * Hides the ray we are debugging.
  64576. */
  64577. RayHelper.prototype.hide = function () {
  64578. if (this._renderFunction && this._scene) {
  64579. this._scene.unregisterBeforeRender(this._renderFunction);
  64580. this._scene = null;
  64581. this._renderFunction = null;
  64582. if (this._renderLine) {
  64583. this._renderLine.dispose();
  64584. this._renderLine = null;
  64585. }
  64586. this._renderPoints = [];
  64587. }
  64588. };
  64589. RayHelper.prototype._render = function () {
  64590. var ray = this.ray;
  64591. if (!ray) {
  64592. return;
  64593. }
  64594. var point = this._renderPoints[1];
  64595. var len = Math.min(ray.length, 1000000);
  64596. point.copyFrom(ray.direction);
  64597. point.scaleInPlace(len);
  64598. point.addInPlace(ray.origin);
  64599. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  64600. };
  64601. /**
  64602. * Attach a ray helper to a mesh so that we can easily see its orientation for instance or information like its normals.
  64603. * @param mesh Defines the mesh we want the helper attached to
  64604. * @param meshSpaceDirection Defines the direction of the Ray in mesh space (local space of the mesh node)
  64605. * @param meshSpaceOrigin Defines the origin of the Ray in mesh space (local space of the mesh node)
  64606. * @param length Defines the length of the ray
  64607. */
  64608. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  64609. this._attachedToMesh = mesh;
  64610. var ray = this.ray;
  64611. if (!ray) {
  64612. return;
  64613. }
  64614. if (!ray.direction) {
  64615. ray.direction = BABYLON.Vector3.Zero();
  64616. }
  64617. if (!ray.origin) {
  64618. ray.origin = BABYLON.Vector3.Zero();
  64619. }
  64620. if (length) {
  64621. ray.length = length;
  64622. }
  64623. if (!meshSpaceOrigin) {
  64624. meshSpaceOrigin = BABYLON.Vector3.Zero();
  64625. }
  64626. if (!meshSpaceDirection) {
  64627. // -1 so that this will work with Mesh.lookAt
  64628. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  64629. }
  64630. if (!this._meshSpaceDirection) {
  64631. this._meshSpaceDirection = meshSpaceDirection.clone();
  64632. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  64633. }
  64634. else {
  64635. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  64636. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  64637. }
  64638. if (!this._updateToMeshFunction) {
  64639. this._updateToMeshFunction = this._updateToMesh.bind(this);
  64640. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  64641. }
  64642. this._updateToMesh();
  64643. };
  64644. /**
  64645. * Detach the ray helper from the mesh it has previously been attached to.
  64646. */
  64647. RayHelper.prototype.detachFromMesh = function () {
  64648. if (this._attachedToMesh) {
  64649. if (this._updateToMeshFunction) {
  64650. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  64651. }
  64652. this._attachedToMesh = null;
  64653. this._updateToMeshFunction = null;
  64654. }
  64655. };
  64656. RayHelper.prototype._updateToMesh = function () {
  64657. var ray = this.ray;
  64658. if (!this._attachedToMesh || !ray) {
  64659. return;
  64660. }
  64661. if (this._attachedToMesh._isDisposed) {
  64662. this.detachFromMesh();
  64663. return;
  64664. }
  64665. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  64666. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  64667. };
  64668. /**
  64669. * Dispose the helper and release its associated resources.
  64670. */
  64671. RayHelper.prototype.dispose = function () {
  64672. this.hide();
  64673. this.detachFromMesh();
  64674. this.ray = null;
  64675. };
  64676. return RayHelper;
  64677. }());
  64678. BABYLON.RayHelper = RayHelper;
  64679. })(BABYLON || (BABYLON = {}));
  64680. //# sourceMappingURL=babylon.rayHelper.js.map
  64681. var BABYLON;
  64682. (function (BABYLON) {
  64683. Object.defineProperty(BABYLON.Scene.prototype, "debugLayer", {
  64684. get: function () {
  64685. if (!this._debugLayer) {
  64686. this._debugLayer = new DebugLayer(this);
  64687. }
  64688. return this._debugLayer;
  64689. },
  64690. enumerable: true,
  64691. configurable: true
  64692. });
  64693. /**
  64694. * The debug layer (aka Inspector) is the go to tool in order to better understand
  64695. * what is happening in your scene
  64696. * @see http://doc.babylonjs.com/features/playground_debuglayer
  64697. */
  64698. var DebugLayer = /** @class */ (function () {
  64699. /**
  64700. * Instantiates a new debug layer.
  64701. * The debug layer (aka Inspector) is the go to tool in order to better understand
  64702. * what is happening in your scene
  64703. * @see http://doc.babylonjs.com/features/playground_debuglayer
  64704. * @param scene Defines the scene to inspect
  64705. */
  64706. function DebugLayer(scene) {
  64707. var _this = this;
  64708. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  64709. /**
  64710. * Observable triggered when a property is changed through the inspector.
  64711. */
  64712. this.onPropertyChangedObservable = new BABYLON.Observable();
  64713. this._scene = scene;
  64714. this._scene.onDisposeObservable.add(function () {
  64715. // Debug layer
  64716. if (_this._scene._debugLayer) {
  64717. _this._scene._debugLayer.hide();
  64718. }
  64719. });
  64720. }
  64721. /** Creates the inspector window. */
  64722. DebugLayer.prototype._createInspector = function (config) {
  64723. if (config === void 0) { config = {}; }
  64724. var popup = config.popup || false;
  64725. var initialTab = config.initialTab || 0;
  64726. var parentElement = config.parentElement || null;
  64727. if (!this._inspector) {
  64728. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  64729. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  64730. } // else nothing to do as instance is already created
  64731. };
  64732. /**
  64733. * Get if the inspector is visible or not.
  64734. * @returns true if visible otherwise, false
  64735. */
  64736. DebugLayer.prototype.isVisible = function () {
  64737. if (!this._inspector) {
  64738. return false;
  64739. }
  64740. return true;
  64741. };
  64742. /**
  64743. * Hide the inspector and close its window.
  64744. */
  64745. DebugLayer.prototype.hide = function () {
  64746. if (this._inspector) {
  64747. try {
  64748. this._inspector.dispose();
  64749. }
  64750. catch (e) {
  64751. // If the inspector has been removed directly from the inspector tool
  64752. }
  64753. this.onPropertyChangedObservable.clear();
  64754. this._inspector = null;
  64755. }
  64756. };
  64757. /**
  64758. *
  64759. * Launch the debugLayer.
  64760. *
  64761. * initialTab:
  64762. * | Value | Tab Name |
  64763. * | --- | --- |
  64764. * | 0 | Scene |
  64765. * | 1 | Console |
  64766. * | 2 | Stats |
  64767. * | 3 | Textures |
  64768. * | 4 | Mesh |
  64769. * | 5 | Light |
  64770. * | 6 | Material |
  64771. * | 7 | GLTF |
  64772. * | 8 | GUI |
  64773. * | 9 | Physics |
  64774. * | 10 | Camera |
  64775. * | 11 | Audio |
  64776. *
  64777. * @param config Define the configuration of the inspector
  64778. */
  64779. DebugLayer.prototype.show = function (config) {
  64780. if (config === void 0) { config = {}; }
  64781. if (typeof this.BJSINSPECTOR == 'undefined') {
  64782. // Load inspector and add it to the DOM
  64783. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  64784. }
  64785. else {
  64786. // Otherwise creates the inspector
  64787. this._createInspector(config);
  64788. }
  64789. };
  64790. /**
  64791. * Gets the active tab
  64792. * @return the index of the active tab or -1 if the inspector is hidden
  64793. */
  64794. DebugLayer.prototype.getActiveTab = function () {
  64795. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  64796. };
  64797. /**
  64798. * Define the url to get the inspector script from.
  64799. * By default it uses the babylonjs CDN.
  64800. * @ignoreNaming
  64801. */
  64802. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  64803. return DebugLayer;
  64804. }());
  64805. BABYLON.DebugLayer = DebugLayer;
  64806. })(BABYLON || (BABYLON = {}));
  64807. //# sourceMappingURL=babylon.debugLayer.js.map
  64808. var BABYLON;
  64809. (function (BABYLON) {
  64810. var Debug;
  64811. (function (Debug) {
  64812. /**
  64813. * Used to show the physics impostor around the specific mesh
  64814. */
  64815. var PhysicsViewer = /** @class */ (function () {
  64816. /**
  64817. * Creates a new PhysicsViewer
  64818. * @param scene defines the hosting scene
  64819. */
  64820. function PhysicsViewer(scene) {
  64821. /** @hidden */
  64822. this._impostors = [];
  64823. /** @hidden */
  64824. this._meshes = [];
  64825. /** @hidden */
  64826. this._numMeshes = 0;
  64827. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64828. var physicEngine = this._scene.getPhysicsEngine();
  64829. if (physicEngine) {
  64830. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  64831. }
  64832. }
  64833. /** @hidden */
  64834. PhysicsViewer.prototype._updateDebugMeshes = function () {
  64835. var plugin = this._physicsEnginePlugin;
  64836. for (var i = 0; i < this._numMeshes; i++) {
  64837. var impostor = this._impostors[i];
  64838. if (!impostor) {
  64839. continue;
  64840. }
  64841. if (impostor.isDisposed) {
  64842. this.hideImpostor(this._impostors[i--]);
  64843. }
  64844. else {
  64845. var mesh = this._meshes[i];
  64846. if (mesh && plugin) {
  64847. plugin.syncMeshWithImpostor(mesh, impostor);
  64848. }
  64849. }
  64850. }
  64851. };
  64852. /**
  64853. * Renders a specified physic impostor
  64854. * @param impostor defines the impostor to render
  64855. */
  64856. PhysicsViewer.prototype.showImpostor = function (impostor) {
  64857. if (!this._scene) {
  64858. return;
  64859. }
  64860. for (var i = 0; i < this._numMeshes; i++) {
  64861. if (this._impostors[i] == impostor) {
  64862. return;
  64863. }
  64864. }
  64865. var debugMesh = this._getDebugMesh(impostor, this._scene);
  64866. if (debugMesh) {
  64867. this._impostors[this._numMeshes] = impostor;
  64868. this._meshes[this._numMeshes] = debugMesh;
  64869. if (this._numMeshes === 0) {
  64870. this._renderFunction = this._updateDebugMeshes.bind(this);
  64871. this._scene.registerBeforeRender(this._renderFunction);
  64872. }
  64873. this._numMeshes++;
  64874. }
  64875. };
  64876. /**
  64877. * Hides a specified physic impostor
  64878. * @param impostor defines the impostor to hide
  64879. */
  64880. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  64881. if (!impostor || !this._scene) {
  64882. return;
  64883. }
  64884. var removed = false;
  64885. for (var i = 0; i < this._numMeshes; i++) {
  64886. if (this._impostors[i] == impostor) {
  64887. var mesh = this._meshes[i];
  64888. if (!mesh) {
  64889. continue;
  64890. }
  64891. this._scene.removeMesh(mesh);
  64892. mesh.dispose();
  64893. this._numMeshes--;
  64894. if (this._numMeshes > 0) {
  64895. this._meshes[i] = this._meshes[this._numMeshes];
  64896. this._impostors[i] = this._impostors[this._numMeshes];
  64897. this._meshes[this._numMeshes] = null;
  64898. this._impostors[this._numMeshes] = null;
  64899. }
  64900. else {
  64901. this._meshes[0] = null;
  64902. this._impostors[0] = null;
  64903. }
  64904. removed = true;
  64905. break;
  64906. }
  64907. }
  64908. if (removed && this._numMeshes === 0) {
  64909. this._scene.unregisterBeforeRender(this._renderFunction);
  64910. }
  64911. };
  64912. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  64913. if (!this._debugMaterial) {
  64914. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  64915. this._debugMaterial.wireframe = true;
  64916. }
  64917. return this._debugMaterial;
  64918. };
  64919. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  64920. if (!this._debugBoxMesh) {
  64921. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  64922. this._debugBoxMesh.renderingGroupId = 1;
  64923. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  64924. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  64925. scene.removeMesh(this._debugBoxMesh);
  64926. }
  64927. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  64928. };
  64929. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  64930. if (!this._debugSphereMesh) {
  64931. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  64932. this._debugSphereMesh.renderingGroupId = 1;
  64933. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  64934. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  64935. scene.removeMesh(this._debugSphereMesh);
  64936. }
  64937. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  64938. };
  64939. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  64940. var mesh = null;
  64941. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  64942. mesh = this._getDebugBoxMesh(scene);
  64943. impostor.getBoxSizeToRef(mesh.scaling);
  64944. }
  64945. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  64946. mesh = this._getDebugSphereMesh(scene);
  64947. var radius = impostor.getRadius();
  64948. mesh.scaling.x = radius * 2;
  64949. mesh.scaling.y = radius * 2;
  64950. mesh.scaling.z = radius * 2;
  64951. }
  64952. return mesh;
  64953. };
  64954. /** Releases all resources */
  64955. PhysicsViewer.prototype.dispose = function () {
  64956. for (var i = 0; i < this._numMeshes; i++) {
  64957. this.hideImpostor(this._impostors[i]);
  64958. }
  64959. if (this._debugBoxMesh) {
  64960. this._debugBoxMesh.dispose();
  64961. }
  64962. if (this._debugSphereMesh) {
  64963. this._debugSphereMesh.dispose();
  64964. }
  64965. if (this._debugMaterial) {
  64966. this._debugMaterial.dispose();
  64967. }
  64968. this._impostors.length = 0;
  64969. this._scene = null;
  64970. this._physicsEnginePlugin = null;
  64971. };
  64972. return PhysicsViewer;
  64973. }());
  64974. Debug.PhysicsViewer = PhysicsViewer;
  64975. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  64976. })(BABYLON || (BABYLON = {}));
  64977. //# sourceMappingURL=babylon.physicsViewer.js.map
  64978. var BABYLON;
  64979. (function (BABYLON) {
  64980. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  64981. get: function () {
  64982. return this._forceShowBoundingBoxes || false;
  64983. },
  64984. set: function (value) {
  64985. this._forceShowBoundingBoxes = value;
  64986. // Lazyly creates a BB renderer if needed.
  64987. if (value) {
  64988. this.getBoundingBoxRenderer();
  64989. }
  64990. },
  64991. enumerable: true,
  64992. configurable: true
  64993. });
  64994. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  64995. if (!this._boundingBoxRenderer) {
  64996. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  64997. }
  64998. return this._boundingBoxRenderer;
  64999. };
  65000. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  65001. get: function () {
  65002. return this._showBoundingBox || false;
  65003. },
  65004. set: function (value) {
  65005. this._showBoundingBox = value;
  65006. // Lazyly creates a BB renderer if needed.
  65007. if (value) {
  65008. this.getScene().getBoundingBoxRenderer();
  65009. }
  65010. },
  65011. enumerable: true,
  65012. configurable: true
  65013. });
  65014. /**
  65015. * Component responsible of rendering the bounding box of the meshes in a scene.
  65016. * This is usually used through the mesh.showBoundingBox or the scene.forceShowBoundingBoxes properties
  65017. */
  65018. var BoundingBoxRenderer = /** @class */ (function () {
  65019. /**
  65020. * Instantiates a new bounding box renderer in a scene.
  65021. * @param scene the scene the renderer renders in
  65022. */
  65023. function BoundingBoxRenderer(scene) {
  65024. /**
  65025. * The component name helpfull to identify the component in the list of scene components.
  65026. */
  65027. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  65028. /**
  65029. * Color of the bounding box lines placed in front of an object
  65030. */
  65031. this.frontColor = new BABYLON.Color3(1, 1, 1);
  65032. /**
  65033. * Color of the bounding box lines placed behind an object
  65034. */
  65035. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  65036. /**
  65037. * Defines if the renderer should show the back lines or not
  65038. */
  65039. this.showBackLines = true;
  65040. /**
  65041. * @hidden
  65042. */
  65043. this.renderList = new BABYLON.SmartArray(32);
  65044. this._vertexBuffers = {};
  65045. this.scene = scene;
  65046. scene._addComponent(this);
  65047. }
  65048. /**
  65049. * Registers the component in a given scene
  65050. */
  65051. BoundingBoxRenderer.prototype.register = function () {
  65052. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  65053. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  65054. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  65055. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER, this, this.render);
  65056. };
  65057. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  65058. if (mesh.showSubMeshesBoundingBox) {
  65059. var boundingInfo = subMesh.getBoundingInfo();
  65060. if (boundingInfo !== null && boundingInfo !== undefined) {
  65061. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  65062. this.renderList.push(boundingInfo.boundingBox);
  65063. }
  65064. }
  65065. };
  65066. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  65067. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  65068. var boundingInfo = sourceMesh.getBoundingInfo();
  65069. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  65070. this.renderList.push(boundingInfo.boundingBox);
  65071. }
  65072. };
  65073. BoundingBoxRenderer.prototype._prepareRessources = function () {
  65074. if (this._colorShader) {
  65075. return;
  65076. }
  65077. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  65078. attributes: [BABYLON.VertexBuffer.PositionKind],
  65079. uniforms: ["world", "viewProjection", "color"]
  65080. });
  65081. var engine = this.scene.getEngine();
  65082. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  65083. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  65084. this._createIndexBuffer();
  65085. };
  65086. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  65087. var engine = this.scene.getEngine();
  65088. 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]);
  65089. };
  65090. /**
  65091. * Rebuilds the elements related to this component in case of
  65092. * context lost for instance.
  65093. */
  65094. BoundingBoxRenderer.prototype.rebuild = function () {
  65095. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65096. if (vb) {
  65097. vb._rebuild();
  65098. }
  65099. this._createIndexBuffer();
  65100. };
  65101. /**
  65102. * @hidden
  65103. */
  65104. BoundingBoxRenderer.prototype.reset = function () {
  65105. this.renderList.reset();
  65106. };
  65107. /**
  65108. * Render the bounding boxes of a specific rendering group
  65109. * @param renderingGroupId defines the rendering group to render
  65110. */
  65111. BoundingBoxRenderer.prototype.render = function (renderingGroupId) {
  65112. if (this.renderList.length === 0) {
  65113. return;
  65114. }
  65115. this._prepareRessources();
  65116. if (!this._colorShader.isReady()) {
  65117. return;
  65118. }
  65119. var engine = this.scene.getEngine();
  65120. engine.setDepthWrite(false);
  65121. this._colorShader._preBind();
  65122. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  65123. var boundingBox = this.renderList.data[boundingBoxIndex];
  65124. if (boundingBox._tag !== renderingGroupId) {
  65125. continue;
  65126. }
  65127. var min = boundingBox.minimum;
  65128. var max = boundingBox.maximum;
  65129. var diff = max.subtract(min);
  65130. var median = min.add(diff.scale(0.5));
  65131. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  65132. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  65133. .multiply(boundingBox.getWorldMatrix());
  65134. // VBOs
  65135. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  65136. if (this.showBackLines) {
  65137. // Back
  65138. engine.setDepthFunctionToGreaterOrEqual();
  65139. this.scene.resetCachedMaterial();
  65140. this._colorShader.setColor4("color", this.backColor.toColor4());
  65141. this._colorShader.bind(worldMatrix);
  65142. // Draw order
  65143. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  65144. }
  65145. // Front
  65146. engine.setDepthFunctionToLess();
  65147. this.scene.resetCachedMaterial();
  65148. this._colorShader.setColor4("color", this.frontColor.toColor4());
  65149. this._colorShader.bind(worldMatrix);
  65150. // Draw order
  65151. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  65152. }
  65153. this._colorShader.unbind();
  65154. engine.setDepthFunctionToLessOrEqual();
  65155. engine.setDepthWrite(true);
  65156. };
  65157. /**
  65158. * In case of occlusion queries, we can render the occlusion bounding box through this method
  65159. * @param mesh Define the mesh to render the occlusion bounding box for
  65160. */
  65161. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  65162. this._prepareRessources();
  65163. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  65164. return;
  65165. }
  65166. var engine = this.scene.getEngine();
  65167. engine.setDepthWrite(false);
  65168. engine.setColorWrite(false);
  65169. this._colorShader._preBind();
  65170. var boundingBox = mesh._boundingInfo.boundingBox;
  65171. var min = boundingBox.minimum;
  65172. var max = boundingBox.maximum;
  65173. var diff = max.subtract(min);
  65174. var median = min.add(diff.scale(0.5));
  65175. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  65176. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  65177. .multiply(boundingBox.getWorldMatrix());
  65178. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  65179. engine.setDepthFunctionToLess();
  65180. this.scene.resetCachedMaterial();
  65181. this._colorShader.bind(worldMatrix);
  65182. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  65183. this._colorShader.unbind();
  65184. engine.setDepthFunctionToLessOrEqual();
  65185. engine.setDepthWrite(true);
  65186. engine.setColorWrite(true);
  65187. };
  65188. /**
  65189. * Dispose and release the resources attached to this renderer.
  65190. */
  65191. BoundingBoxRenderer.prototype.dispose = function () {
  65192. if (!this._colorShader) {
  65193. return;
  65194. }
  65195. this.renderList.dispose();
  65196. this._colorShader.dispose();
  65197. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65198. if (buffer) {
  65199. buffer.dispose();
  65200. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  65201. }
  65202. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  65203. };
  65204. return BoundingBoxRenderer;
  65205. }());
  65206. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  65207. })(BABYLON || (BABYLON = {}));
  65208. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  65209. var BABYLON;
  65210. (function (BABYLON) {
  65211. BABYLON.Engine.prototype.createTransformFeedback = function () {
  65212. return this._gl.createTransformFeedback();
  65213. };
  65214. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  65215. this._gl.deleteTransformFeedback(value);
  65216. };
  65217. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  65218. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  65219. };
  65220. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  65221. if (usePoints === void 0) { usePoints = true; }
  65222. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  65223. };
  65224. BABYLON.Engine.prototype.endTransformFeedback = function () {
  65225. this._gl.endTransformFeedback();
  65226. };
  65227. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  65228. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  65229. };
  65230. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  65231. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  65232. };
  65233. })(BABYLON || (BABYLON = {}));
  65234. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  65235. var BABYLON;
  65236. (function (BABYLON) {
  65237. /**
  65238. * This represents a GPU particle system in Babylon
  65239. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  65240. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  65241. */
  65242. var GPUParticleSystem = /** @class */ (function (_super) {
  65243. __extends(GPUParticleSystem, _super);
  65244. /**
  65245. * Instantiates a GPU particle system.
  65246. * 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.
  65247. * @param name The name of the particle system
  65248. * @param options The options used to create the system
  65249. * @param scene The scene the particle system belongs to
  65250. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  65251. */
  65252. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  65253. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  65254. var _this = _super.call(this, name) || this;
  65255. /**
  65256. * The layer mask we are rendering the particles through.
  65257. */
  65258. _this.layerMask = 0x0FFFFFFF;
  65259. _this._accumulatedCount = 0;
  65260. _this._targetIndex = 0;
  65261. _this._currentRenderId = -1;
  65262. _this._started = false;
  65263. _this._stopped = false;
  65264. _this._timeDelta = 0;
  65265. _this._attributesStrideSize = 21;
  65266. _this._actualFrame = 0;
  65267. _this._rawTextureWidth = 256;
  65268. /**
  65269. * An event triggered when the system is disposed.
  65270. */
  65271. _this.onDisposeObservable = new BABYLON.Observable();
  65272. /**
  65273. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  65274. * to override the particles.
  65275. */
  65276. _this.forceDepthWrite = false;
  65277. _this._preWarmDone = false;
  65278. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  65279. // Setup the default processing configuration to the scene.
  65280. _this._attachImageProcessingConfiguration(null);
  65281. _this._engine = _this._scene.getEngine();
  65282. if (!options.randomTextureSize) {
  65283. delete options.randomTextureSize;
  65284. }
  65285. var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
  65286. var optionsAsNumber = options;
  65287. if (isFinite(optionsAsNumber)) {
  65288. fullOptions.capacity = optionsAsNumber;
  65289. }
  65290. _this._capacity = fullOptions.capacity;
  65291. _this._activeCount = fullOptions.capacity;
  65292. _this._currentActiveCount = 0;
  65293. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  65294. _this._scene.particleSystems.push(_this);
  65295. _this._updateEffectOptions = {
  65296. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex", "cellStartOffset", "noiseCoordinates1", "noiseCoordinates2"],
  65297. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  65298. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  65299. "angleRange", "radiusRange", "cellInfos", "noiseStrength", "limitVelocityDamping"],
  65300. uniformBuffersNames: [],
  65301. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "limitVelocityGradientSampler", "noiseSampler", "dragGradientSampler"],
  65302. defines: "",
  65303. fallbacks: null,
  65304. onCompiled: null,
  65305. onError: null,
  65306. indexParameters: null,
  65307. maxSimultaneousLights: 0,
  65308. transformFeedbackVaryings: []
  65309. };
  65310. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  65311. // Random data
  65312. var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  65313. var d = [];
  65314. for (var i = 0; i < maxTextureSize; ++i) {
  65315. d.push(Math.random());
  65316. d.push(Math.random());
  65317. d.push(Math.random());
  65318. d.push(Math.random());
  65319. }
  65320. _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);
  65321. _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65322. _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65323. d = [];
  65324. for (var i = 0; i < maxTextureSize; ++i) {
  65325. d.push(Math.random());
  65326. d.push(Math.random());
  65327. d.push(Math.random());
  65328. d.push(Math.random());
  65329. }
  65330. _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);
  65331. _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65332. _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65333. _this._randomTextureSize = maxTextureSize;
  65334. return _this;
  65335. }
  65336. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  65337. /**
  65338. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  65339. */
  65340. get: function () {
  65341. if (!BABYLON.Engine.LastCreatedEngine) {
  65342. return false;
  65343. }
  65344. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  65345. },
  65346. enumerable: true,
  65347. configurable: true
  65348. });
  65349. /**
  65350. * Gets the maximum number of particles active at the same time.
  65351. * @returns The max number of active particles.
  65352. */
  65353. GPUParticleSystem.prototype.getCapacity = function () {
  65354. return this._capacity;
  65355. };
  65356. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  65357. /**
  65358. * Gets or set the number of active particles
  65359. */
  65360. get: function () {
  65361. return this._activeCount;
  65362. },
  65363. set: function (value) {
  65364. this._activeCount = Math.min(value, this._capacity);
  65365. },
  65366. enumerable: true,
  65367. configurable: true
  65368. });
  65369. /**
  65370. * Is this system ready to be used/rendered
  65371. * @return true if the system is ready
  65372. */
  65373. GPUParticleSystem.prototype.isReady = function () {
  65374. if (!this._updateEffect) {
  65375. this._recreateUpdateEffect();
  65376. this._recreateRenderEffect();
  65377. return false;
  65378. }
  65379. if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  65380. return false;
  65381. }
  65382. return true;
  65383. };
  65384. /**
  65385. * Gets if the system has been started. (Note: this will still be true after stop is called)
  65386. * @returns True if it has been started, otherwise false.
  65387. */
  65388. GPUParticleSystem.prototype.isStarted = function () {
  65389. return this._started;
  65390. };
  65391. /**
  65392. * Starts the particle system and begins to emit
  65393. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  65394. */
  65395. GPUParticleSystem.prototype.start = function (delay) {
  65396. var _this = this;
  65397. if (delay === void 0) { delay = this.startDelay; }
  65398. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  65399. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  65400. }
  65401. if (delay) {
  65402. setTimeout(function () {
  65403. _this.start(0);
  65404. }, delay);
  65405. return;
  65406. }
  65407. this._started = true;
  65408. this._stopped = false;
  65409. this._preWarmDone = false;
  65410. // Animations
  65411. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  65412. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  65413. }
  65414. };
  65415. /**
  65416. * Stops the particle system.
  65417. */
  65418. GPUParticleSystem.prototype.stop = function () {
  65419. this._stopped = true;
  65420. };
  65421. /**
  65422. * Remove all active particles
  65423. */
  65424. GPUParticleSystem.prototype.reset = function () {
  65425. this._releaseBuffers();
  65426. this._releaseVAOs();
  65427. this._currentActiveCount = 0;
  65428. this._targetIndex = 0;
  65429. };
  65430. /**
  65431. * Returns the string "GPUParticleSystem"
  65432. * @returns a string containing the class name
  65433. */
  65434. GPUParticleSystem.prototype.getClassName = function () {
  65435. return "GPUParticleSystem";
  65436. };
  65437. GPUParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  65438. _super.prototype._removeGradientAndTexture.call(this, gradient, gradients, texture);
  65439. this._releaseBuffers();
  65440. return this;
  65441. };
  65442. /**
  65443. * Adds a new color gradient
  65444. * @param gradient defines the gradient to use (between 0 and 1)
  65445. * @param color1 defines the color to affect to the specified gradient
  65446. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  65447. * @returns the current particle system
  65448. */
  65449. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  65450. if (!this._colorGradients) {
  65451. this._colorGradients = [];
  65452. }
  65453. var colorGradient = new BABYLON.ColorGradient();
  65454. colorGradient.gradient = gradient;
  65455. colorGradient.color1 = color1;
  65456. this._colorGradients.push(colorGradient);
  65457. this._colorGradients.sort(function (a, b) {
  65458. if (a.gradient < b.gradient) {
  65459. return -1;
  65460. }
  65461. else if (a.gradient > b.gradient) {
  65462. return 1;
  65463. }
  65464. return 0;
  65465. });
  65466. if (this._colorGradientsTexture) {
  65467. this._colorGradientsTexture.dispose();
  65468. this._colorGradientsTexture = null;
  65469. }
  65470. this._releaseBuffers();
  65471. return this;
  65472. };
  65473. /**
  65474. * Remove a specific color gradient
  65475. * @param gradient defines the gradient to remove
  65476. * @returns the current particle system
  65477. */
  65478. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  65479. this._removeGradientAndTexture(gradient, this._colorGradients, this._colorGradientsTexture);
  65480. this._colorGradientsTexture = null;
  65481. return this;
  65482. };
  65483. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  65484. var valueGradient = new BABYLON.FactorGradient();
  65485. valueGradient.gradient = gradient;
  65486. valueGradient.factor1 = factor;
  65487. factorGradients.push(valueGradient);
  65488. factorGradients.sort(function (a, b) {
  65489. if (a.gradient < b.gradient) {
  65490. return -1;
  65491. }
  65492. else if (a.gradient > b.gradient) {
  65493. return 1;
  65494. }
  65495. return 0;
  65496. });
  65497. this._releaseBuffers();
  65498. };
  65499. /**
  65500. * Adds a new size gradient
  65501. * @param gradient defines the gradient to use (between 0 and 1)
  65502. * @param factor defines the size factor to affect to the specified gradient
  65503. * @returns the current particle system
  65504. */
  65505. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  65506. if (!this._sizeGradients) {
  65507. this._sizeGradients = [];
  65508. }
  65509. this._addFactorGradient(this._sizeGradients, gradient, factor);
  65510. if (this._sizeGradientsTexture) {
  65511. this._sizeGradientsTexture.dispose();
  65512. this._sizeGradientsTexture = null;
  65513. }
  65514. this._releaseBuffers();
  65515. return this;
  65516. };
  65517. /**
  65518. * Remove a specific size gradient
  65519. * @param gradient defines the gradient to remove
  65520. * @returns the current particle system
  65521. */
  65522. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  65523. this._removeGradientAndTexture(gradient, this._sizeGradients, this._sizeGradientsTexture);
  65524. this._sizeGradientsTexture = null;
  65525. return this;
  65526. };
  65527. /**
  65528. * Adds a new angular speed gradient
  65529. * @param gradient defines the gradient to use (between 0 and 1)
  65530. * @param factor defines the angular speed to affect to the specified gradient
  65531. * @returns the current particle system
  65532. */
  65533. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  65534. if (!this._angularSpeedGradients) {
  65535. this._angularSpeedGradients = [];
  65536. }
  65537. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  65538. if (this._angularSpeedGradientsTexture) {
  65539. this._angularSpeedGradientsTexture.dispose();
  65540. this._angularSpeedGradientsTexture = null;
  65541. }
  65542. this._releaseBuffers();
  65543. return this;
  65544. };
  65545. /**
  65546. * Remove a specific angular speed gradient
  65547. * @param gradient defines the gradient to remove
  65548. * @returns the current particle system
  65549. */
  65550. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  65551. this._removeGradientAndTexture(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  65552. this._angularSpeedGradientsTexture = null;
  65553. return this;
  65554. };
  65555. /**
  65556. * Adds a new velocity gradient
  65557. * @param gradient defines the gradient to use (between 0 and 1)
  65558. * @param factor defines the velocity to affect to the specified gradient
  65559. * @returns the current particle system
  65560. */
  65561. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  65562. if (!this._velocityGradients) {
  65563. this._velocityGradients = [];
  65564. }
  65565. this._addFactorGradient(this._velocityGradients, gradient, factor);
  65566. if (this._velocityGradientsTexture) {
  65567. this._velocityGradientsTexture.dispose();
  65568. this._velocityGradientsTexture = null;
  65569. }
  65570. this._releaseBuffers();
  65571. return this;
  65572. };
  65573. /**
  65574. * Remove a specific velocity gradient
  65575. * @param gradient defines the gradient to remove
  65576. * @returns the current particle system
  65577. */
  65578. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  65579. this._removeGradientAndTexture(gradient, this._velocityGradients, this._velocityGradientsTexture);
  65580. this._velocityGradientsTexture = null;
  65581. return this;
  65582. };
  65583. /**
  65584. * Adds a new limit velocity gradient
  65585. * @param gradient defines the gradient to use (between 0 and 1)
  65586. * @param factor defines the limit velocity value to affect to the specified gradient
  65587. * @returns the current particle system
  65588. */
  65589. GPUParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor) {
  65590. if (!this._limitVelocityGradients) {
  65591. this._limitVelocityGradients = [];
  65592. }
  65593. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  65594. if (this._limitVelocityGradientsTexture) {
  65595. this._limitVelocityGradientsTexture.dispose();
  65596. this._limitVelocityGradientsTexture = null;
  65597. }
  65598. this._releaseBuffers();
  65599. return this;
  65600. };
  65601. /**
  65602. * Remove a specific limit velocity gradient
  65603. * @param gradient defines the gradient to remove
  65604. * @returns the current particle system
  65605. */
  65606. GPUParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  65607. this._removeGradientAndTexture(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  65608. this._limitVelocityGradientsTexture = null;
  65609. return this;
  65610. };
  65611. /**
  65612. * Adds a new drag gradient
  65613. * @param gradient defines the gradient to use (between 0 and 1)
  65614. * @param factor defines the drag value to affect to the specified gradient
  65615. * @returns the current particle system
  65616. */
  65617. GPUParticleSystem.prototype.addDragGradient = function (gradient, factor) {
  65618. if (!this._dragGradients) {
  65619. this._dragGradients = [];
  65620. }
  65621. this._addFactorGradient(this._dragGradients, gradient, factor);
  65622. if (this._dragGradientsTexture) {
  65623. this._dragGradientsTexture.dispose();
  65624. this._dragGradientsTexture = null;
  65625. }
  65626. this._releaseBuffers();
  65627. return this;
  65628. };
  65629. /**
  65630. * Remove a specific drag gradient
  65631. * @param gradient defines the gradient to remove
  65632. * @returns the current particle system
  65633. */
  65634. GPUParticleSystem.prototype.removeDragGradient = function (gradient) {
  65635. this._removeGradientAndTexture(gradient, this._dragGradients, this._dragGradientsTexture);
  65636. this._dragGradientsTexture = null;
  65637. return this;
  65638. };
  65639. /**
  65640. * Not supported by GPUParticleSystem
  65641. * @param gradient defines the gradient to use (between 0 and 1)
  65642. * @param factor defines the emit rate value to affect to the specified gradient
  65643. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  65644. * @returns the current particle system
  65645. */
  65646. GPUParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  65647. // Do nothing as emit rate is not supported by GPUParticleSystem
  65648. return this;
  65649. };
  65650. /**
  65651. * Not supported by GPUParticleSystem
  65652. * @param gradient defines the gradient to remove
  65653. * @returns the current particle system
  65654. */
  65655. GPUParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  65656. // Do nothing as emit rate is not supported by GPUParticleSystem
  65657. return this;
  65658. };
  65659. /**
  65660. * Not supported by GPUParticleSystem
  65661. * @param gradient defines the gradient to use (between 0 and 1)
  65662. * @param factor defines the start size value to affect to the specified gradient
  65663. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  65664. * @returns the current particle system
  65665. */
  65666. GPUParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  65667. // Do nothing as start size is not supported by GPUParticleSystem
  65668. return this;
  65669. };
  65670. /**
  65671. * Not supported by GPUParticleSystem
  65672. * @param gradient defines the gradient to remove
  65673. * @returns the current particle system
  65674. */
  65675. GPUParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  65676. // Do nothing as start size is not supported by GPUParticleSystem
  65677. return this;
  65678. };
  65679. /**
  65680. * Not supported by GPUParticleSystem
  65681. * @param gradient defines the gradient to use (between 0 and 1)
  65682. * @param min defines the color remap minimal range
  65683. * @param max defines the color remap maximal range
  65684. * @returns the current particle system
  65685. */
  65686. GPUParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  65687. // Do nothing as start size is not supported by GPUParticleSystem
  65688. return this;
  65689. };
  65690. /**
  65691. * Not supported by GPUParticleSystem
  65692. * @param gradient defines the gradient to remove
  65693. * @returns the current particle system
  65694. */
  65695. GPUParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  65696. // Do nothing as start size is not supported by GPUParticleSystem
  65697. return this;
  65698. };
  65699. /**
  65700. * Not supported by GPUParticleSystem
  65701. * @param gradient defines the gradient to use (between 0 and 1)
  65702. * @param min defines the alpha remap minimal range
  65703. * @param max defines the alpha remap maximal range
  65704. * @returns the current particle system
  65705. */
  65706. GPUParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  65707. // Do nothing as start size is not supported by GPUParticleSystem
  65708. return this;
  65709. };
  65710. /**
  65711. * Not supported by GPUParticleSystem
  65712. * @param gradient defines the gradient to remove
  65713. * @returns the current particle system
  65714. */
  65715. GPUParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  65716. // Do nothing as start size is not supported by GPUParticleSystem
  65717. return this;
  65718. };
  65719. /**
  65720. * Not supported by GPUParticleSystem
  65721. * @param gradient defines the gradient to use (between 0 and 1)
  65722. * @param color defines the color to affect to the specified gradient
  65723. * @returns the current particle system
  65724. */
  65725. GPUParticleSystem.prototype.addRampGradient = function (gradient, color) {
  65726. //Not supported by GPUParticleSystem
  65727. return this;
  65728. };
  65729. /**
  65730. * Not supported by GPUParticleSystem
  65731. * @param gradient defines the gradient to remove
  65732. * @returns the current particle system
  65733. */
  65734. GPUParticleSystem.prototype.removeRampGradient = function (gradient) {
  65735. //Not supported by GPUParticleSystem
  65736. return this;
  65737. };
  65738. /**
  65739. * Not supported by GPUParticleSystem
  65740. * @returns the list of ramp gradients
  65741. */
  65742. GPUParticleSystem.prototype.getRampGradients = function () {
  65743. return null;
  65744. };
  65745. Object.defineProperty(GPUParticleSystem.prototype, "useRampGradients", {
  65746. /**
  65747. * Not supported by GPUParticleSystem
  65748. * Gets or sets a boolean indicating that ramp gradients must be used
  65749. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  65750. */
  65751. get: function () {
  65752. //Not supported by GPUParticleSystem
  65753. return false;
  65754. },
  65755. set: function (value) {
  65756. //Not supported by GPUParticleSystem
  65757. },
  65758. enumerable: true,
  65759. configurable: true
  65760. });
  65761. /**
  65762. * Not supported by GPUParticleSystem
  65763. * @param gradient defines the gradient to use (between 0 and 1)
  65764. * @param factor defines the life time factor to affect to the specified gradient
  65765. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  65766. * @returns the current particle system
  65767. */
  65768. GPUParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  65769. //Not supported by GPUParticleSystem
  65770. return this;
  65771. };
  65772. /**
  65773. * Not supported by GPUParticleSystem
  65774. * @param gradient defines the gradient to remove
  65775. * @returns the current particle system
  65776. */
  65777. GPUParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  65778. //Not supported by GPUParticleSystem
  65779. return this;
  65780. };
  65781. GPUParticleSystem.prototype._reset = function () {
  65782. this._releaseBuffers();
  65783. };
  65784. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  65785. var updateVertexBuffers = {};
  65786. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  65787. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  65788. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  65789. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  65790. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  65791. var offset = 12;
  65792. if (!this._colorGradientsTexture) {
  65793. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  65794. offset += 4;
  65795. }
  65796. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  65797. offset += 3;
  65798. if (!this._isBillboardBased) {
  65799. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  65800. offset += 3;
  65801. }
  65802. if (this._angularSpeedGradientsTexture) {
  65803. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  65804. offset += 1;
  65805. }
  65806. else {
  65807. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  65808. offset += 2;
  65809. }
  65810. if (this._isAnimationSheetEnabled) {
  65811. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  65812. offset += 1;
  65813. if (this.spriteRandomStartCell) {
  65814. updateVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1);
  65815. offset += 1;
  65816. }
  65817. }
  65818. if (this.noiseTexture) {
  65819. updateVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3);
  65820. offset += 3;
  65821. updateVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3);
  65822. offset += 3;
  65823. }
  65824. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  65825. this._engine.bindArrayBuffer(null);
  65826. return vao;
  65827. };
  65828. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  65829. var renderVertexBuffers = {};
  65830. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  65831. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  65832. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  65833. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  65834. var offset = 12;
  65835. if (!this._colorGradientsTexture) {
  65836. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  65837. offset += 4;
  65838. }
  65839. if (this.billboardMode === BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED) {
  65840. renderVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3, this._attributesStrideSize, true);
  65841. }
  65842. offset += 3; // Direction
  65843. if (!this._isBillboardBased) {
  65844. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  65845. offset += 3;
  65846. }
  65847. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  65848. if (this._angularSpeedGradientsTexture) {
  65849. offset++;
  65850. }
  65851. else {
  65852. offset += 2;
  65853. }
  65854. if (this._isAnimationSheetEnabled) {
  65855. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  65856. offset += 1;
  65857. if (this.spriteRandomStartCell) {
  65858. renderVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true);
  65859. offset += 1;
  65860. }
  65861. }
  65862. if (this.noiseTexture) {
  65863. renderVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3, this._attributesStrideSize, true);
  65864. offset += 3;
  65865. renderVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3, this._attributesStrideSize, true);
  65866. offset += 3;
  65867. }
  65868. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  65869. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  65870. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  65871. this._engine.bindArrayBuffer(null);
  65872. return vao;
  65873. };
  65874. GPUParticleSystem.prototype._initialize = function (force) {
  65875. if (force === void 0) { force = false; }
  65876. if (this._buffer0 && !force) {
  65877. return;
  65878. }
  65879. var engine = this._scene.getEngine();
  65880. var data = new Array();
  65881. if (!this.isBillboardBased) {
  65882. this._attributesStrideSize += 3;
  65883. }
  65884. if (this._colorGradientsTexture) {
  65885. this._attributesStrideSize -= 4;
  65886. }
  65887. if (this._angularSpeedGradientsTexture) {
  65888. this._attributesStrideSize -= 1;
  65889. }
  65890. if (this._isAnimationSheetEnabled) {
  65891. this._attributesStrideSize += 1;
  65892. if (this.spriteRandomStartCell) {
  65893. this._attributesStrideSize += 1;
  65894. }
  65895. }
  65896. if (this.noiseTexture) {
  65897. this._attributesStrideSize += 6;
  65898. }
  65899. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  65900. // position
  65901. data.push(0.0);
  65902. data.push(0.0);
  65903. data.push(0.0);
  65904. // Age and life
  65905. data.push(0.0); // create the particle as a dead one to create a new one at start
  65906. data.push(0.0);
  65907. // Seed
  65908. data.push(Math.random());
  65909. data.push(Math.random());
  65910. data.push(Math.random());
  65911. data.push(Math.random());
  65912. // Size
  65913. data.push(0.0);
  65914. data.push(0.0);
  65915. data.push(0.0);
  65916. if (!this._colorGradientsTexture) {
  65917. // color
  65918. data.push(0.0);
  65919. data.push(0.0);
  65920. data.push(0.0);
  65921. data.push(0.0);
  65922. }
  65923. // direction
  65924. data.push(0.0);
  65925. data.push(0.0);
  65926. data.push(0.0);
  65927. if (!this.isBillboardBased) {
  65928. // initialDirection
  65929. data.push(0.0);
  65930. data.push(0.0);
  65931. data.push(0.0);
  65932. }
  65933. // angle
  65934. data.push(0.0);
  65935. if (!this._angularSpeedGradientsTexture) {
  65936. data.push(0.0);
  65937. }
  65938. if (this._isAnimationSheetEnabled) {
  65939. data.push(0.0);
  65940. if (this.spriteRandomStartCell) {
  65941. data.push(0.0);
  65942. }
  65943. }
  65944. if (this.noiseTexture) { // Random coordinates for reading into noise texture
  65945. data.push(Math.random());
  65946. data.push(Math.random());
  65947. data.push(Math.random());
  65948. data.push(Math.random());
  65949. data.push(Math.random());
  65950. data.push(Math.random());
  65951. }
  65952. }
  65953. // Sprite data
  65954. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  65955. -0.5, 0.5, 0, 1,
  65956. -0.5, -0.5, 0, 0,
  65957. 0.5, -0.5, 1, 0]);
  65958. // Buffers
  65959. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  65960. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  65961. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  65962. // Update VAO
  65963. this._updateVAO = [];
  65964. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  65965. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  65966. // Render VAO
  65967. this._renderVAO = [];
  65968. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  65969. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  65970. // Links
  65971. this._sourceBuffer = this._buffer0;
  65972. this._targetBuffer = this._buffer1;
  65973. };
  65974. /** @hidden */
  65975. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  65976. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  65977. if (this._isBillboardBased) {
  65978. defines += "\n#define BILLBOARD";
  65979. }
  65980. if (this._colorGradientsTexture) {
  65981. defines += "\n#define COLORGRADIENTS";
  65982. }
  65983. if (this._sizeGradientsTexture) {
  65984. defines += "\n#define SIZEGRADIENTS";
  65985. }
  65986. if (this._angularSpeedGradientsTexture) {
  65987. defines += "\n#define ANGULARSPEEDGRADIENTS";
  65988. }
  65989. if (this._velocityGradientsTexture) {
  65990. defines += "\n#define VELOCITYGRADIENTS";
  65991. }
  65992. if (this._limitVelocityGradientsTexture) {
  65993. defines += "\n#define LIMITVELOCITYGRADIENTS";
  65994. }
  65995. if (this._dragGradientsTexture) {
  65996. defines += "\n#define DRAGGRADIENTS";
  65997. }
  65998. if (this.isAnimationSheetEnabled) {
  65999. defines += "\n#define ANIMATESHEET";
  66000. if (this.spriteRandomStartCell) {
  66001. defines += "\n#define ANIMATESHEETRANDOMSTART";
  66002. }
  66003. }
  66004. if (this.noiseTexture) {
  66005. defines += "\n#define NOISE";
  66006. }
  66007. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  66008. return;
  66009. }
  66010. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  66011. if (!this._colorGradientsTexture) {
  66012. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  66013. }
  66014. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  66015. if (!this._isBillboardBased) {
  66016. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  66017. }
  66018. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  66019. if (this.isAnimationSheetEnabled) {
  66020. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  66021. if (this.spriteRandomStartCell) {
  66022. this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset");
  66023. }
  66024. }
  66025. if (this.noiseTexture) {
  66026. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1");
  66027. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2");
  66028. }
  66029. this._updateEffectOptions.defines = defines;
  66030. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  66031. };
  66032. /** @hidden */
  66033. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  66034. var defines = "";
  66035. if (this._scene.clipPlane) {
  66036. defines = "\n#define CLIPPLANE";
  66037. }
  66038. if (this._scene.clipPlane2) {
  66039. defines = "\n#define CLIPPLANE2";
  66040. }
  66041. if (this._scene.clipPlane3) {
  66042. defines = "\n#define CLIPPLANE3";
  66043. }
  66044. if (this._scene.clipPlane4) {
  66045. defines = "\n#define CLIPPLANE4";
  66046. }
  66047. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_MULTIPLY) {
  66048. defines = "\n#define BLENDMULTIPLYMODE";
  66049. }
  66050. if (this._isBillboardBased) {
  66051. defines += "\n#define BILLBOARD";
  66052. switch (this.billboardMode) {
  66053. case BABYLON.ParticleSystem.BILLBOARDMODE_Y:
  66054. defines += "\n#define BILLBOARDY";
  66055. break;
  66056. case BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED:
  66057. defines += "\n#define BILLBOARDSTRETCHED";
  66058. break;
  66059. case BABYLON.ParticleSystem.BILLBOARDMODE_ALL:
  66060. default:
  66061. break;
  66062. }
  66063. }
  66064. if (this._colorGradientsTexture) {
  66065. defines += "\n#define COLORGRADIENTS";
  66066. }
  66067. if (this.isAnimationSheetEnabled) {
  66068. defines += "\n#define ANIMATESHEET";
  66069. }
  66070. if (this._imageProcessingConfiguration) {
  66071. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  66072. defines += "\n" + this._imageProcessingConfigurationDefines.toString();
  66073. }
  66074. if (this._renderEffect && this._renderEffect.defines === defines) {
  66075. return;
  66076. }
  66077. var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
  66078. var samplers = ["textureSampler", "colorGradientSampler"];
  66079. if (BABYLON.ImageProcessingConfiguration) {
  66080. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  66081. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  66082. }
  66083. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "direction", "initialDirection", "angle", "cellIndex"], uniforms, samplers, this._scene.getEngine(), defines);
  66084. };
  66085. /**
  66086. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  66087. * @param preWarm defines if we are in the pre-warmimg phase
  66088. */
  66089. GPUParticleSystem.prototype.animate = function (preWarm) {
  66090. if (preWarm === void 0) { preWarm = false; }
  66091. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  66092. this._actualFrame += this._timeDelta;
  66093. if (!this._stopped) {
  66094. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  66095. this.stop();
  66096. }
  66097. }
  66098. };
  66099. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  66100. var texture = this[textureName];
  66101. if (!factorGradients || !factorGradients.length || texture) {
  66102. return;
  66103. }
  66104. var data = new Float32Array(this._rawTextureWidth);
  66105. for (var x = 0; x < this._rawTextureWidth; x++) {
  66106. var ratio = x / this._rawTextureWidth;
  66107. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  66108. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  66109. });
  66110. }
  66111. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66112. };
  66113. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  66114. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  66115. };
  66116. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  66117. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  66118. };
  66119. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  66120. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  66121. };
  66122. GPUParticleSystem.prototype._createLimitVelocityGradientTexture = function () {
  66123. this._createFactorGradientTexture(this._limitVelocityGradients, "_limitVelocityGradientsTexture");
  66124. };
  66125. GPUParticleSystem.prototype._createDragGradientTexture = function () {
  66126. this._createFactorGradientTexture(this._dragGradients, "_dragGradientsTexture");
  66127. };
  66128. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  66129. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  66130. return;
  66131. }
  66132. var data = new Uint8Array(this._rawTextureWidth * 4);
  66133. var tmpColor = BABYLON.Tmp.Color4[0];
  66134. for (var x = 0; x < this._rawTextureWidth; x++) {
  66135. var ratio = x / this._rawTextureWidth;
  66136. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  66137. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  66138. data[x * 4] = tmpColor.r * 255;
  66139. data[x * 4 + 1] = tmpColor.g * 255;
  66140. data[x * 4 + 2] = tmpColor.b * 255;
  66141. data[x * 4 + 3] = tmpColor.a * 255;
  66142. });
  66143. }
  66144. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66145. };
  66146. /**
  66147. * Renders the particle system in its current state
  66148. * @param preWarm defines if the system should only update the particles but not render them
  66149. * @returns the current number of particles
  66150. */
  66151. GPUParticleSystem.prototype.render = function (preWarm) {
  66152. if (preWarm === void 0) { preWarm = false; }
  66153. if (!this._started) {
  66154. return 0;
  66155. }
  66156. this._createColorGradientTexture();
  66157. this._createSizeGradientTexture();
  66158. this._createAngularSpeedGradientTexture();
  66159. this._createVelocityGradientTexture();
  66160. this._createLimitVelocityGradientTexture();
  66161. this._createDragGradientTexture();
  66162. this._recreateUpdateEffect();
  66163. this._recreateRenderEffect();
  66164. if (!this.isReady()) {
  66165. return 0;
  66166. }
  66167. if (!preWarm) {
  66168. if (!this._preWarmDone && this.preWarmCycles) {
  66169. for (var index = 0; index < this.preWarmCycles; index++) {
  66170. this.animate(true);
  66171. this.render(true);
  66172. }
  66173. this._preWarmDone = true;
  66174. }
  66175. if (this._currentRenderId === this._scene.getRenderId()) {
  66176. return 0;
  66177. }
  66178. this._currentRenderId = this._scene.getRenderId();
  66179. }
  66180. // Get everything ready to render
  66181. this._initialize();
  66182. this._accumulatedCount += this.emitRate * this._timeDelta;
  66183. if (this._accumulatedCount > 1) {
  66184. var intPart = this._accumulatedCount | 0;
  66185. this._accumulatedCount -= intPart;
  66186. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  66187. }
  66188. if (!this._currentActiveCount) {
  66189. return 0;
  66190. }
  66191. // Enable update effect
  66192. this._engine.enableEffect(this._updateEffect);
  66193. this._engine.setState(false);
  66194. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  66195. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  66196. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  66197. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  66198. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  66199. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  66200. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  66201. if (!this._colorGradientsTexture) {
  66202. this._updateEffect.setDirectColor4("color1", this.color1);
  66203. this._updateEffect.setDirectColor4("color2", this.color2);
  66204. }
  66205. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  66206. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  66207. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  66208. this._updateEffect.setVector3("gravity", this.gravity);
  66209. if (this._sizeGradientsTexture) {
  66210. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  66211. }
  66212. if (this._angularSpeedGradientsTexture) {
  66213. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  66214. }
  66215. if (this._velocityGradientsTexture) {
  66216. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  66217. }
  66218. if (this._limitVelocityGradientsTexture) {
  66219. this._updateEffect.setTexture("limitVelocityGradientSampler", this._limitVelocityGradientsTexture);
  66220. this._updateEffect.setFloat("limitVelocityDamping", this.limitVelocityDamping);
  66221. }
  66222. if (this._dragGradientsTexture) {
  66223. this._updateEffect.setTexture("dragGradientSampler", this._dragGradientsTexture);
  66224. }
  66225. if (this.particleEmitterType) {
  66226. this.particleEmitterType.applyToShader(this._updateEffect);
  66227. }
  66228. if (this._isAnimationSheetEnabled) {
  66229. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  66230. }
  66231. if (this.noiseTexture) {
  66232. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  66233. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  66234. }
  66235. var emitterWM;
  66236. if (this.emitter.position) {
  66237. var emitterMesh = this.emitter;
  66238. emitterWM = emitterMesh.getWorldMatrix();
  66239. }
  66240. else {
  66241. var emitterPosition = this.emitter;
  66242. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  66243. }
  66244. this._updateEffect.setMatrix("emitterWM", emitterWM);
  66245. // Bind source VAO
  66246. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  66247. // Update
  66248. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  66249. this._engine.setRasterizerState(false);
  66250. this._engine.beginTransformFeedback(true);
  66251. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  66252. this._engine.endTransformFeedback();
  66253. this._engine.setRasterizerState(true);
  66254. this._engine.bindTransformFeedbackBuffer(null);
  66255. if (!preWarm) {
  66256. // Enable render effect
  66257. this._engine.enableEffect(this._renderEffect);
  66258. var viewMatrix = this._scene.getViewMatrix();
  66259. this._renderEffect.setMatrix("view", viewMatrix);
  66260. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  66261. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  66262. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  66263. if (this._colorGradientsTexture) {
  66264. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  66265. }
  66266. else {
  66267. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  66268. }
  66269. if (this._isAnimationSheetEnabled && this.particleTexture) {
  66270. var baseSize = this.particleTexture.getBaseSize();
  66271. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  66272. }
  66273. if (this._isBillboardBased) {
  66274. var camera = this._scene.activeCamera;
  66275. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  66276. }
  66277. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  66278. var invView = viewMatrix.clone();
  66279. invView.invert();
  66280. this._renderEffect.setMatrix("invView", invView);
  66281. BABYLON.MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
  66282. }
  66283. // image processing
  66284. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  66285. this._imageProcessingConfiguration.bind(this._renderEffect);
  66286. }
  66287. // Draw order
  66288. switch (this.blendMode) {
  66289. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  66290. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  66291. break;
  66292. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  66293. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  66294. break;
  66295. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  66296. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  66297. break;
  66298. case BABYLON.ParticleSystem.BLENDMODE_MULTIPLY:
  66299. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  66300. break;
  66301. }
  66302. if (this.forceDepthWrite) {
  66303. this._engine.setDepthWrite(true);
  66304. }
  66305. // Bind source VAO
  66306. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  66307. // Render
  66308. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  66309. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  66310. }
  66311. // Switch VAOs
  66312. this._targetIndex++;
  66313. if (this._targetIndex === 2) {
  66314. this._targetIndex = 0;
  66315. }
  66316. // Switch buffers
  66317. var tmpBuffer = this._sourceBuffer;
  66318. this._sourceBuffer = this._targetBuffer;
  66319. this._targetBuffer = tmpBuffer;
  66320. return this._currentActiveCount;
  66321. };
  66322. /**
  66323. * Rebuilds the particle system
  66324. */
  66325. GPUParticleSystem.prototype.rebuild = function () {
  66326. this._initialize(true);
  66327. };
  66328. GPUParticleSystem.prototype._releaseBuffers = function () {
  66329. if (this._buffer0) {
  66330. this._buffer0.dispose();
  66331. this._buffer0 = null;
  66332. }
  66333. if (this._buffer1) {
  66334. this._buffer1.dispose();
  66335. this._buffer1 = null;
  66336. }
  66337. if (this._spriteBuffer) {
  66338. this._spriteBuffer.dispose();
  66339. this._spriteBuffer = null;
  66340. }
  66341. };
  66342. GPUParticleSystem.prototype._releaseVAOs = function () {
  66343. if (!this._updateVAO) {
  66344. return;
  66345. }
  66346. for (var index = 0; index < this._updateVAO.length; index++) {
  66347. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  66348. }
  66349. this._updateVAO = [];
  66350. for (var index = 0; index < this._renderVAO.length; index++) {
  66351. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  66352. }
  66353. this._renderVAO = [];
  66354. };
  66355. /**
  66356. * Disposes the particle system and free the associated resources
  66357. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  66358. */
  66359. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  66360. if (disposeTexture === void 0) { disposeTexture = true; }
  66361. var index = this._scene.particleSystems.indexOf(this);
  66362. if (index > -1) {
  66363. this._scene.particleSystems.splice(index, 1);
  66364. }
  66365. this._releaseBuffers();
  66366. this._releaseVAOs();
  66367. if (this._colorGradientsTexture) {
  66368. this._colorGradientsTexture.dispose();
  66369. this._colorGradientsTexture = null;
  66370. }
  66371. if (this._sizeGradientsTexture) {
  66372. this._sizeGradientsTexture.dispose();
  66373. this._sizeGradientsTexture = null;
  66374. }
  66375. if (this._angularSpeedGradientsTexture) {
  66376. this._angularSpeedGradientsTexture.dispose();
  66377. this._angularSpeedGradientsTexture = null;
  66378. }
  66379. if (this._velocityGradientsTexture) {
  66380. this._velocityGradientsTexture.dispose();
  66381. this._velocityGradientsTexture = null;
  66382. }
  66383. if (this._limitVelocityGradientsTexture) {
  66384. this._limitVelocityGradientsTexture.dispose();
  66385. this._limitVelocityGradientsTexture = null;
  66386. }
  66387. if (this._dragGradientsTexture) {
  66388. this._dragGradientsTexture.dispose();
  66389. this._dragGradientsTexture = null;
  66390. }
  66391. if (this._randomTexture) {
  66392. this._randomTexture.dispose();
  66393. this._randomTexture = null;
  66394. }
  66395. if (this._randomTexture2) {
  66396. this._randomTexture2.dispose();
  66397. this._randomTexture2 = null;
  66398. }
  66399. if (disposeTexture && this.particleTexture) {
  66400. this.particleTexture.dispose();
  66401. this.particleTexture = null;
  66402. }
  66403. if (disposeTexture && this.noiseTexture) {
  66404. this.noiseTexture.dispose();
  66405. this.noiseTexture = null;
  66406. }
  66407. // Callback
  66408. this.onDisposeObservable.notifyObservers(this);
  66409. this.onDisposeObservable.clear();
  66410. };
  66411. /**
  66412. * Clones the particle system.
  66413. * @param name The name of the cloned object
  66414. * @param newEmitter The new emitter to use
  66415. * @returns the cloned particle system
  66416. */
  66417. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  66418. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  66419. BABYLON.Tools.DeepCopy(this, result);
  66420. if (newEmitter === undefined) {
  66421. newEmitter = this.emitter;
  66422. }
  66423. result.emitter = newEmitter;
  66424. if (this.particleTexture) {
  66425. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  66426. }
  66427. return result;
  66428. };
  66429. /**
  66430. * Serializes the particle system to a JSON object.
  66431. * @returns the JSON object
  66432. */
  66433. GPUParticleSystem.prototype.serialize = function () {
  66434. var serializationObject = {};
  66435. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  66436. serializationObject.activeParticleCount = this.activeParticleCount;
  66437. return serializationObject;
  66438. };
  66439. /**
  66440. * Parses a JSON object to create a GPU particle system.
  66441. * @param parsedParticleSystem The JSON object to parse
  66442. * @param scene The scene to create the particle system in
  66443. * @param rootUrl The root url to use to load external dependencies like texture
  66444. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  66445. * @returns the parsed GPU particle system
  66446. */
  66447. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  66448. if (doNotStart === void 0) { doNotStart = false; }
  66449. var name = parsedParticleSystem.name;
  66450. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  66451. if (parsedParticleSystem.activeParticleCount) {
  66452. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  66453. }
  66454. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  66455. // Auto start
  66456. if (parsedParticleSystem.preventAutoStart) {
  66457. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  66458. }
  66459. if (!doNotStart && !particleSystem.preventAutoStart) {
  66460. particleSystem.start();
  66461. }
  66462. return particleSystem;
  66463. };
  66464. return GPUParticleSystem;
  66465. }(BABYLON.BaseParticleSystem));
  66466. BABYLON.GPUParticleSystem = GPUParticleSystem;
  66467. })(BABYLON || (BABYLON = {}));
  66468. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  66469. var BABYLON;
  66470. (function (BABYLON) {
  66471. /**
  66472. * Represents one particle of a solid particle system.
  66473. */
  66474. var SolidParticle = /** @class */ (function () {
  66475. /**
  66476. * Creates a Solid Particle object.
  66477. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  66478. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  66479. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  66480. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  66481. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  66482. * @param shapeId (integer) is the model shape identifier in the SPS.
  66483. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  66484. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  66485. */
  66486. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  66487. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  66488. /**
  66489. * particle global index
  66490. */
  66491. this.idx = 0;
  66492. /**
  66493. * The color of the particle
  66494. */
  66495. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  66496. /**
  66497. * The world space position of the particle.
  66498. */
  66499. this.position = BABYLON.Vector3.Zero();
  66500. /**
  66501. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  66502. */
  66503. this.rotation = BABYLON.Vector3.Zero();
  66504. /**
  66505. * The scaling of the particle.
  66506. */
  66507. this.scaling = BABYLON.Vector3.One();
  66508. /**
  66509. * The uvs of the particle.
  66510. */
  66511. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  66512. /**
  66513. * The current speed of the particle.
  66514. */
  66515. this.velocity = BABYLON.Vector3.Zero();
  66516. /**
  66517. * The pivot point in the particle local space.
  66518. */
  66519. this.pivot = BABYLON.Vector3.Zero();
  66520. /**
  66521. * Must the particle be translated from its pivot point in its local space ?
  66522. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  66523. * Default : false
  66524. */
  66525. this.translateFromPivot = false;
  66526. /**
  66527. * Is the particle active or not ?
  66528. */
  66529. this.alive = true;
  66530. /**
  66531. * Is the particle visible or not ?
  66532. */
  66533. this.isVisible = true;
  66534. /**
  66535. * Index of this particle in the global "positions" array (Internal use)
  66536. * @hidden
  66537. */
  66538. this._pos = 0;
  66539. /**
  66540. * @hidden Index of this particle in the global "indices" array (Internal use)
  66541. */
  66542. this._ind = 0;
  66543. /**
  66544. * ModelShape id of this particle
  66545. */
  66546. this.shapeId = 0;
  66547. /**
  66548. * Index of the particle in its shape id (Internal use)
  66549. */
  66550. this.idxInShape = 0;
  66551. /**
  66552. * @hidden Still set as invisible in order to skip useless computations (Internal use)
  66553. */
  66554. this._stillInvisible = false;
  66555. /**
  66556. * @hidden Last computed particle rotation matrix
  66557. */
  66558. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  66559. /**
  66560. * Parent particle Id, if any.
  66561. * Default null.
  66562. */
  66563. this.parentId = null;
  66564. /**
  66565. * @hidden Internal global position in the SPS.
  66566. */
  66567. this._globalPosition = BABYLON.Vector3.Zero();
  66568. this.idx = particleIndex;
  66569. this._pos = positionIndex;
  66570. this._ind = indiceIndex;
  66571. this._model = model;
  66572. this.shapeId = shapeId;
  66573. this.idxInShape = idxInShape;
  66574. this._sps = sps;
  66575. if (modelBoundingInfo) {
  66576. this._modelBoundingInfo = modelBoundingInfo;
  66577. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  66578. }
  66579. }
  66580. Object.defineProperty(SolidParticle.prototype, "scale", {
  66581. /**
  66582. * Legacy support, changed scale to scaling
  66583. */
  66584. get: function () {
  66585. return this.scaling;
  66586. },
  66587. /**
  66588. * Legacy support, changed scale to scaling
  66589. */
  66590. set: function (scale) {
  66591. this.scaling = scale;
  66592. },
  66593. enumerable: true,
  66594. configurable: true
  66595. });
  66596. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  66597. /**
  66598. * Legacy support, changed quaternion to rotationQuaternion
  66599. */
  66600. get: function () {
  66601. return this.rotationQuaternion;
  66602. },
  66603. /**
  66604. * Legacy support, changed quaternion to rotationQuaternion
  66605. */
  66606. set: function (q) {
  66607. this.rotationQuaternion = q;
  66608. },
  66609. enumerable: true,
  66610. configurable: true
  66611. });
  66612. /**
  66613. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  66614. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  66615. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  66616. * @returns true if it intersects
  66617. */
  66618. SolidParticle.prototype.intersectsMesh = function (target) {
  66619. if (!this._boundingInfo || !target._boundingInfo) {
  66620. return false;
  66621. }
  66622. if (this._sps._bSphereOnly) {
  66623. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  66624. }
  66625. return this._boundingInfo.intersects(target._boundingInfo, false);
  66626. };
  66627. return SolidParticle;
  66628. }());
  66629. BABYLON.SolidParticle = SolidParticle;
  66630. /**
  66631. * Represents the shape of the model used by one particle of a solid particle system.
  66632. * SPS internal tool, don't use it manually.
  66633. */
  66634. var ModelShape = /** @class */ (function () {
  66635. /**
  66636. * 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.
  66637. * SPS internal tool, don't use it manually.
  66638. * @hidden
  66639. */
  66640. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  66641. /**
  66642. * length of the shape in the model indices array (internal use)
  66643. * @hidden
  66644. */
  66645. this._indicesLength = 0;
  66646. this.shapeID = id;
  66647. this._shape = shape;
  66648. this._indicesLength = indicesLength;
  66649. this._shapeUV = shapeUV;
  66650. this._positionFunction = posFunction;
  66651. this._vertexFunction = vtxFunction;
  66652. }
  66653. return ModelShape;
  66654. }());
  66655. BABYLON.ModelShape = ModelShape;
  66656. /**
  66657. * Represents a Depth Sorted Particle in the solid particle system.
  66658. */
  66659. var DepthSortedParticle = /** @class */ (function () {
  66660. function DepthSortedParticle() {
  66661. /**
  66662. * Index of the particle in the "indices" array
  66663. */
  66664. this.ind = 0;
  66665. /**
  66666. * Length of the particle shape in the "indices" array
  66667. */
  66668. this.indicesLength = 0;
  66669. /**
  66670. * Squared distance from the particle to the camera
  66671. */
  66672. this.sqDistance = 0.0;
  66673. }
  66674. return DepthSortedParticle;
  66675. }());
  66676. BABYLON.DepthSortedParticle = DepthSortedParticle;
  66677. })(BABYLON || (BABYLON = {}));
  66678. //# sourceMappingURL=babylon.solidParticle.js.map
  66679. var BABYLON;
  66680. (function (BABYLON) {
  66681. /**
  66682. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  66683. *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.
  66684. * The SPS is also a particle system. It provides some methods to manage the particles.
  66685. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  66686. *
  66687. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  66688. */
  66689. var SolidParticleSystem = /** @class */ (function () {
  66690. /**
  66691. * Creates a SPS (Solid Particle System) object.
  66692. * @param name (String) is the SPS name, this will be the underlying mesh name.
  66693. * @param scene (Scene) is the scene in which the SPS is added.
  66694. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  66695. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  66696. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  66697. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  66698. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  66699. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  66700. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  66701. */
  66702. function SolidParticleSystem(name, scene, options) {
  66703. /**
  66704. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  66705. * Example : var p = SPS.particles[i];
  66706. */
  66707. this.particles = new Array();
  66708. /**
  66709. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  66710. */
  66711. this.nbParticles = 0;
  66712. /**
  66713. * If the particles must ever face the camera (default false). Useful for planar particles.
  66714. */
  66715. this.billboard = false;
  66716. /**
  66717. * Recompute normals when adding a shape
  66718. */
  66719. this.recomputeNormals = true;
  66720. /**
  66721. * This a counter ofr your own usage. It's not set by any SPS functions.
  66722. */
  66723. this.counter = 0;
  66724. /**
  66725. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  66726. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  66727. */
  66728. this.vars = {};
  66729. /**
  66730. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  66731. * @hidden
  66732. */
  66733. this._bSphereOnly = false;
  66734. /**
  66735. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  66736. * @hidden
  66737. */
  66738. this._bSphereRadiusFactor = 1.0;
  66739. this._positions = new Array();
  66740. this._indices = new Array();
  66741. this._normals = new Array();
  66742. this._colors = new Array();
  66743. this._uvs = new Array();
  66744. this._index = 0; // indices index
  66745. this._updatable = true;
  66746. this._pickable = false;
  66747. this._isVisibilityBoxLocked = false;
  66748. this._alwaysVisible = false;
  66749. this._depthSort = false;
  66750. this._shapeCounter = 0;
  66751. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  66752. this._color = new BABYLON.Color4(0, 0, 0, 0);
  66753. this._computeParticleColor = true;
  66754. this._computeParticleTexture = true;
  66755. this._computeParticleRotation = true;
  66756. this._computeParticleVertex = false;
  66757. this._computeBoundingBox = false;
  66758. this._depthSortParticles = true;
  66759. this._cam_axisZ = BABYLON.Vector3.Zero();
  66760. this._cam_axisY = BABYLON.Vector3.Zero();
  66761. this._cam_axisX = BABYLON.Vector3.Zero();
  66762. this._axisZ = BABYLON.Axis.Z;
  66763. this._camDir = BABYLON.Vector3.Zero();
  66764. this._camInvertedPosition = BABYLON.Vector3.Zero();
  66765. this._rotMatrix = new BABYLON.Matrix();
  66766. this._invertMatrix = new BABYLON.Matrix();
  66767. this._rotated = BABYLON.Vector3.Zero();
  66768. this._quaternion = new BABYLON.Quaternion();
  66769. this._vertex = BABYLON.Vector3.Zero();
  66770. this._normal = BABYLON.Vector3.Zero();
  66771. this._yaw = 0.0;
  66772. this._pitch = 0.0;
  66773. this._roll = 0.0;
  66774. this._halfroll = 0.0;
  66775. this._halfpitch = 0.0;
  66776. this._halfyaw = 0.0;
  66777. this._sinRoll = 0.0;
  66778. this._cosRoll = 0.0;
  66779. this._sinPitch = 0.0;
  66780. this._cosPitch = 0.0;
  66781. this._sinYaw = 0.0;
  66782. this._cosYaw = 0.0;
  66783. this._mustUnrotateFixedNormals = false;
  66784. this._minimum = BABYLON.Vector3.Zero();
  66785. this._maximum = BABYLON.Vector3.Zero();
  66786. this._minBbox = BABYLON.Vector3.Zero();
  66787. this._maxBbox = BABYLON.Vector3.Zero();
  66788. this._particlesIntersect = false;
  66789. this._depthSortFunction = function (p1, p2) {
  66790. return (p2.sqDistance - p1.sqDistance);
  66791. };
  66792. this._needs32Bits = false;
  66793. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  66794. this._scaledPivot = BABYLON.Vector3.Zero();
  66795. this._particleHasParent = false;
  66796. this.name = name;
  66797. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  66798. this._camera = scene.activeCamera;
  66799. this._pickable = options ? options.isPickable : false;
  66800. this._depthSort = options ? options.enableDepthSort : false;
  66801. this._particlesIntersect = options ? options.particleIntersection : false;
  66802. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  66803. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  66804. if (options && options.updatable !== undefined) {
  66805. this._updatable = options.updatable;
  66806. }
  66807. else {
  66808. this._updatable = true;
  66809. }
  66810. if (this._pickable) {
  66811. this.pickedParticles = [];
  66812. }
  66813. if (this._depthSort) {
  66814. this.depthSortedParticles = [];
  66815. }
  66816. }
  66817. /**
  66818. * Builds the SPS underlying mesh. Returns a standard Mesh.
  66819. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  66820. * @returns the created mesh
  66821. */
  66822. SolidParticleSystem.prototype.buildMesh = function () {
  66823. if (this.nbParticles === 0) {
  66824. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  66825. this.addShape(triangle, 1);
  66826. triangle.dispose();
  66827. }
  66828. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  66829. this._positions32 = new Float32Array(this._positions);
  66830. this._uvs32 = new Float32Array(this._uvs);
  66831. this._colors32 = new Float32Array(this._colors);
  66832. if (this.recomputeNormals) {
  66833. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  66834. }
  66835. this._normals32 = new Float32Array(this._normals);
  66836. this._fixedNormal32 = new Float32Array(this._normals);
  66837. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  66838. this._unrotateFixedNormals();
  66839. }
  66840. var vertexData = new BABYLON.VertexData();
  66841. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  66842. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  66843. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  66844. if (this._uvs32.length > 0) {
  66845. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  66846. }
  66847. if (this._colors32.length > 0) {
  66848. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  66849. }
  66850. var mesh = new BABYLON.Mesh(this.name, this._scene);
  66851. vertexData.applyToMesh(mesh, this._updatable);
  66852. this.mesh = mesh;
  66853. this.mesh.isPickable = this._pickable;
  66854. // free memory
  66855. if (!this._depthSort) {
  66856. this._indices = null;
  66857. }
  66858. this._positions = null;
  66859. this._normals = null;
  66860. this._uvs = null;
  66861. this._colors = null;
  66862. if (!this._updatable) {
  66863. this.particles.length = 0;
  66864. }
  66865. return mesh;
  66866. };
  66867. /**
  66868. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  66869. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  66870. * Thus the particles generated from `digest()` have their property `position` set yet.
  66871. * @param mesh ( Mesh ) is the mesh to be digested
  66872. * @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
  66873. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  66874. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  66875. * @returns the current SPS
  66876. */
  66877. SolidParticleSystem.prototype.digest = function (mesh, options) {
  66878. var size = (options && options.facetNb) || 1;
  66879. var number = (options && options.number) || 0;
  66880. var delta = (options && options.delta) || 0;
  66881. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  66882. var meshInd = mesh.getIndices();
  66883. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  66884. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  66885. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  66886. var f = 0; // facet counter
  66887. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  66888. // compute size from number
  66889. if (number) {
  66890. number = (number > totalFacets) ? totalFacets : number;
  66891. size = Math.round(totalFacets / number);
  66892. delta = 0;
  66893. }
  66894. else {
  66895. size = (size > totalFacets) ? totalFacets : size;
  66896. }
  66897. var facetPos = []; // submesh positions
  66898. var facetInd = []; // submesh indices
  66899. var facetUV = []; // submesh UV
  66900. var facetCol = []; // submesh colors
  66901. var barycenter = BABYLON.Vector3.Zero();
  66902. var sizeO = size;
  66903. while (f < totalFacets) {
  66904. size = sizeO + Math.floor((1 + delta) * Math.random());
  66905. if (f > totalFacets - size) {
  66906. size = totalFacets - f;
  66907. }
  66908. // reset temp arrays
  66909. facetPos.length = 0;
  66910. facetInd.length = 0;
  66911. facetUV.length = 0;
  66912. facetCol.length = 0;
  66913. // iterate over "size" facets
  66914. var fi = 0;
  66915. for (var j = f * 3; j < (f + size) * 3; j++) {
  66916. facetInd.push(fi);
  66917. var i = meshInd[j];
  66918. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  66919. if (meshUV) {
  66920. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  66921. }
  66922. if (meshCol) {
  66923. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  66924. }
  66925. fi++;
  66926. }
  66927. // create a model shape for each single particle
  66928. var idx = this.nbParticles;
  66929. var shape = this._posToShape(facetPos);
  66930. var shapeUV = this._uvsToShapeUV(facetUV);
  66931. // compute the barycenter of the shape
  66932. var v;
  66933. for (v = 0; v < shape.length; v++) {
  66934. barycenter.addInPlace(shape[v]);
  66935. }
  66936. barycenter.scaleInPlace(1 / shape.length);
  66937. // shift the shape from its barycenter to the origin
  66938. for (v = 0; v < shape.length; v++) {
  66939. shape[v].subtractInPlace(barycenter);
  66940. }
  66941. var bInfo;
  66942. if (this._particlesIntersect) {
  66943. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  66944. }
  66945. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  66946. // add the particle in the SPS
  66947. var currentPos = this._positions.length;
  66948. var currentInd = this._indices.length;
  66949. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  66950. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  66951. // initialize the particle position
  66952. this.particles[this.nbParticles].position.addInPlace(barycenter);
  66953. this._index += shape.length;
  66954. idx++;
  66955. this.nbParticles++;
  66956. this._shapeCounter++;
  66957. f += size;
  66958. }
  66959. return this;
  66960. };
  66961. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  66962. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  66963. var index = 0;
  66964. var idx = 0;
  66965. for (var p = 0; p < this.particles.length; p++) {
  66966. this._particle = this.particles[p];
  66967. this._shape = this._particle._model._shape;
  66968. if (this._particle.rotationQuaternion) {
  66969. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  66970. }
  66971. else {
  66972. this._yaw = this._particle.rotation.y;
  66973. this._pitch = this._particle.rotation.x;
  66974. this._roll = this._particle.rotation.z;
  66975. this._quaternionRotationYPR();
  66976. }
  66977. this._quaternionToRotationMatrix();
  66978. this._rotMatrix.invertToRef(this._invertMatrix);
  66979. for (var pt = 0; pt < this._shape.length; pt++) {
  66980. idx = index + pt * 3;
  66981. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  66982. this._fixedNormal32[idx] = this._normal.x;
  66983. this._fixedNormal32[idx + 1] = this._normal.y;
  66984. this._fixedNormal32[idx + 2] = this._normal.z;
  66985. }
  66986. index = idx + 3;
  66987. }
  66988. };
  66989. //reset copy
  66990. SolidParticleSystem.prototype._resetCopy = function () {
  66991. this._copy.position.x = 0;
  66992. this._copy.position.y = 0;
  66993. this._copy.position.z = 0;
  66994. this._copy.rotation.x = 0;
  66995. this._copy.rotation.y = 0;
  66996. this._copy.rotation.z = 0;
  66997. this._copy.rotationQuaternion = null;
  66998. this._copy.scaling.x = 1.0;
  66999. this._copy.scaling.y = 1.0;
  67000. this._copy.scaling.z = 1.0;
  67001. this._copy.uvs.x = 0;
  67002. this._copy.uvs.y = 0;
  67003. this._copy.uvs.z = 1.0;
  67004. this._copy.uvs.w = 1.0;
  67005. this._copy.color = null;
  67006. this._copy.translateFromPivot = false;
  67007. };
  67008. // _meshBuilder : inserts the shape model in the global SPS mesh
  67009. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  67010. var i;
  67011. var u = 0;
  67012. var c = 0;
  67013. var n = 0;
  67014. this._resetCopy();
  67015. if (options && options.positionFunction) { // call to custom positionFunction
  67016. options.positionFunction(this._copy, idx, idxInShape);
  67017. this._mustUnrotateFixedNormals = true;
  67018. }
  67019. if (this._copy.rotationQuaternion) {
  67020. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  67021. }
  67022. else {
  67023. this._yaw = this._copy.rotation.y;
  67024. this._pitch = this._copy.rotation.x;
  67025. this._roll = this._copy.rotation.z;
  67026. this._quaternionRotationYPR();
  67027. }
  67028. this._quaternionToRotationMatrix();
  67029. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  67030. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  67031. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  67032. if (this._copy.translateFromPivot) {
  67033. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  67034. }
  67035. else {
  67036. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  67037. }
  67038. for (i = 0; i < shape.length; i++) {
  67039. this._vertex.x = shape[i].x;
  67040. this._vertex.y = shape[i].y;
  67041. this._vertex.z = shape[i].z;
  67042. if (options && options.vertexFunction) {
  67043. options.vertexFunction(this._copy, this._vertex, i);
  67044. }
  67045. this._vertex.x *= this._copy.scaling.x;
  67046. this._vertex.y *= this._copy.scaling.y;
  67047. this._vertex.z *= this._copy.scaling.z;
  67048. this._vertex.x -= this._scaledPivot.x;
  67049. this._vertex.y -= this._scaledPivot.y;
  67050. this._vertex.z -= this._scaledPivot.z;
  67051. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  67052. this._rotated.addInPlace(this._pivotBackTranslation);
  67053. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  67054. if (meshUV) {
  67055. uvs.push((this._copy.uvs.z - this._copy.uvs.x) * meshUV[u] + this._copy.uvs.x, (this._copy.uvs.w - this._copy.uvs.y) * meshUV[u + 1] + this._copy.uvs.y);
  67056. u += 2;
  67057. }
  67058. if (this._copy.color) {
  67059. this._color = this._copy.color;
  67060. }
  67061. else if (meshCol && meshCol[c] !== undefined) {
  67062. this._color.r = meshCol[c];
  67063. this._color.g = meshCol[c + 1];
  67064. this._color.b = meshCol[c + 2];
  67065. this._color.a = meshCol[c + 3];
  67066. }
  67067. else {
  67068. this._color.r = 1.0;
  67069. this._color.g = 1.0;
  67070. this._color.b = 1.0;
  67071. this._color.a = 1.0;
  67072. }
  67073. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  67074. c += 4;
  67075. if (!this.recomputeNormals && meshNor) {
  67076. this._normal.x = meshNor[n];
  67077. this._normal.y = meshNor[n + 1];
  67078. this._normal.z = meshNor[n + 2];
  67079. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  67080. normals.push(this._normal.x, this._normal.y, this._normal.z);
  67081. n += 3;
  67082. }
  67083. }
  67084. for (i = 0; i < meshInd.length; i++) {
  67085. var current_ind = p + meshInd[i];
  67086. indices.push(current_ind);
  67087. if (current_ind > 65535) {
  67088. this._needs32Bits = true;
  67089. }
  67090. }
  67091. if (this._pickable) {
  67092. var nbfaces = meshInd.length / 3;
  67093. for (i = 0; i < nbfaces; i++) {
  67094. this.pickedParticles.push({ idx: idx, faceId: i });
  67095. }
  67096. }
  67097. if (this._depthSort) {
  67098. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  67099. }
  67100. return this._copy;
  67101. };
  67102. // returns a shape array from positions array
  67103. SolidParticleSystem.prototype._posToShape = function (positions) {
  67104. var shape = [];
  67105. for (var i = 0; i < positions.length; i += 3) {
  67106. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  67107. }
  67108. return shape;
  67109. };
  67110. // returns a shapeUV array from a Vector4 uvs
  67111. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  67112. var shapeUV = [];
  67113. if (uvs) {
  67114. for (var i = 0; i < uvs.length; i++) {
  67115. shapeUV.push(uvs[i]);
  67116. }
  67117. }
  67118. return shapeUV;
  67119. };
  67120. // adds a new particle object in the particles array
  67121. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  67122. if (bInfo === void 0) { bInfo = null; }
  67123. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  67124. this.particles.push(sp);
  67125. return sp;
  67126. };
  67127. /**
  67128. * Adds some particles to the SPS from the model shape. Returns the shape id.
  67129. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  67130. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  67131. * @param nb (positive integer) the number of particles to be created from this model
  67132. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  67133. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  67134. * @returns the number of shapes in the system
  67135. */
  67136. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  67137. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  67138. var meshInd = mesh.getIndices();
  67139. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  67140. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  67141. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  67142. var bbInfo;
  67143. if (this._particlesIntersect) {
  67144. bbInfo = mesh.getBoundingInfo();
  67145. }
  67146. var shape = this._posToShape(meshPos);
  67147. var shapeUV = this._uvsToShapeUV(meshUV);
  67148. var posfunc = options ? options.positionFunction : null;
  67149. var vtxfunc = options ? options.vertexFunction : null;
  67150. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  67151. // particles
  67152. var sp;
  67153. var currentCopy;
  67154. var idx = this.nbParticles;
  67155. for (var i = 0; i < nb; i++) {
  67156. var currentPos = this._positions.length;
  67157. var currentInd = this._indices.length;
  67158. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  67159. if (this._updatable) {
  67160. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  67161. sp.position.copyFrom(currentCopy.position);
  67162. sp.rotation.copyFrom(currentCopy.rotation);
  67163. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  67164. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  67165. }
  67166. if (currentCopy.color && sp.color) {
  67167. sp.color.copyFrom(currentCopy.color);
  67168. }
  67169. sp.scaling.copyFrom(currentCopy.scaling);
  67170. sp.uvs.copyFrom(currentCopy.uvs);
  67171. }
  67172. this._index += shape.length;
  67173. idx++;
  67174. }
  67175. this.nbParticles += nb;
  67176. this._shapeCounter++;
  67177. return this._shapeCounter - 1;
  67178. };
  67179. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  67180. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  67181. this._resetCopy();
  67182. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  67183. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  67184. }
  67185. if (this._copy.rotationQuaternion) {
  67186. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  67187. }
  67188. else {
  67189. this._yaw = this._copy.rotation.y;
  67190. this._pitch = this._copy.rotation.x;
  67191. this._roll = this._copy.rotation.z;
  67192. this._quaternionRotationYPR();
  67193. }
  67194. this._quaternionToRotationMatrix();
  67195. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  67196. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  67197. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  67198. if (this._copy.translateFromPivot) {
  67199. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  67200. }
  67201. else {
  67202. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  67203. }
  67204. this._shape = particle._model._shape;
  67205. for (var pt = 0; pt < this._shape.length; pt++) {
  67206. this._vertex.x = this._shape[pt].x;
  67207. this._vertex.y = this._shape[pt].y;
  67208. this._vertex.z = this._shape[pt].z;
  67209. if (particle._model._vertexFunction) {
  67210. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  67211. }
  67212. this._vertex.x *= this._copy.scaling.x;
  67213. this._vertex.y *= this._copy.scaling.y;
  67214. this._vertex.z *= this._copy.scaling.z;
  67215. this._vertex.x -= this._scaledPivot.x;
  67216. this._vertex.y -= this._scaledPivot.y;
  67217. this._vertex.z -= this._scaledPivot.z;
  67218. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  67219. this._rotated.addInPlace(this._pivotBackTranslation);
  67220. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  67221. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  67222. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  67223. }
  67224. particle.position.x = 0.0;
  67225. particle.position.y = 0.0;
  67226. particle.position.z = 0.0;
  67227. particle.rotation.x = 0.0;
  67228. particle.rotation.y = 0.0;
  67229. particle.rotation.z = 0.0;
  67230. particle.rotationQuaternion = null;
  67231. particle.scaling.x = 1.0;
  67232. particle.scaling.y = 1.0;
  67233. particle.scaling.z = 1.0;
  67234. particle.uvs.x = 0.0;
  67235. particle.uvs.y = 0.0;
  67236. particle.uvs.z = 1.0;
  67237. particle.uvs.w = 1.0;
  67238. particle.pivot.x = 0.0;
  67239. particle.pivot.y = 0.0;
  67240. particle.pivot.z = 0.0;
  67241. particle.translateFromPivot = false;
  67242. particle.parentId = null;
  67243. };
  67244. /**
  67245. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  67246. * @returns the SPS.
  67247. */
  67248. SolidParticleSystem.prototype.rebuildMesh = function () {
  67249. for (var p = 0; p < this.particles.length; p++) {
  67250. this._rebuildParticle(this.particles[p]);
  67251. }
  67252. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  67253. return this;
  67254. };
  67255. /**
  67256. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  67257. * This method calls `updateParticle()` for each particle of the SPS.
  67258. * For an animated SPS, it is usually called within the render loop.
  67259. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  67260. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  67261. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  67262. * @returns the SPS.
  67263. */
  67264. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  67265. if (start === void 0) { start = 0; }
  67266. if (end === void 0) { end = this.nbParticles - 1; }
  67267. if (update === void 0) { update = true; }
  67268. if (!this._updatable) {
  67269. return this;
  67270. }
  67271. // custom beforeUpdate
  67272. this.beforeUpdateParticles(start, end, update);
  67273. this._cam_axisX.x = 1.0;
  67274. this._cam_axisX.y = 0.0;
  67275. this._cam_axisX.z = 0.0;
  67276. this._cam_axisY.x = 0.0;
  67277. this._cam_axisY.y = 1.0;
  67278. this._cam_axisY.z = 0.0;
  67279. this._cam_axisZ.x = 0.0;
  67280. this._cam_axisZ.y = 0.0;
  67281. this._cam_axisZ.z = 1.0;
  67282. // cases when the World Matrix is to be computed first
  67283. if (this.billboard || this._depthSort) {
  67284. this.mesh.computeWorldMatrix(true);
  67285. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  67286. }
  67287. // if the particles will always face the camera
  67288. if (this.billboard) {
  67289. // compute the camera position and un-rotate it by the current mesh rotation
  67290. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  67291. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  67292. this._cam_axisZ.normalize();
  67293. // same for camera up vector extracted from the cam view matrix
  67294. var view = this._camera.getViewMatrix(true);
  67295. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  67296. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  67297. this._cam_axisY.normalize();
  67298. this._cam_axisX.normalize();
  67299. }
  67300. // if depthSort, compute the camera global position in the mesh local system
  67301. if (this._depthSort) {
  67302. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  67303. }
  67304. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  67305. var idx = 0; // current position index in the global array positions32
  67306. var index = 0; // position start index in the global array positions32 of the current particle
  67307. var colidx = 0; // current color index in the global array colors32
  67308. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  67309. var uvidx = 0; // current uv index in the global array uvs32
  67310. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  67311. var pt = 0; // current index in the particle model shape
  67312. if (this.mesh.isFacetDataEnabled) {
  67313. this._computeBoundingBox = true;
  67314. }
  67315. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  67316. if (this._computeBoundingBox) {
  67317. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  67318. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  67319. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  67320. }
  67321. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  67322. if (this.mesh._boundingInfo) {
  67323. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  67324. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  67325. }
  67326. }
  67327. }
  67328. // particle loop
  67329. index = this.particles[start]._pos;
  67330. var vpos = (index / 3) | 0;
  67331. colorIndex = vpos * 4;
  67332. uvIndex = vpos * 2;
  67333. for (var p = start; p <= end; p++) {
  67334. this._particle = this.particles[p];
  67335. this._shape = this._particle._model._shape;
  67336. this._shapeUV = this._particle._model._shapeUV;
  67337. // call to custom user function to update the particle properties
  67338. this.updateParticle(this._particle);
  67339. // camera-particle distance for depth sorting
  67340. if (this._depthSort && this._depthSortParticles) {
  67341. var dsp = this.depthSortedParticles[p];
  67342. dsp.ind = this._particle._ind;
  67343. dsp.indicesLength = this._particle._model._indicesLength;
  67344. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  67345. }
  67346. // skip the computations for inactive or already invisible particles
  67347. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  67348. // increment indexes for the next particle
  67349. pt = this._shape.length;
  67350. index += pt * 3;
  67351. colorIndex += pt * 4;
  67352. uvIndex += pt * 2;
  67353. continue;
  67354. }
  67355. if (this._particle.isVisible) {
  67356. this._particle._stillInvisible = false; // un-mark permanent invisibility
  67357. this._particleHasParent = (this._particle.parentId !== null);
  67358. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  67359. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  67360. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  67361. // particle rotation matrix
  67362. if (this.billboard) {
  67363. this._particle.rotation.x = 0.0;
  67364. this._particle.rotation.y = 0.0;
  67365. }
  67366. if (this._computeParticleRotation || this.billboard) {
  67367. if (this._particle.rotationQuaternion) {
  67368. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  67369. }
  67370. else {
  67371. this._yaw = this._particle.rotation.y;
  67372. this._pitch = this._particle.rotation.x;
  67373. this._roll = this._particle.rotation.z;
  67374. this._quaternionRotationYPR();
  67375. }
  67376. this._quaternionToRotationMatrix();
  67377. }
  67378. if (this._particleHasParent) {
  67379. this._parent = this.particles[this._particle.parentId];
  67380. this._rotated.x = this._particle.position.x * this._parent._rotationMatrix[0] + this._particle.position.y * this._parent._rotationMatrix[3] + this._particle.position.z * this._parent._rotationMatrix[6];
  67381. this._rotated.y = this._particle.position.x * this._parent._rotationMatrix[1] + this._particle.position.y * this._parent._rotationMatrix[4] + this._particle.position.z * this._parent._rotationMatrix[7];
  67382. this._rotated.z = this._particle.position.x * this._parent._rotationMatrix[2] + this._particle.position.y * this._parent._rotationMatrix[5] + this._particle.position.z * this._parent._rotationMatrix[8];
  67383. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  67384. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  67385. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  67386. if (this._computeParticleRotation || this.billboard) {
  67387. this._particle._rotationMatrix[0] = this._rotMatrix.m[0] * this._parent._rotationMatrix[0] + this._rotMatrix.m[1] * this._parent._rotationMatrix[3] + this._rotMatrix.m[2] * this._parent._rotationMatrix[6];
  67388. this._particle._rotationMatrix[1] = this._rotMatrix.m[0] * this._parent._rotationMatrix[1] + this._rotMatrix.m[1] * this._parent._rotationMatrix[4] + this._rotMatrix.m[2] * this._parent._rotationMatrix[7];
  67389. this._particle._rotationMatrix[2] = this._rotMatrix.m[0] * this._parent._rotationMatrix[2] + this._rotMatrix.m[1] * this._parent._rotationMatrix[5] + this._rotMatrix.m[2] * this._parent._rotationMatrix[8];
  67390. this._particle._rotationMatrix[3] = this._rotMatrix.m[4] * this._parent._rotationMatrix[0] + this._rotMatrix.m[5] * this._parent._rotationMatrix[3] + this._rotMatrix.m[6] * this._parent._rotationMatrix[6];
  67391. this._particle._rotationMatrix[4] = this._rotMatrix.m[4] * this._parent._rotationMatrix[1] + this._rotMatrix.m[5] * this._parent._rotationMatrix[4] + this._rotMatrix.m[6] * this._parent._rotationMatrix[7];
  67392. this._particle._rotationMatrix[5] = this._rotMatrix.m[4] * this._parent._rotationMatrix[2] + this._rotMatrix.m[5] * this._parent._rotationMatrix[5] + this._rotMatrix.m[6] * this._parent._rotationMatrix[8];
  67393. this._particle._rotationMatrix[6] = this._rotMatrix.m[8] * this._parent._rotationMatrix[0] + this._rotMatrix.m[9] * this._parent._rotationMatrix[3] + this._rotMatrix.m[10] * this._parent._rotationMatrix[6];
  67394. this._particle._rotationMatrix[7] = this._rotMatrix.m[8] * this._parent._rotationMatrix[1] + this._rotMatrix.m[9] * this._parent._rotationMatrix[4] + this._rotMatrix.m[10] * this._parent._rotationMatrix[7];
  67395. this._particle._rotationMatrix[8] = this._rotMatrix.m[8] * this._parent._rotationMatrix[2] + this._rotMatrix.m[9] * this._parent._rotationMatrix[5] + this._rotMatrix.m[10] * this._parent._rotationMatrix[8];
  67396. }
  67397. }
  67398. else {
  67399. this._particle._globalPosition.x = this._particle.position.x;
  67400. this._particle._globalPosition.y = this._particle.position.y;
  67401. this._particle._globalPosition.z = this._particle.position.z;
  67402. if (this._computeParticleRotation || this.billboard) {
  67403. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  67404. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  67405. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  67406. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  67407. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  67408. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  67409. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  67410. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  67411. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  67412. }
  67413. }
  67414. if (this._particle.translateFromPivot) {
  67415. this._pivotBackTranslation.x = 0.0;
  67416. this._pivotBackTranslation.y = 0.0;
  67417. this._pivotBackTranslation.z = 0.0;
  67418. }
  67419. else {
  67420. this._pivotBackTranslation.x = this._scaledPivot.x;
  67421. this._pivotBackTranslation.y = this._scaledPivot.y;
  67422. this._pivotBackTranslation.z = this._scaledPivot.z;
  67423. }
  67424. // particle vertex loop
  67425. for (pt = 0; pt < this._shape.length; pt++) {
  67426. idx = index + pt * 3;
  67427. colidx = colorIndex + pt * 4;
  67428. uvidx = uvIndex + pt * 2;
  67429. this._vertex.x = this._shape[pt].x;
  67430. this._vertex.y = this._shape[pt].y;
  67431. this._vertex.z = this._shape[pt].z;
  67432. if (this._computeParticleVertex) {
  67433. this.updateParticleVertex(this._particle, this._vertex, pt);
  67434. }
  67435. // positions
  67436. this._vertex.x *= this._particle.scaling.x;
  67437. this._vertex.y *= this._particle.scaling.y;
  67438. this._vertex.z *= this._particle.scaling.z;
  67439. this._vertex.x -= this._scaledPivot.x;
  67440. this._vertex.y -= this._scaledPivot.y;
  67441. this._vertex.z -= this._scaledPivot.z;
  67442. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  67443. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  67444. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  67445. this._rotated.x += this._pivotBackTranslation.x;
  67446. this._rotated.y += this._pivotBackTranslation.y;
  67447. this._rotated.z += this._pivotBackTranslation.z;
  67448. this._positions32[idx] = this._particle._globalPosition.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  67449. this._positions32[idx + 1] = this._particle._globalPosition.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  67450. this._positions32[idx + 2] = this._particle._globalPosition.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  67451. if (this._computeBoundingBox) {
  67452. if (this._positions32[idx] < this._minimum.x) {
  67453. this._minimum.x = this._positions32[idx];
  67454. }
  67455. if (this._positions32[idx] > this._maximum.x) {
  67456. this._maximum.x = this._positions32[idx];
  67457. }
  67458. if (this._positions32[idx + 1] < this._minimum.y) {
  67459. this._minimum.y = this._positions32[idx + 1];
  67460. }
  67461. if (this._positions32[idx + 1] > this._maximum.y) {
  67462. this._maximum.y = this._positions32[idx + 1];
  67463. }
  67464. if (this._positions32[idx + 2] < this._minimum.z) {
  67465. this._minimum.z = this._positions32[idx + 2];
  67466. }
  67467. if (this._positions32[idx + 2] > this._maximum.z) {
  67468. this._maximum.z = this._positions32[idx + 2];
  67469. }
  67470. }
  67471. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  67472. if (!this._computeParticleVertex) {
  67473. this._normal.x = this._fixedNormal32[idx];
  67474. this._normal.y = this._fixedNormal32[idx + 1];
  67475. this._normal.z = this._fixedNormal32[idx + 2];
  67476. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  67477. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  67478. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  67479. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  67480. this._normals32[idx + 1] = this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  67481. this._normals32[idx + 2] = this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  67482. }
  67483. if (this._computeParticleColor && this._particle.color) {
  67484. this._colors32[colidx] = this._particle.color.r;
  67485. this._colors32[colidx + 1] = this._particle.color.g;
  67486. this._colors32[colidx + 2] = this._particle.color.b;
  67487. this._colors32[colidx + 3] = this._particle.color.a;
  67488. }
  67489. if (this._computeParticleTexture) {
  67490. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  67491. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  67492. }
  67493. }
  67494. }
  67495. // particle just set invisible : scaled to zero and positioned at the origin
  67496. else {
  67497. this._particle._stillInvisible = true; // mark the particle as invisible
  67498. for (pt = 0; pt < this._shape.length; pt++) {
  67499. idx = index + pt * 3;
  67500. colidx = colorIndex + pt * 4;
  67501. uvidx = uvIndex + pt * 2;
  67502. this._positions32[idx] = 0.0;
  67503. this._positions32[idx + 1] = 0.0;
  67504. this._positions32[idx + 2] = 0.0;
  67505. this._normals32[idx] = 0.0;
  67506. this._normals32[idx + 1] = 0.0;
  67507. this._normals32[idx + 2] = 0.0;
  67508. if (this._computeParticleColor && this._particle.color) {
  67509. this._colors32[colidx] = this._particle.color.r;
  67510. this._colors32[colidx + 1] = this._particle.color.g;
  67511. this._colors32[colidx + 2] = this._particle.color.b;
  67512. this._colors32[colidx + 3] = this._particle.color.a;
  67513. }
  67514. if (this._computeParticleTexture) {
  67515. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  67516. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  67517. }
  67518. }
  67519. }
  67520. // if the particle intersections must be computed : update the bbInfo
  67521. if (this._particlesIntersect) {
  67522. var bInfo = this._particle._boundingInfo;
  67523. var bBox = bInfo.boundingBox;
  67524. var bSphere = bInfo.boundingSphere;
  67525. if (!this._bSphereOnly) {
  67526. // place, scale and rotate the particle bbox within the SPS local system, then update it
  67527. for (var b = 0; b < bBox.vectors.length; b++) {
  67528. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  67529. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  67530. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  67531. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  67532. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  67533. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  67534. bBox.vectors[b].x = this._particle.position.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  67535. bBox.vectors[b].y = this._particle.position.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  67536. bBox.vectors[b].z = this._particle.position.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  67537. }
  67538. bBox._update(this.mesh._worldMatrix);
  67539. }
  67540. // place and scale the particle bouding sphere in the SPS local system, then update it
  67541. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  67542. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  67543. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  67544. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  67545. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  67546. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  67547. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  67548. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  67549. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  67550. bSphere.radius = this._bSphereRadiusFactor * 0.5 * Math.sqrt((this._maxBbox.x - this._minBbox.x) * (this._maxBbox.x - this._minBbox.x) + (this._maxBbox.y - this._minBbox.y) * (this._maxBbox.y - this._minBbox.y) + (this._maxBbox.z - this._minBbox.z) * (this._maxBbox.z - this._minBbox.z));
  67551. bSphere._update(this.mesh._worldMatrix);
  67552. }
  67553. // increment indexes for the next particle
  67554. index = idx + 3;
  67555. colorIndex = colidx + 4;
  67556. uvIndex = uvidx + 2;
  67557. }
  67558. // if the VBO must be updated
  67559. if (update) {
  67560. if (this._computeParticleColor) {
  67561. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  67562. }
  67563. if (this._computeParticleTexture) {
  67564. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  67565. }
  67566. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  67567. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  67568. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  67569. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  67570. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  67571. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  67572. for (var i = 0; i < this._normals32.length; i++) {
  67573. this._fixedNormal32[i] = this._normals32[i];
  67574. }
  67575. }
  67576. if (!this.mesh.areNormalsFrozen) {
  67577. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  67578. }
  67579. }
  67580. if (this._depthSort && this._depthSortParticles) {
  67581. this.depthSortedParticles.sort(this._depthSortFunction);
  67582. var dspl = this.depthSortedParticles.length;
  67583. var sorted = 0;
  67584. var lind = 0;
  67585. var sind = 0;
  67586. var sid = 0;
  67587. for (sorted = 0; sorted < dspl; sorted++) {
  67588. lind = this.depthSortedParticles[sorted].indicesLength;
  67589. sind = this.depthSortedParticles[sorted].ind;
  67590. for (var i = 0; i < lind; i++) {
  67591. this._indices32[sid] = this._indices[sind + i];
  67592. sid++;
  67593. }
  67594. }
  67595. this.mesh.updateIndices(this._indices32);
  67596. }
  67597. }
  67598. if (this._computeBoundingBox) {
  67599. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  67600. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  67601. }
  67602. this.afterUpdateParticles(start, end, update);
  67603. return this;
  67604. };
  67605. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  67606. this._halfroll = this._roll * 0.5;
  67607. this._halfpitch = this._pitch * 0.5;
  67608. this._halfyaw = this._yaw * 0.5;
  67609. this._sinRoll = Math.sin(this._halfroll);
  67610. this._cosRoll = Math.cos(this._halfroll);
  67611. this._sinPitch = Math.sin(this._halfpitch);
  67612. this._cosPitch = Math.cos(this._halfpitch);
  67613. this._sinYaw = Math.sin(this._halfyaw);
  67614. this._cosYaw = Math.cos(this._halfyaw);
  67615. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  67616. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  67617. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  67618. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  67619. };
  67620. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  67621. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  67622. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  67623. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  67624. this._rotMatrix.m[3] = 0;
  67625. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  67626. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  67627. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  67628. this._rotMatrix.m[7] = 0;
  67629. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  67630. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  67631. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  67632. this._rotMatrix.m[11] = 0;
  67633. this._rotMatrix.m[12] = 0;
  67634. this._rotMatrix.m[13] = 0;
  67635. this._rotMatrix.m[14] = 0;
  67636. this._rotMatrix.m[15] = 1.0;
  67637. };
  67638. /**
  67639. * Disposes the SPS.
  67640. */
  67641. SolidParticleSystem.prototype.dispose = function () {
  67642. this.mesh.dispose();
  67643. this.vars = null;
  67644. // drop references to internal big arrays for the GC
  67645. this._positions = null;
  67646. this._indices = null;
  67647. this._normals = null;
  67648. this._uvs = null;
  67649. this._colors = null;
  67650. this._indices32 = null;
  67651. this._positions32 = null;
  67652. this._normals32 = null;
  67653. this._fixedNormal32 = null;
  67654. this._uvs32 = null;
  67655. this._colors32 = null;
  67656. this.pickedParticles = null;
  67657. };
  67658. /**
  67659. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  67660. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  67661. * @returns the SPS.
  67662. */
  67663. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  67664. if (!this._isVisibilityBoxLocked) {
  67665. this.mesh.refreshBoundingInfo();
  67666. }
  67667. return this;
  67668. };
  67669. /**
  67670. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  67671. * @param size the size (float) of the visibility box
  67672. * note : this doesn't lock the SPS mesh bounding box.
  67673. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  67674. */
  67675. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  67676. var vis = size / 2;
  67677. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  67678. };
  67679. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  67680. /**
  67681. * Gets whether the SPS as always visible or not
  67682. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  67683. */
  67684. get: function () {
  67685. return this._alwaysVisible;
  67686. },
  67687. /**
  67688. * Sets the SPS as always visible or not
  67689. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  67690. */
  67691. set: function (val) {
  67692. this._alwaysVisible = val;
  67693. this.mesh.alwaysSelectAsActiveMesh = val;
  67694. },
  67695. enumerable: true,
  67696. configurable: true
  67697. });
  67698. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  67699. /**
  67700. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  67701. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  67702. */
  67703. get: function () {
  67704. return this._isVisibilityBoxLocked;
  67705. },
  67706. /**
  67707. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  67708. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  67709. */
  67710. set: function (val) {
  67711. this._isVisibilityBoxLocked = val;
  67712. var boundingInfo = this.mesh.getBoundingInfo();
  67713. boundingInfo.isLocked = val;
  67714. },
  67715. enumerable: true,
  67716. configurable: true
  67717. });
  67718. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  67719. /**
  67720. * Gets if `setParticles()` computes the particle rotations or not.
  67721. * Default value : true. The SPS is faster when it's set to false.
  67722. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  67723. */
  67724. get: function () {
  67725. return this._computeParticleRotation;
  67726. },
  67727. /**
  67728. * Tells to `setParticles()` to compute the particle rotations or not.
  67729. * Default value : true. The SPS is faster when it's set to false.
  67730. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  67731. */
  67732. set: function (val) {
  67733. this._computeParticleRotation = val;
  67734. },
  67735. enumerable: true,
  67736. configurable: true
  67737. });
  67738. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  67739. /**
  67740. * Gets if `setParticles()` computes the particle colors or not.
  67741. * Default value : true. The SPS is faster when it's set to false.
  67742. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  67743. */
  67744. get: function () {
  67745. return this._computeParticleColor;
  67746. },
  67747. /**
  67748. * Tells to `setParticles()` to compute the particle colors or not.
  67749. * Default value : true. The SPS is faster when it's set to false.
  67750. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  67751. */
  67752. set: function (val) {
  67753. this._computeParticleColor = val;
  67754. },
  67755. enumerable: true,
  67756. configurable: true
  67757. });
  67758. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  67759. /**
  67760. * Gets if `setParticles()` computes the particle textures or not.
  67761. * Default value : true. The SPS is faster when it's set to false.
  67762. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  67763. */
  67764. get: function () {
  67765. return this._computeParticleTexture;
  67766. },
  67767. set: function (val) {
  67768. this._computeParticleTexture = val;
  67769. },
  67770. enumerable: true,
  67771. configurable: true
  67772. });
  67773. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  67774. /**
  67775. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  67776. * Default value : false. The SPS is faster when it's set to false.
  67777. * Note : the particle custom vertex positions aren't stored values.
  67778. */
  67779. get: function () {
  67780. return this._computeParticleVertex;
  67781. },
  67782. /**
  67783. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  67784. * Default value : false. The SPS is faster when it's set to false.
  67785. * Note : the particle custom vertex positions aren't stored values.
  67786. */
  67787. set: function (val) {
  67788. this._computeParticleVertex = val;
  67789. },
  67790. enumerable: true,
  67791. configurable: true
  67792. });
  67793. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  67794. /**
  67795. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  67796. */
  67797. get: function () {
  67798. return this._computeBoundingBox;
  67799. },
  67800. /**
  67801. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  67802. */
  67803. set: function (val) {
  67804. this._computeBoundingBox = val;
  67805. },
  67806. enumerable: true,
  67807. configurable: true
  67808. });
  67809. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  67810. /**
  67811. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  67812. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  67813. * Default : `true`
  67814. */
  67815. get: function () {
  67816. return this._depthSortParticles;
  67817. },
  67818. /**
  67819. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  67820. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  67821. * Default : `true`
  67822. */
  67823. set: function (val) {
  67824. this._depthSortParticles = val;
  67825. },
  67826. enumerable: true,
  67827. configurable: true
  67828. });
  67829. // =======================================================================
  67830. // Particle behavior logic
  67831. // these following methods may be overwritten by the user to fit his needs
  67832. /**
  67833. * This function does nothing. It may be overwritten to set all the particle first values.
  67834. * The SPS doesn't call this function, you may have to call it by your own.
  67835. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  67836. */
  67837. SolidParticleSystem.prototype.initParticles = function () {
  67838. };
  67839. /**
  67840. * This function does nothing. It may be overwritten to recycle a particle.
  67841. * The SPS doesn't call this function, you may have to call it by your own.
  67842. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  67843. * @param particle The particle to recycle
  67844. * @returns the recycled particle
  67845. */
  67846. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  67847. return particle;
  67848. };
  67849. /**
  67850. * Updates a particle : this function should be overwritten by the user.
  67851. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  67852. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  67853. * @example : just set a particle position or velocity and recycle conditions
  67854. * @param particle The particle to update
  67855. * @returns the updated particle
  67856. */
  67857. SolidParticleSystem.prototype.updateParticle = function (particle) {
  67858. return particle;
  67859. };
  67860. /**
  67861. * Updates a vertex of a particle : it can be overwritten by the user.
  67862. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  67863. * @param particle the current particle
  67864. * @param vertex the current index of the current particle
  67865. * @param pt the index of the current vertex in the particle shape
  67866. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  67867. * @example : just set a vertex particle position
  67868. * @returns the updated vertex
  67869. */
  67870. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  67871. return vertex;
  67872. };
  67873. /**
  67874. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  67875. * This does nothing and may be overwritten by the user.
  67876. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  67877. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  67878. * @param update the boolean update value actually passed to setParticles()
  67879. */
  67880. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  67881. };
  67882. /**
  67883. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  67884. * This will be passed three parameters.
  67885. * This does nothing and may be overwritten by the user.
  67886. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  67887. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  67888. * @param update the boolean update value actually passed to setParticles()
  67889. */
  67890. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  67891. };
  67892. return SolidParticleSystem;
  67893. }());
  67894. BABYLON.SolidParticleSystem = SolidParticleSystem;
  67895. })(BABYLON || (BABYLON = {}));
  67896. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  67897. var BABYLON;
  67898. (function (BABYLON) {
  67899. /**
  67900. * Class containing static functions to help procedurally build meshes
  67901. */
  67902. var MeshBuilder = /** @class */ (function () {
  67903. function MeshBuilder() {
  67904. }
  67905. MeshBuilder.updateSideOrientation = function (orientation) {
  67906. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  67907. return BABYLON.Mesh.DOUBLESIDE;
  67908. }
  67909. if (orientation === undefined || orientation === null) {
  67910. return BABYLON.Mesh.FRONTSIDE;
  67911. }
  67912. return orientation;
  67913. };
  67914. /**
  67915. * Creates a box mesh
  67916. * * The parameter `size` sets the size (float) of each box side (default 1)
  67917. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value of `size`)
  67918. * * 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)
  67919. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  67920. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67921. * * 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
  67922. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67923. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  67924. * @param name defines the name of the mesh
  67925. * @param options defines the options used to create the mesh
  67926. * @param scene defines the hosting scene
  67927. * @returns the box mesh
  67928. */
  67929. MeshBuilder.CreateBox = function (name, options, scene) {
  67930. if (scene === void 0) { scene = null; }
  67931. var box = new BABYLON.Mesh(name, scene);
  67932. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67933. box._originalBuilderSideOrientation = options.sideOrientation;
  67934. var vertexData = BABYLON.VertexData.CreateBox(options);
  67935. vertexData.applyToMesh(box, options.updatable);
  67936. return box;
  67937. };
  67938. /**
  67939. * Creates a sphere mesh
  67940. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  67941. * * 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`)
  67942. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  67943. * * 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
  67944. * * 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)
  67945. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67946. * * 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
  67947. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67948. * @param name defines the name of the mesh
  67949. * @param options defines the options used to create the mesh
  67950. * @param scene defines the hosting scene
  67951. * @returns the sphere mesh
  67952. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  67953. */
  67954. MeshBuilder.CreateSphere = function (name, options, scene) {
  67955. var sphere = new BABYLON.Mesh(name, scene);
  67956. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67957. sphere._originalBuilderSideOrientation = options.sideOrientation;
  67958. var vertexData = BABYLON.VertexData.CreateSphere(options);
  67959. vertexData.applyToMesh(sphere, options.updatable);
  67960. return sphere;
  67961. };
  67962. /**
  67963. * Creates a plane polygonal mesh. By default, this is a disc
  67964. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  67965. * * 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
  67966. * * 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
  67967. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67968. * * 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
  67969. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67970. * @param name defines the name of the mesh
  67971. * @param options defines the options used to create the mesh
  67972. * @param scene defines the hosting scene
  67973. * @returns the plane polygonal mesh
  67974. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  67975. */
  67976. MeshBuilder.CreateDisc = function (name, options, scene) {
  67977. if (scene === void 0) { scene = null; }
  67978. var disc = new BABYLON.Mesh(name, scene);
  67979. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67980. disc._originalBuilderSideOrientation = options.sideOrientation;
  67981. var vertexData = BABYLON.VertexData.CreateDisc(options);
  67982. vertexData.applyToMesh(disc, options.updatable);
  67983. return disc;
  67984. };
  67985. /**
  67986. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  67987. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  67988. * * 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`)
  67989. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  67990. * * 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
  67991. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67992. * * 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
  67993. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67994. * @param name defines the name of the mesh
  67995. * @param options defines the options used to create the mesh
  67996. * @param scene defines the hosting scene
  67997. * @returns the icosahedron mesh
  67998. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  67999. */
  68000. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  68001. var sphere = new BABYLON.Mesh(name, scene);
  68002. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68003. sphere._originalBuilderSideOrientation = options.sideOrientation;
  68004. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  68005. vertexData.applyToMesh(sphere, options.updatable);
  68006. return sphere;
  68007. };
  68008. /**
  68009. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  68010. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  68011. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  68012. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  68013. * * 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
  68014. * * 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
  68015. * * 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
  68016. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68017. * * 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
  68018. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  68019. * * 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
  68020. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  68021. * * 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
  68022. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  68023. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68024. * @param name defines the name of the mesh
  68025. * @param options defines the options used to create the mesh
  68026. * @param scene defines the hosting scene
  68027. * @returns the ribbon mesh
  68028. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  68029. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  68030. */
  68031. MeshBuilder.CreateRibbon = function (name, options, scene) {
  68032. if (scene === void 0) { scene = null; }
  68033. var pathArray = options.pathArray;
  68034. var closeArray = options.closeArray;
  68035. var closePath = options.closePath;
  68036. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68037. var instance = options.instance;
  68038. var updatable = options.updatable;
  68039. if (instance) { // existing ribbon instance update
  68040. // positionFunction : ribbon case
  68041. // only pathArray and sideOrientation parameters are taken into account for positions update
  68042. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  68043. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  68044. var positionFunction = function (positions) {
  68045. var minlg = pathArray[0].length;
  68046. var mesh = instance;
  68047. var i = 0;
  68048. var ns = (mesh._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  68049. for (var si = 1; si <= ns; si++) {
  68050. for (var p = 0; p < pathArray.length; p++) {
  68051. var path = pathArray[p];
  68052. var l = path.length;
  68053. minlg = (minlg < l) ? minlg : l;
  68054. var j = 0;
  68055. while (j < minlg) {
  68056. positions[i] = path[j].x;
  68057. positions[i + 1] = path[j].y;
  68058. positions[i + 2] = path[j].z;
  68059. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  68060. BABYLON.Tmp.Vector3[0].x = path[j].x;
  68061. }
  68062. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  68063. BABYLON.Tmp.Vector3[1].x = path[j].x;
  68064. }
  68065. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  68066. BABYLON.Tmp.Vector3[0].y = path[j].y;
  68067. }
  68068. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  68069. BABYLON.Tmp.Vector3[1].y = path[j].y;
  68070. }
  68071. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  68072. BABYLON.Tmp.Vector3[0].z = path[j].z;
  68073. }
  68074. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  68075. BABYLON.Tmp.Vector3[1].z = path[j].z;
  68076. }
  68077. j++;
  68078. i += 3;
  68079. }
  68080. if (mesh._creationDataStorage && mesh._creationDataStorage.closePath) {
  68081. positions[i] = path[0].x;
  68082. positions[i + 1] = path[0].y;
  68083. positions[i + 2] = path[0].z;
  68084. i += 3;
  68085. }
  68086. }
  68087. }
  68088. };
  68089. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  68090. positionFunction(positions);
  68091. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[2], BABYLON.Tmp.Vector3[3]);
  68092. instance._boundingInfo.update(instance._worldMatrix);
  68093. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  68094. if (options.colors) {
  68095. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  68096. for (var c = 0; c < options.colors.length; c++) {
  68097. colors[c * 4] = options.colors[c].r;
  68098. colors[c * 4 + 1] = options.colors[c].g;
  68099. colors[c * 4 + 2] = options.colors[c].b;
  68100. colors[c * 4 + 3] = options.colors[c].a;
  68101. }
  68102. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  68103. }
  68104. if (options.uvs) {
  68105. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  68106. for (var i = 0; i < options.uvs.length; i++) {
  68107. uvs[i * 2] = options.uvs[i].x;
  68108. uvs[i * 2 + 1] = options.uvs[i].y;
  68109. }
  68110. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  68111. }
  68112. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  68113. var indices = instance.getIndices();
  68114. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  68115. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  68116. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  68117. if (instance._creationDataStorage && instance._creationDataStorage.closePath) {
  68118. var indexFirst = 0;
  68119. var indexLast = 0;
  68120. for (var p = 0; p < pathArray.length; p++) {
  68121. indexFirst = instance._creationDataStorage.idx[p] * 3;
  68122. if (p + 1 < pathArray.length) {
  68123. indexLast = (instance._creationDataStorage.idx[p + 1] - 1) * 3;
  68124. }
  68125. else {
  68126. indexLast = normals.length - 3;
  68127. }
  68128. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  68129. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  68130. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  68131. normals[indexLast] = normals[indexFirst];
  68132. normals[indexLast + 1] = normals[indexFirst + 1];
  68133. normals[indexLast + 2] = normals[indexFirst + 2];
  68134. }
  68135. }
  68136. if (!(instance.areNormalsFrozen)) {
  68137. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  68138. }
  68139. }
  68140. return instance;
  68141. }
  68142. else { // new ribbon creation
  68143. var ribbon = new BABYLON.Mesh(name, scene);
  68144. ribbon._originalBuilderSideOrientation = sideOrientation;
  68145. ribbon._creationDataStorage = new BABYLON._CreationDataStorage();
  68146. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  68147. if (closePath) {
  68148. ribbon._creationDataStorage.idx = vertexData._idx;
  68149. }
  68150. ribbon._creationDataStorage.closePath = closePath;
  68151. ribbon._creationDataStorage.closeArray = closeArray;
  68152. vertexData.applyToMesh(ribbon, updatable);
  68153. return ribbon;
  68154. }
  68155. };
  68156. /**
  68157. * Creates a cylinder or a cone mesh
  68158. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  68159. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  68160. * * 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.
  68161. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  68162. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  68163. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  68164. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  68165. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  68166. * * 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).
  68167. * * 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
  68168. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  68169. * * 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
  68170. * * 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.
  68171. * * If `enclose` is false, a ring surface is one element.
  68172. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  68173. * * 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
  68174. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68175. * * 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
  68176. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  68177. * @param name defines the name of the mesh
  68178. * @param options defines the options used to create the mesh
  68179. * @param scene defines the hosting scene
  68180. * @returns the cylinder mesh
  68181. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  68182. */
  68183. MeshBuilder.CreateCylinder = function (name, options, scene) {
  68184. var cylinder = new BABYLON.Mesh(name, scene);
  68185. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68186. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  68187. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  68188. vertexData.applyToMesh(cylinder, options.updatable);
  68189. return cylinder;
  68190. };
  68191. /**
  68192. * Creates a torus mesh
  68193. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  68194. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  68195. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  68196. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68197. * * 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
  68198. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  68199. * @param name defines the name of the mesh
  68200. * @param options defines the options used to create the mesh
  68201. * @param scene defines the hosting scene
  68202. * @returns the torus mesh
  68203. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  68204. */
  68205. MeshBuilder.CreateTorus = function (name, options, scene) {
  68206. var torus = new BABYLON.Mesh(name, scene);
  68207. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68208. torus._originalBuilderSideOrientation = options.sideOrientation;
  68209. var vertexData = BABYLON.VertexData.CreateTorus(options);
  68210. vertexData.applyToMesh(torus, options.updatable);
  68211. return torus;
  68212. };
  68213. /**
  68214. * Creates a torus knot mesh
  68215. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  68216. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  68217. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  68218. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  68219. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68220. * * 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
  68221. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  68222. * @param name defines the name of the mesh
  68223. * @param options defines the options used to create the mesh
  68224. * @param scene defines the hosting scene
  68225. * @returns the torus knot mesh
  68226. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  68227. */
  68228. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  68229. var torusKnot = new BABYLON.Mesh(name, scene);
  68230. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68231. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  68232. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  68233. vertexData.applyToMesh(torusKnot, options.updatable);
  68234. return torusKnot;
  68235. };
  68236. /**
  68237. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  68238. * * 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
  68239. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  68240. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  68241. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  68242. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  68243. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  68244. * * 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
  68245. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  68246. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68247. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  68248. * @param name defines the name of the new line system
  68249. * @param options defines the options used to create the line system
  68250. * @param scene defines the hosting scene
  68251. * @returns a new line system mesh
  68252. */
  68253. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  68254. var instance = options.instance;
  68255. var lines = options.lines;
  68256. var colors = options.colors;
  68257. if (instance) { // lines update
  68258. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  68259. var vertexColor;
  68260. var lineColors;
  68261. if (colors) {
  68262. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  68263. }
  68264. var i = 0;
  68265. var c = 0;
  68266. for (var l = 0; l < lines.length; l++) {
  68267. var points = lines[l];
  68268. for (var p = 0; p < points.length; p++) {
  68269. positions[i] = points[p].x;
  68270. positions[i + 1] = points[p].y;
  68271. positions[i + 2] = points[p].z;
  68272. if (colors && vertexColor) {
  68273. lineColors = colors[l];
  68274. vertexColor[c] = lineColors[p].r;
  68275. vertexColor[c + 1] = lineColors[p].g;
  68276. vertexColor[c + 2] = lineColors[p].b;
  68277. vertexColor[c + 3] = lineColors[p].a;
  68278. c += 4;
  68279. }
  68280. i += 3;
  68281. }
  68282. }
  68283. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  68284. if (colors && vertexColor) {
  68285. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  68286. }
  68287. return instance;
  68288. }
  68289. // line system creation
  68290. var useVertexColor = (colors) ? true : false;
  68291. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  68292. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  68293. vertexData.applyToMesh(lineSystem, options.updatable);
  68294. return lineSystem;
  68295. };
  68296. /**
  68297. * Creates a line mesh
  68298. * 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
  68299. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  68300. * * The parameter `points` is an array successive Vector3
  68301. * * 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
  68302. * * The optional parameter `colors` is an array of successive Color4, one per line point
  68303. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  68304. * * When updating an instance, remember that only point positions can change, not the number of points
  68305. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68306. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  68307. * @param name defines the name of the new line system
  68308. * @param options defines the options used to create the line system
  68309. * @param scene defines the hosting scene
  68310. * @returns a new line mesh
  68311. */
  68312. MeshBuilder.CreateLines = function (name, options, scene) {
  68313. if (scene === void 0) { scene = null; }
  68314. var colors = (options.colors) ? [options.colors] : null;
  68315. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  68316. return lines;
  68317. };
  68318. /**
  68319. * Creates a dashed line mesh
  68320. * * 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
  68321. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  68322. * * The parameter `points` is an array successive Vector3
  68323. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  68324. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  68325. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  68326. * * 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
  68327. * * When updating an instance, remember that only point positions can change, not the number of points
  68328. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68329. * @param name defines the name of the mesh
  68330. * @param options defines the options used to create the mesh
  68331. * @param scene defines the hosting scene
  68332. * @returns the dashed line mesh
  68333. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  68334. */
  68335. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  68336. if (scene === void 0) { scene = null; }
  68337. var points = options.points;
  68338. var instance = options.instance;
  68339. var gapSize = options.gapSize || 1;
  68340. var dashSize = options.dashSize || 3;
  68341. if (instance) { // dashed lines update
  68342. var positionFunction = function (positions) {
  68343. var curvect = BABYLON.Vector3.Zero();
  68344. var nbSeg = positions.length / 6;
  68345. var lg = 0;
  68346. var nb = 0;
  68347. var shft = 0;
  68348. var dashshft = 0;
  68349. var curshft = 0;
  68350. var p = 0;
  68351. var i = 0;
  68352. var j = 0;
  68353. for (i = 0; i < points.length - 1; i++) {
  68354. points[i + 1].subtractToRef(points[i], curvect);
  68355. lg += curvect.length();
  68356. }
  68357. shft = lg / nbSeg;
  68358. var dashSize = instance._creationDataStorage.dashSize;
  68359. var gapSize = instance._creationDataStorage.gapSize;
  68360. dashshft = dashSize * shft / (dashSize + gapSize);
  68361. for (i = 0; i < points.length - 1; i++) {
  68362. points[i + 1].subtractToRef(points[i], curvect);
  68363. nb = Math.floor(curvect.length() / shft);
  68364. curvect.normalize();
  68365. j = 0;
  68366. while (j < nb && p < positions.length) {
  68367. curshft = shft * j;
  68368. positions[p] = points[i].x + curshft * curvect.x;
  68369. positions[p + 1] = points[i].y + curshft * curvect.y;
  68370. positions[p + 2] = points[i].z + curshft * curvect.z;
  68371. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  68372. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  68373. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  68374. p += 6;
  68375. j++;
  68376. }
  68377. }
  68378. while (p < positions.length) {
  68379. positions[p] = points[i].x;
  68380. positions[p + 1] = points[i].y;
  68381. positions[p + 2] = points[i].z;
  68382. p += 3;
  68383. }
  68384. };
  68385. instance.updateMeshPositions(positionFunction, false);
  68386. return instance;
  68387. }
  68388. // dashed lines creation
  68389. var dashedLines = new BABYLON.LinesMesh(name, scene);
  68390. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  68391. vertexData.applyToMesh(dashedLines, options.updatable);
  68392. dashedLines._creationDataStorage = new BABYLON._CreationDataStorage();
  68393. dashedLines._creationDataStorage.dashSize = dashSize;
  68394. dashedLines._creationDataStorage.gapSize = gapSize;
  68395. return dashedLines;
  68396. };
  68397. /**
  68398. * 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.
  68399. * * 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.
  68400. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  68401. * * 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.
  68402. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  68403. * * 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
  68404. * * 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
  68405. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  68406. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68407. * * 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
  68408. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  68409. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  68410. * @param name defines the name of the mesh
  68411. * @param options defines the options used to create the mesh
  68412. * @param scene defines the hosting scene
  68413. * @returns the extruded shape mesh
  68414. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  68415. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  68416. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  68417. */
  68418. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  68419. if (scene === void 0) { scene = null; }
  68420. var path = options.path;
  68421. var shape = options.shape;
  68422. var scale = options.scale || 1;
  68423. var rotation = options.rotation || 0;
  68424. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  68425. var updatable = options.updatable;
  68426. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68427. var instance = options.instance || null;
  68428. var invertUV = options.invertUV || false;
  68429. 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);
  68430. };
  68431. /**
  68432. * Creates an custom extruded shape mesh.
  68433. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  68434. * * 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.
  68435. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  68436. * * 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
  68437. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  68438. * * 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
  68439. * * It must returns a float value that will be the scale value applied to the shape on each path point
  68440. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  68441. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  68442. * * 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
  68443. * * 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
  68444. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  68445. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68446. * * 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
  68447. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  68448. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68449. * @param name defines the name of the mesh
  68450. * @param options defines the options used to create the mesh
  68451. * @param scene defines the hosting scene
  68452. * @returns the custom extruded shape mesh
  68453. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  68454. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  68455. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  68456. */
  68457. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  68458. var path = options.path;
  68459. var shape = options.shape;
  68460. var scaleFunction = options.scaleFunction || (function () { return 1; });
  68461. var rotationFunction = options.rotationFunction || (function () { return 0; });
  68462. var ribbonCloseArray = options.ribbonCloseArray || false;
  68463. var ribbonClosePath = options.ribbonClosePath || false;
  68464. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  68465. var updatable = options.updatable;
  68466. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68467. var instance = options.instance;
  68468. var invertUV = options.invertUV || false;
  68469. 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);
  68470. };
  68471. /**
  68472. * Creates lathe mesh.
  68473. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  68474. * * 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
  68475. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  68476. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  68477. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  68478. * * 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
  68479. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  68480. * * 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
  68481. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68482. * * 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
  68483. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  68484. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68485. * @param name defines the name of the mesh
  68486. * @param options defines the options used to create the mesh
  68487. * @param scene defines the hosting scene
  68488. * @returns the lathe mesh
  68489. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  68490. */
  68491. MeshBuilder.CreateLathe = function (name, options, scene) {
  68492. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  68493. var closed = (options.closed === undefined) ? true : options.closed;
  68494. var shape = options.shape;
  68495. var radius = options.radius || 1;
  68496. var tessellation = options.tessellation || 64;
  68497. var clip = options.clip || 0;
  68498. var updatable = options.updatable;
  68499. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68500. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  68501. var pi2 = Math.PI * 2;
  68502. var paths = new Array();
  68503. var invertUV = options.invertUV || false;
  68504. var i = 0;
  68505. var p = 0;
  68506. var step = pi2 / tessellation * arc;
  68507. var rotated;
  68508. var path = new Array();
  68509. for (i = 0; i <= tessellation - clip; i++) {
  68510. var path = [];
  68511. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  68512. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  68513. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  68514. }
  68515. for (p = 0; p < shape.length; p++) {
  68516. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  68517. path.push(rotated);
  68518. }
  68519. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  68520. 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));
  68521. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  68522. }
  68523. paths.push(path);
  68524. }
  68525. // lathe ribbon
  68526. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  68527. return lathe;
  68528. };
  68529. /**
  68530. * Creates a plane mesh
  68531. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  68532. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value of `size`)
  68533. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  68534. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68535. * * 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
  68536. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68537. * @param name defines the name of the mesh
  68538. * @param options defines the options used to create the mesh
  68539. * @param scene defines the hosting scene
  68540. * @returns the plane mesh
  68541. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  68542. */
  68543. MeshBuilder.CreatePlane = function (name, options, scene) {
  68544. var plane = new BABYLON.Mesh(name, scene);
  68545. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68546. plane._originalBuilderSideOrientation = options.sideOrientation;
  68547. var vertexData = BABYLON.VertexData.CreatePlane(options);
  68548. vertexData.applyToMesh(plane, options.updatable);
  68549. if (options.sourcePlane) {
  68550. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  68551. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  68552. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  68553. if (vectorProduct.lengthSquared() > BABYLON.Epsilon) {
  68554. plane.rotate(vectorProduct, product);
  68555. }
  68556. }
  68557. return plane;
  68558. };
  68559. /**
  68560. * Creates a ground mesh
  68561. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  68562. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  68563. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68564. * @param name defines the name of the mesh
  68565. * @param options defines the options used to create the mesh
  68566. * @param scene defines the hosting scene
  68567. * @returns the ground mesh
  68568. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  68569. */
  68570. MeshBuilder.CreateGround = function (name, options, scene) {
  68571. var ground = new BABYLON.GroundMesh(name, scene);
  68572. ground._setReady(false);
  68573. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  68574. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  68575. ground._width = options.width || 1;
  68576. ground._height = options.height || 1;
  68577. ground._maxX = ground._width / 2;
  68578. ground._maxZ = ground._height / 2;
  68579. ground._minX = -ground._maxX;
  68580. ground._minZ = -ground._maxZ;
  68581. var vertexData = BABYLON.VertexData.CreateGround(options);
  68582. vertexData.applyToMesh(ground, options.updatable);
  68583. ground._setReady(true);
  68584. return ground;
  68585. };
  68586. /**
  68587. * Creates a tiled ground mesh
  68588. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  68589. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  68590. * * 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
  68591. * * 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
  68592. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  68593. * @param name defines the name of the mesh
  68594. * @param options defines the options used to create the mesh
  68595. * @param scene defines the hosting scene
  68596. * @returns the tiled ground mesh
  68597. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  68598. */
  68599. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  68600. var tiledGround = new BABYLON.Mesh(name, scene);
  68601. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  68602. vertexData.applyToMesh(tiledGround, options.updatable);
  68603. return tiledGround;
  68604. };
  68605. /**
  68606. * Creates a ground mesh from a height map
  68607. * * The parameter `url` sets the URL of the height map image resource.
  68608. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  68609. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  68610. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  68611. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  68612. * * 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.
  68613. * * 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).
  68614. * * The parameter `alphaFilter` will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  68615. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  68616. * @param name defines the name of the mesh
  68617. * @param url defines the url to the height map
  68618. * @param options defines the options used to create the mesh
  68619. * @param scene defines the hosting scene
  68620. * @returns the ground mesh
  68621. * @see http://doc.babylonjs.com/babylon101/height_map
  68622. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  68623. */
  68624. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  68625. var width = options.width || 10.0;
  68626. var height = options.height || 10.0;
  68627. var subdivisions = options.subdivisions || 1 | 0;
  68628. var minHeight = options.minHeight || 0.0;
  68629. var maxHeight = options.maxHeight || 1.0;
  68630. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  68631. var alphaFilter = options.alphaFilter || 0.0;
  68632. var updatable = options.updatable;
  68633. var onReady = options.onReady;
  68634. var ground = new BABYLON.GroundMesh(name, scene);
  68635. ground._subdivisionsX = subdivisions;
  68636. ground._subdivisionsY = subdivisions;
  68637. ground._width = width;
  68638. ground._height = height;
  68639. ground._maxX = ground._width / 2.0;
  68640. ground._maxZ = ground._height / 2.0;
  68641. ground._minX = -ground._maxX;
  68642. ground._minZ = -ground._maxZ;
  68643. ground._setReady(false);
  68644. var onload = function (img) {
  68645. // Getting height map data
  68646. var canvas = document.createElement("canvas");
  68647. var context = canvas.getContext("2d");
  68648. if (!context) {
  68649. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  68650. }
  68651. if (scene.isDisposed) {
  68652. return;
  68653. }
  68654. var bufferWidth = img.width;
  68655. var bufferHeight = img.height;
  68656. canvas.width = bufferWidth;
  68657. canvas.height = bufferHeight;
  68658. context.drawImage(img, 0, 0);
  68659. // Create VertexData from map data
  68660. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  68661. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  68662. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  68663. width: width, height: height,
  68664. subdivisions: subdivisions,
  68665. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  68666. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight,
  68667. alphaFilter: alphaFilter
  68668. });
  68669. vertexData.applyToMesh(ground, updatable);
  68670. //execute ready callback, if set
  68671. if (onReady) {
  68672. onReady(ground);
  68673. }
  68674. ground._setReady(true);
  68675. };
  68676. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  68677. return ground;
  68678. };
  68679. /**
  68680. * Creates a polygon mesh
  68681. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  68682. * * 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
  68683. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68684. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68685. * * 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)
  68686. * * Remember you can only change the shape positions, not their number when updating a polygon
  68687. * @param name defines the name of the mesh
  68688. * @param options defines the options used to create the mesh
  68689. * @param scene defines the hosting scene
  68690. * @returns the polygon mesh
  68691. */
  68692. MeshBuilder.CreatePolygon = function (name, options, scene) {
  68693. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68694. var shape = options.shape;
  68695. var holes = options.holes || [];
  68696. var depth = options.depth || 0;
  68697. var contours = [];
  68698. var hole = [];
  68699. for (var i = 0; i < shape.length; i++) {
  68700. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  68701. }
  68702. var epsilon = 0.00000001;
  68703. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  68704. contours.pop();
  68705. }
  68706. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  68707. for (var hNb = 0; hNb < holes.length; hNb++) {
  68708. hole = [];
  68709. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  68710. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  68711. }
  68712. polygonTriangulation.addHole(hole);
  68713. }
  68714. var polygon = polygonTriangulation.build(options.updatable, depth);
  68715. polygon._originalBuilderSideOrientation = options.sideOrientation;
  68716. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  68717. vertexData.applyToMesh(polygon, options.updatable);
  68718. return polygon;
  68719. };
  68720. /**
  68721. * Creates an extruded polygon mesh, with depth in the Y direction.
  68722. * * 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)
  68723. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  68724. * @param name defines the name of the mesh
  68725. * @param options defines the options used to create the mesh
  68726. * @param scene defines the hosting scene
  68727. * @returns the polygon mesh
  68728. */
  68729. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  68730. return MeshBuilder.CreatePolygon(name, options, scene);
  68731. };
  68732. /**
  68733. * Creates a tube mesh.
  68734. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  68735. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  68736. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  68737. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  68738. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  68739. * * 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)
  68740. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  68741. * * 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
  68742. * * 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
  68743. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68744. * * 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
  68745. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  68746. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68747. * @param name defines the name of the mesh
  68748. * @param options defines the options used to create the mesh
  68749. * @param scene defines the hosting scene
  68750. * @returns the tube mesh
  68751. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  68752. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  68753. */
  68754. MeshBuilder.CreateTube = function (name, options, scene) {
  68755. var path = options.path;
  68756. var instance = options.instance;
  68757. var radius = 1.0;
  68758. if (options.radius !== undefined) {
  68759. radius = options.radius;
  68760. }
  68761. else if (instance) {
  68762. radius = instance._creationDataStorage.radius;
  68763. }
  68764. var tessellation = options.tessellation || 64 | 0;
  68765. var radiusFunction = options.radiusFunction || null;
  68766. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  68767. var invertUV = options.invertUV || false;
  68768. var updatable = options.updatable;
  68769. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68770. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  68771. // tube geometry
  68772. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  68773. var tangents = path3D.getTangents();
  68774. var normals = path3D.getNormals();
  68775. var distances = path3D.getDistances();
  68776. var pi2 = Math.PI * 2;
  68777. var step = pi2 / tessellation * arc;
  68778. var returnRadius = function () { return radius; };
  68779. var radiusFunctionFinal = radiusFunction || returnRadius;
  68780. var circlePath;
  68781. var rad;
  68782. var normal;
  68783. var rotated;
  68784. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  68785. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  68786. for (var i = 0; i < path.length; i++) {
  68787. rad = radiusFunctionFinal(i, distances[i]); // current radius
  68788. circlePath = Array(); // current circle array
  68789. normal = normals[i]; // current normal
  68790. for (var t = 0; t < tessellation; t++) {
  68791. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  68792. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  68793. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  68794. rotated.scaleInPlace(rad).addInPlace(path[i]);
  68795. circlePath[t] = rotated;
  68796. }
  68797. circlePaths[index] = circlePath;
  68798. index++;
  68799. }
  68800. // cap
  68801. var capPath = function (nbPoints, pathIndex) {
  68802. var pointCap = Array();
  68803. for (var i = 0; i < nbPoints; i++) {
  68804. pointCap.push(path[pathIndex]);
  68805. }
  68806. return pointCap;
  68807. };
  68808. switch (cap) {
  68809. case BABYLON.Mesh.NO_CAP:
  68810. break;
  68811. case BABYLON.Mesh.CAP_START:
  68812. circlePaths[0] = capPath(tessellation, 0);
  68813. circlePaths[1] = circlePaths[2].slice(0);
  68814. break;
  68815. case BABYLON.Mesh.CAP_END:
  68816. circlePaths[index] = circlePaths[index - 1].slice(0);
  68817. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  68818. break;
  68819. case BABYLON.Mesh.CAP_ALL:
  68820. circlePaths[0] = capPath(tessellation, 0);
  68821. circlePaths[1] = circlePaths[2].slice(0);
  68822. circlePaths[index] = circlePaths[index - 1].slice(0);
  68823. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  68824. break;
  68825. default:
  68826. break;
  68827. }
  68828. return circlePaths;
  68829. };
  68830. var path3D;
  68831. var pathArray;
  68832. if (instance) { // tube update
  68833. var storage = instance._creationDataStorage;
  68834. var arc = options.arc || storage.arc;
  68835. path3D = storage.path3D.update(path);
  68836. pathArray = tubePathArray(path, path3D, storage.pathArray, radius, storage.tessellation, radiusFunction, storage.cap, arc);
  68837. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  68838. // Update mode, no need to recreate the storage.
  68839. storage.path3D = path3D;
  68840. storage.pathArray = pathArray;
  68841. storage.arc = arc;
  68842. storage.radius = radius;
  68843. return instance;
  68844. }
  68845. // tube creation
  68846. path3D = new BABYLON.Path3D(path);
  68847. var newPathArray = new Array();
  68848. cap = (cap < 0 || cap > 3) ? 0 : cap;
  68849. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  68850. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  68851. tube._creationDataStorage.pathArray = pathArray;
  68852. tube._creationDataStorage.path3D = path3D;
  68853. tube._creationDataStorage.tessellation = tessellation;
  68854. tube._creationDataStorage.cap = cap;
  68855. tube._creationDataStorage.arc = options.arc;
  68856. tube._creationDataStorage.radius = radius;
  68857. return tube;
  68858. };
  68859. /**
  68860. * Creates a polyhedron mesh
  68861. * * 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
  68862. * * The parameter `size` (positive float, default 1) sets the polygon size
  68863. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  68864. * * 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`
  68865. * * 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
  68866. * * 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)`)
  68867. * * 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
  68868. * * 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
  68869. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68870. * * 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
  68871. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68872. * @param name defines the name of the mesh
  68873. * @param options defines the options used to create the mesh
  68874. * @param scene defines the hosting scene
  68875. * @returns the polyhedron mesh
  68876. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  68877. */
  68878. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  68879. var polyhedron = new BABYLON.Mesh(name, scene);
  68880. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68881. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  68882. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  68883. vertexData.applyToMesh(polyhedron, options.updatable);
  68884. return polyhedron;
  68885. };
  68886. /**
  68887. * Creates a decal mesh.
  68888. * 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
  68889. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  68890. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  68891. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  68892. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  68893. * @param name defines the name of the mesh
  68894. * @param sourceMesh defines the mesh where the decal must be applied
  68895. * @param options defines the options used to create the mesh
  68896. * @param scene defines the hosting scene
  68897. * @returns the decal mesh
  68898. * @see http://doc.babylonjs.com/how_to/decals
  68899. */
  68900. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  68901. var indices = sourceMesh.getIndices();
  68902. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  68903. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  68904. var position = options.position || BABYLON.Vector3.Zero();
  68905. var normal = options.normal || BABYLON.Vector3.Up();
  68906. var size = options.size || BABYLON.Vector3.One();
  68907. var angle = options.angle || 0;
  68908. // Getting correct rotation
  68909. if (!normal) {
  68910. var target = new BABYLON.Vector3(0, 0, 1);
  68911. var camera = sourceMesh.getScene().activeCamera;
  68912. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  68913. normal = camera.globalPosition.subtract(cameraWorldTarget);
  68914. }
  68915. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  68916. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  68917. var pitch = Math.atan2(normal.y, len);
  68918. // Matrix
  68919. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  68920. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  68921. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  68922. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  68923. var vertexData = new BABYLON.VertexData();
  68924. vertexData.indices = [];
  68925. vertexData.positions = [];
  68926. vertexData.normals = [];
  68927. vertexData.uvs = [];
  68928. var currentVertexDataIndex = 0;
  68929. var extractDecalVector3 = function (indexId) {
  68930. var result = new BABYLON.PositionNormalVertex();
  68931. if (!indices || !positions || !normals) {
  68932. return result;
  68933. }
  68934. var vertexId = indices[indexId];
  68935. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  68936. // Send vector to decal local world
  68937. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  68938. // Get normal
  68939. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  68940. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  68941. return result;
  68942. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  68943. var clip = function (vertices, axis) {
  68944. if (vertices.length === 0) {
  68945. return vertices;
  68946. }
  68947. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  68948. var clipVertices = function (v0, v1) {
  68949. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  68950. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  68951. };
  68952. var result = new Array();
  68953. for (var index = 0; index < vertices.length; index += 3) {
  68954. var v1Out;
  68955. var v2Out;
  68956. var v3Out;
  68957. var total = 0;
  68958. var nV1 = null;
  68959. var nV2 = null;
  68960. var nV3 = null;
  68961. var nV4 = null;
  68962. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  68963. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  68964. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  68965. v1Out = d1 > 0;
  68966. v2Out = d2 > 0;
  68967. v3Out = d3 > 0;
  68968. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  68969. switch (total) {
  68970. case 0:
  68971. result.push(vertices[index]);
  68972. result.push(vertices[index + 1]);
  68973. result.push(vertices[index + 2]);
  68974. break;
  68975. case 1:
  68976. if (v1Out) {
  68977. nV1 = vertices[index + 1];
  68978. nV2 = vertices[index + 2];
  68979. nV3 = clipVertices(vertices[index], nV1);
  68980. nV4 = clipVertices(vertices[index], nV2);
  68981. }
  68982. if (v2Out) {
  68983. nV1 = vertices[index];
  68984. nV2 = vertices[index + 2];
  68985. nV3 = clipVertices(vertices[index + 1], nV1);
  68986. nV4 = clipVertices(vertices[index + 1], nV2);
  68987. result.push(nV3);
  68988. result.push(nV2.clone());
  68989. result.push(nV1.clone());
  68990. result.push(nV2.clone());
  68991. result.push(nV3.clone());
  68992. result.push(nV4);
  68993. break;
  68994. }
  68995. if (v3Out) {
  68996. nV1 = vertices[index];
  68997. nV2 = vertices[index + 1];
  68998. nV3 = clipVertices(vertices[index + 2], nV1);
  68999. nV4 = clipVertices(vertices[index + 2], nV2);
  69000. }
  69001. if (nV1 && nV2 && nV3 && nV4) {
  69002. result.push(nV1.clone());
  69003. result.push(nV2.clone());
  69004. result.push(nV3);
  69005. result.push(nV4);
  69006. result.push(nV3.clone());
  69007. result.push(nV2.clone());
  69008. }
  69009. break;
  69010. case 2:
  69011. if (!v1Out) {
  69012. nV1 = vertices[index].clone();
  69013. nV2 = clipVertices(nV1, vertices[index + 1]);
  69014. nV3 = clipVertices(nV1, vertices[index + 2]);
  69015. result.push(nV1);
  69016. result.push(nV2);
  69017. result.push(nV3);
  69018. }
  69019. if (!v2Out) {
  69020. nV1 = vertices[index + 1].clone();
  69021. nV2 = clipVertices(nV1, vertices[index + 2]);
  69022. nV3 = clipVertices(nV1, vertices[index]);
  69023. result.push(nV1);
  69024. result.push(nV2);
  69025. result.push(nV3);
  69026. }
  69027. if (!v3Out) {
  69028. nV1 = vertices[index + 2].clone();
  69029. nV2 = clipVertices(nV1, vertices[index]);
  69030. nV3 = clipVertices(nV1, vertices[index + 1]);
  69031. result.push(nV1);
  69032. result.push(nV2);
  69033. result.push(nV3);
  69034. }
  69035. break;
  69036. case 3:
  69037. break;
  69038. }
  69039. }
  69040. return result;
  69041. };
  69042. for (var index = 0; index < indices.length; index += 3) {
  69043. var faceVertices = new Array();
  69044. faceVertices.push(extractDecalVector3(index));
  69045. faceVertices.push(extractDecalVector3(index + 1));
  69046. faceVertices.push(extractDecalVector3(index + 2));
  69047. // Clip
  69048. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  69049. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  69050. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  69051. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  69052. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  69053. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  69054. if (faceVertices.length === 0) {
  69055. continue;
  69056. }
  69057. // Add UVs and get back to world
  69058. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  69059. var vertex = faceVertices[vIndex];
  69060. //TODO check for Int32Array | Uint32Array | Uint16Array
  69061. vertexData.indices.push(currentVertexDataIndex);
  69062. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  69063. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  69064. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  69065. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  69066. currentVertexDataIndex++;
  69067. }
  69068. }
  69069. // Return mesh
  69070. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  69071. vertexData.applyToMesh(decal);
  69072. decal.position = position.clone();
  69073. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  69074. return decal;
  69075. };
  69076. // Privates
  69077. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  69078. // extrusion geometry
  69079. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  69080. var tangents = path3D.getTangents();
  69081. var normals = path3D.getNormals();
  69082. var binormals = path3D.getBinormals();
  69083. var distances = path3D.getDistances();
  69084. var angle = 0;
  69085. var returnScale = function () { return scale !== null ? scale : 1; };
  69086. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  69087. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  69088. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  69089. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  69090. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  69091. for (var i = 0; i < curve.length; i++) {
  69092. var shapePath = new Array();
  69093. var angleStep = rotate(i, distances[i]);
  69094. var scaleRatio = scl(i, distances[i]);
  69095. for (var p = 0; p < shape.length; p++) {
  69096. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  69097. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  69098. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  69099. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  69100. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  69101. shapePath[p] = rotated;
  69102. }
  69103. shapePaths[index] = shapePath;
  69104. angle += angleStep;
  69105. index++;
  69106. }
  69107. // cap
  69108. var capPath = function (shapePath) {
  69109. var pointCap = Array();
  69110. var barycenter = BABYLON.Vector3.Zero();
  69111. var i;
  69112. for (i = 0; i < shapePath.length; i++) {
  69113. barycenter.addInPlace(shapePath[i]);
  69114. }
  69115. barycenter.scaleInPlace(1.0 / shapePath.length);
  69116. for (i = 0; i < shapePath.length; i++) {
  69117. pointCap.push(barycenter);
  69118. }
  69119. return pointCap;
  69120. };
  69121. switch (cap) {
  69122. case BABYLON.Mesh.NO_CAP:
  69123. break;
  69124. case BABYLON.Mesh.CAP_START:
  69125. shapePaths[0] = capPath(shapePaths[2]);
  69126. shapePaths[1] = shapePaths[2];
  69127. break;
  69128. case BABYLON.Mesh.CAP_END:
  69129. shapePaths[index] = shapePaths[index - 1];
  69130. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  69131. break;
  69132. case BABYLON.Mesh.CAP_ALL:
  69133. shapePaths[0] = capPath(shapePaths[2]);
  69134. shapePaths[1] = shapePaths[2];
  69135. shapePaths[index] = shapePaths[index - 1];
  69136. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  69137. break;
  69138. default:
  69139. break;
  69140. }
  69141. return shapePaths;
  69142. };
  69143. var path3D;
  69144. var pathArray;
  69145. if (instance) { // instance update
  69146. var storage = instance._creationDataStorage;
  69147. path3D = storage.path3D.update(curve);
  69148. pathArray = extrusionPathArray(shape, curve, storage.path3D, storage.pathArray, scale, rotation, scaleFunction, rotateFunction, storage.cap, custom);
  69149. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  69150. return instance;
  69151. }
  69152. // extruded shape creation
  69153. path3D = new BABYLON.Path3D(curve);
  69154. var newShapePaths = new Array();
  69155. cap = (cap < 0 || cap > 3) ? 0 : cap;
  69156. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  69157. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  69158. extrudedGeneric._creationDataStorage.pathArray = pathArray;
  69159. extrudedGeneric._creationDataStorage.path3D = path3D;
  69160. extrudedGeneric._creationDataStorage.cap = cap;
  69161. return extrudedGeneric;
  69162. };
  69163. return MeshBuilder;
  69164. }());
  69165. BABYLON.MeshBuilder = MeshBuilder;
  69166. })(BABYLON || (BABYLON = {}));
  69167. //# sourceMappingURL=babylon.meshBuilder.js.map
  69168. var BABYLON;
  69169. (function (BABYLON) {
  69170. /**
  69171. * Draco compression (https://google.github.io/draco/)
  69172. *
  69173. * This class wraps the Draco module.
  69174. *
  69175. * **Encoder**
  69176. *
  69177. * The encoder is not currently implemented.
  69178. *
  69179. * **Decoder**
  69180. *
  69181. * 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.
  69182. *
  69183. * To update the configuration, use the following code:
  69184. * ```javascript
  69185. * BABYLON.DracoCompression.Configuration = {
  69186. * decoder: {
  69187. * wasmUrl: "<url to the WebAssembly library>",
  69188. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  69189. * fallbackUrl: "<url to the fallback JavaScript library>",
  69190. * }
  69191. * };
  69192. * ```
  69193. *
  69194. * 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.
  69195. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  69196. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  69197. *
  69198. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  69199. * ```javascript
  69200. * var dracoCompression = new BABYLON.DracoCompression();
  69201. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  69202. * [BABYLON.VertexBuffer.PositionKind]: 0
  69203. * });
  69204. * ```
  69205. *
  69206. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  69207. */
  69208. var DracoCompression = /** @class */ (function () {
  69209. /**
  69210. * Constructor
  69211. */
  69212. function DracoCompression() {
  69213. }
  69214. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  69215. /**
  69216. * Returns true if the decoder is available.
  69217. */
  69218. get: function () {
  69219. if (typeof DracoDecoderModule !== "undefined") {
  69220. return true;
  69221. }
  69222. var decoder = DracoCompression.Configuration.decoder;
  69223. if (decoder) {
  69224. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  69225. return true;
  69226. }
  69227. if (decoder.fallbackUrl) {
  69228. return true;
  69229. }
  69230. }
  69231. return false;
  69232. },
  69233. enumerable: true,
  69234. configurable: true
  69235. });
  69236. /**
  69237. * Stop all async operations and release resources.
  69238. */
  69239. DracoCompression.prototype.dispose = function () {
  69240. };
  69241. /**
  69242. * Decode Draco compressed mesh data to vertex data.
  69243. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  69244. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  69245. * @returns A promise that resolves with the decoded vertex data
  69246. */
  69247. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  69248. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  69249. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  69250. var module = wrappedModule.module;
  69251. var vertexData = new BABYLON.VertexData();
  69252. var buffer = new module.DecoderBuffer();
  69253. buffer.Init(dataView, dataView.byteLength);
  69254. var decoder = new module.Decoder();
  69255. var geometry;
  69256. var status;
  69257. try {
  69258. var type = decoder.GetEncodedGeometryType(buffer);
  69259. switch (type) {
  69260. case module.TRIANGULAR_MESH:
  69261. geometry = new module.Mesh();
  69262. status = decoder.DecodeBufferToMesh(buffer, geometry);
  69263. break;
  69264. case module.POINT_CLOUD:
  69265. geometry = new module.PointCloud();
  69266. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  69267. break;
  69268. default:
  69269. throw new Error("Invalid geometry type " + type);
  69270. }
  69271. if (!status.ok() || !geometry.ptr) {
  69272. throw new Error(status.error_msg());
  69273. }
  69274. var numPoints = geometry.num_points();
  69275. if (type === module.TRIANGULAR_MESH) {
  69276. var numFaces = geometry.num_faces();
  69277. var faceIndices = new module.DracoInt32Array();
  69278. try {
  69279. var indices = new Uint32Array(numFaces * 3);
  69280. for (var i = 0; i < numFaces; i++) {
  69281. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  69282. var offset = i * 3;
  69283. indices[offset + 0] = faceIndices.GetValue(0);
  69284. indices[offset + 1] = faceIndices.GetValue(1);
  69285. indices[offset + 2] = faceIndices.GetValue(2);
  69286. }
  69287. vertexData.indices = indices;
  69288. }
  69289. finally {
  69290. module.destroy(faceIndices);
  69291. }
  69292. }
  69293. for (var kind in attributes) {
  69294. var uniqueId = attributes[kind];
  69295. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  69296. var dracoData = new module.DracoFloat32Array();
  69297. try {
  69298. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  69299. var babylonData = new Float32Array(numPoints * attribute.num_components());
  69300. for (var i = 0; i < babylonData.length; i++) {
  69301. babylonData[i] = dracoData.GetValue(i);
  69302. }
  69303. vertexData.set(babylonData, kind);
  69304. }
  69305. finally {
  69306. module.destroy(dracoData);
  69307. }
  69308. }
  69309. }
  69310. finally {
  69311. if (geometry) {
  69312. module.destroy(geometry);
  69313. }
  69314. module.destroy(decoder);
  69315. module.destroy(buffer);
  69316. }
  69317. return vertexData;
  69318. });
  69319. };
  69320. DracoCompression._GetDecoderModule = function () {
  69321. if (!DracoCompression._DecoderModulePromise) {
  69322. var promise = null;
  69323. var config_1 = {};
  69324. if (typeof DracoDecoderModule !== "undefined") {
  69325. promise = Promise.resolve();
  69326. }
  69327. else {
  69328. var decoder = DracoCompression.Configuration.decoder;
  69329. if (decoder) {
  69330. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  69331. promise = Promise.all([
  69332. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  69333. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  69334. config_1.wasmBinary = data;
  69335. })
  69336. ]);
  69337. }
  69338. else if (decoder.fallbackUrl) {
  69339. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  69340. }
  69341. }
  69342. }
  69343. if (!promise) {
  69344. throw new Error("Draco decoder module is not available");
  69345. }
  69346. DracoCompression._DecoderModulePromise = promise.then(function () {
  69347. return new Promise(function (resolve) {
  69348. config_1.onModuleLoaded = function (decoderModule) {
  69349. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  69350. resolve({ module: decoderModule });
  69351. };
  69352. DracoDecoderModule(config_1);
  69353. });
  69354. });
  69355. }
  69356. return DracoCompression._DecoderModulePromise;
  69357. };
  69358. DracoCompression._LoadScriptAsync = function (url) {
  69359. return new Promise(function (resolve, reject) {
  69360. BABYLON.Tools.LoadScript(url, function () {
  69361. resolve();
  69362. }, function (message) {
  69363. reject(new Error(message));
  69364. });
  69365. });
  69366. };
  69367. DracoCompression._LoadFileAsync = function (url) {
  69368. return new Promise(function (resolve, reject) {
  69369. BABYLON.Tools.LoadFile(url, function (data) {
  69370. resolve(data);
  69371. }, undefined, undefined, true, function (request, exception) {
  69372. reject(exception);
  69373. });
  69374. });
  69375. };
  69376. /**
  69377. * The configuration. Defaults to the following urls:
  69378. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  69379. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  69380. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  69381. */
  69382. DracoCompression.Configuration = {
  69383. decoder: {
  69384. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  69385. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  69386. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  69387. }
  69388. };
  69389. return DracoCompression;
  69390. }());
  69391. BABYLON.DracoCompression = DracoCompression;
  69392. })(BABYLON || (BABYLON = {}));
  69393. //# sourceMappingURL=babylon.dracoCompression.js.map
  69394. var BABYLON;
  69395. (function (BABYLON) {
  69396. // Sets the default audio engine to Babylon JS.
  69397. BABYLON.Engine.AudioEngineFactory = function (hostElement) { return new AudioEngine(hostElement); };
  69398. /**
  69399. * This represents the default audio engine used in babylon.
  69400. * It is responsible to play, synchronize and analyse sounds throughout the application.
  69401. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  69402. */
  69403. var AudioEngine = /** @class */ (function () {
  69404. /**
  69405. * Instantiates a new audio engine.
  69406. *
  69407. * There should be only one per page as some browsers restrict the number
  69408. * of audio contexts you can create.
  69409. * @param hostElement defines the host element where to display the mute icon if necessary
  69410. */
  69411. function AudioEngine(hostElement) {
  69412. if (hostElement === void 0) { hostElement = null; }
  69413. var _this = this;
  69414. this._audioContext = null;
  69415. this._audioContextInitialized = false;
  69416. this._muteButton = null;
  69417. /**
  69418. * Gets whether the current host supports Web Audio and thus could create AudioContexts.
  69419. */
  69420. this.canUseWebAudio = false;
  69421. /**
  69422. * Defines if Babylon should emit a warning if WebAudio is not supported.
  69423. * @ignoreNaming
  69424. */
  69425. this.WarnedWebAudioUnsupported = false;
  69426. /**
  69427. * Gets whether or not mp3 are supported by your browser.
  69428. */
  69429. this.isMP3supported = false;
  69430. /**
  69431. * Gets whether or not ogg are supported by your browser.
  69432. */
  69433. this.isOGGsupported = false;
  69434. /**
  69435. * Gets whether audio has been unlocked on the device.
  69436. * Some Browsers have strong restrictions about Audio and won t autoplay unless
  69437. * a user interaction has happened.
  69438. */
  69439. this.unlocked = true;
  69440. /**
  69441. * Defines if the audio engine relies on a custom unlocked button.
  69442. * In this case, the embedded button will not be displayed.
  69443. */
  69444. this.useCustomUnlockedButton = false;
  69445. /**
  69446. * Event raised when audio has been unlocked on the browser.
  69447. */
  69448. this.onAudioUnlockedObservable = new BABYLON.Observable();
  69449. /**
  69450. * Event raised when audio has been locked on the browser.
  69451. */
  69452. this.onAudioLockedObservable = new BABYLON.Observable();
  69453. this._tryToRun = false;
  69454. this._onResize = function () {
  69455. _this._moveButtonToTopLeft();
  69456. };
  69457. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  69458. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  69459. this.canUseWebAudio = true;
  69460. }
  69461. var audioElem = document.createElement('audio');
  69462. this._hostElement = hostElement;
  69463. try {
  69464. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  69465. this.isMP3supported = true;
  69466. }
  69467. }
  69468. catch (e) {
  69469. // protect error during capability check.
  69470. }
  69471. try {
  69472. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  69473. this.isOGGsupported = true;
  69474. }
  69475. }
  69476. catch (e) {
  69477. // protect error during capability check.
  69478. }
  69479. }
  69480. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  69481. /**
  69482. * Gets the current AudioContext if available.
  69483. */
  69484. get: function () {
  69485. if (!this._audioContextInitialized) {
  69486. this._initializeAudioContext();
  69487. }
  69488. else {
  69489. if (!this.unlocked && !this._muteButton) {
  69490. this._displayMuteButton();
  69491. }
  69492. }
  69493. return this._audioContext;
  69494. },
  69495. enumerable: true,
  69496. configurable: true
  69497. });
  69498. /**
  69499. * Flags the audio engine in Locked state.
  69500. * This happens due to new browser policies preventing audio to autoplay.
  69501. */
  69502. AudioEngine.prototype.lock = function () {
  69503. this._triggerSuspendedState();
  69504. };
  69505. /**
  69506. * Unlocks the audio engine once a user action has been done on the dom.
  69507. * This is helpful to resume play once browser policies have been satisfied.
  69508. */
  69509. AudioEngine.prototype.unlock = function () {
  69510. this._triggerRunningState();
  69511. };
  69512. AudioEngine.prototype._resumeAudioContext = function () {
  69513. var result;
  69514. if (this._audioContext.resume) {
  69515. result = this._audioContext.resume();
  69516. }
  69517. return result || Promise.resolve();
  69518. };
  69519. AudioEngine.prototype._initializeAudioContext = function () {
  69520. try {
  69521. if (this.canUseWebAudio) {
  69522. this._audioContext = new AudioContext();
  69523. // create a global volume gain node
  69524. this.masterGain = this._audioContext.createGain();
  69525. this.masterGain.gain.value = 1;
  69526. this.masterGain.connect(this._audioContext.destination);
  69527. this._audioContextInitialized = true;
  69528. if (this._audioContext.state === "running") {
  69529. // Do not wait for the promise to unlock.
  69530. this._triggerRunningState();
  69531. }
  69532. }
  69533. }
  69534. catch (e) {
  69535. this.canUseWebAudio = false;
  69536. BABYLON.Tools.Error("Web Audio: " + e.message);
  69537. }
  69538. };
  69539. AudioEngine.prototype._triggerRunningState = function () {
  69540. var _this = this;
  69541. if (this._tryToRun) {
  69542. return;
  69543. }
  69544. this._tryToRun = true;
  69545. this._resumeAudioContext()
  69546. .then(function () {
  69547. _this._tryToRun = false;
  69548. if (_this._muteButton) {
  69549. _this._hideMuteButton();
  69550. }
  69551. }).catch(function () {
  69552. _this._tryToRun = false;
  69553. _this.unlocked = false;
  69554. });
  69555. // Notify users that the audio stack is unlocked/unmuted
  69556. this.unlocked = true;
  69557. this.onAudioUnlockedObservable.notifyObservers(this);
  69558. };
  69559. AudioEngine.prototype._triggerSuspendedState = function () {
  69560. this.unlocked = false;
  69561. this.onAudioLockedObservable.notifyObservers(this);
  69562. this._displayMuteButton();
  69563. };
  69564. AudioEngine.prototype._displayMuteButton = function () {
  69565. var _this = this;
  69566. if (this.useCustomUnlockedButton) {
  69567. return;
  69568. }
  69569. this._muteButton = document.createElement("BUTTON");
  69570. this._muteButton.className = "babylonUnmuteIcon";
  69571. this._muteButton.id = "babylonUnmuteIconBtn";
  69572. this._muteButton.title = "Unmute";
  69573. 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) }";
  69574. var style = document.createElement('style');
  69575. style.appendChild(document.createTextNode(css));
  69576. document.getElementsByTagName('head')[0].appendChild(style);
  69577. document.body.appendChild(this._muteButton);
  69578. this._moveButtonToTopLeft();
  69579. this._muteButton.addEventListener('touchend', function () {
  69580. _this._triggerRunningState();
  69581. }, true);
  69582. this._muteButton.addEventListener('click', function () {
  69583. _this._triggerRunningState();
  69584. }, true);
  69585. window.addEventListener("resize", this._onResize);
  69586. };
  69587. AudioEngine.prototype._moveButtonToTopLeft = function () {
  69588. if (this._hostElement && this._muteButton) {
  69589. this._muteButton.style.top = this._hostElement.offsetTop + 20 + "px";
  69590. this._muteButton.style.left = this._hostElement.offsetLeft + 20 + "px";
  69591. }
  69592. };
  69593. AudioEngine.prototype._hideMuteButton = function () {
  69594. if (this._muteButton) {
  69595. document.body.removeChild(this._muteButton);
  69596. this._muteButton = null;
  69597. }
  69598. };
  69599. /**
  69600. * Destroy and release the resources associated with the audio ccontext.
  69601. */
  69602. AudioEngine.prototype.dispose = function () {
  69603. if (this.canUseWebAudio && this._audioContextInitialized) {
  69604. if (this._connectedAnalyser && this._audioContext) {
  69605. this._connectedAnalyser.stopDebugCanvas();
  69606. this._connectedAnalyser.dispose();
  69607. this.masterGain.disconnect();
  69608. this.masterGain.connect(this._audioContext.destination);
  69609. this._connectedAnalyser = null;
  69610. }
  69611. this.masterGain.gain.value = 1;
  69612. }
  69613. this.WarnedWebAudioUnsupported = false;
  69614. this._hideMuteButton();
  69615. window.removeEventListener("resize", this._onResize);
  69616. this.onAudioUnlockedObservable.clear();
  69617. this.onAudioLockedObservable.clear();
  69618. };
  69619. /**
  69620. * Gets the global volume sets on the master gain.
  69621. * @returns the global volume if set or -1 otherwise
  69622. */
  69623. AudioEngine.prototype.getGlobalVolume = function () {
  69624. if (this.canUseWebAudio && this._audioContextInitialized) {
  69625. return this.masterGain.gain.value;
  69626. }
  69627. else {
  69628. return -1;
  69629. }
  69630. };
  69631. /**
  69632. * Sets the global volume of your experience (sets on the master gain).
  69633. * @param newVolume Defines the new global volume of the application
  69634. */
  69635. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  69636. if (this.canUseWebAudio && this._audioContextInitialized) {
  69637. this.masterGain.gain.value = newVolume;
  69638. }
  69639. };
  69640. /**
  69641. * Connect the audio engine to an audio analyser allowing some amazing
  69642. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  69643. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  69644. * @param analyser The analyser to connect to the engine
  69645. */
  69646. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  69647. if (this._connectedAnalyser) {
  69648. this._connectedAnalyser.stopDebugCanvas();
  69649. }
  69650. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  69651. this._connectedAnalyser = analyser;
  69652. this.masterGain.disconnect();
  69653. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  69654. }
  69655. };
  69656. return AudioEngine;
  69657. }());
  69658. BABYLON.AudioEngine = AudioEngine;
  69659. })(BABYLON || (BABYLON = {}));
  69660. //# sourceMappingURL=babylon.audioEngine.js.map
  69661. var BABYLON;
  69662. (function (BABYLON) {
  69663. /**
  69664. * Defines a sound that can be played in the application.
  69665. * The sound can either be an ambient track or a simple sound played in reaction to a user action.
  69666. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  69667. */
  69668. var Sound = /** @class */ (function () {
  69669. /**
  69670. * Create a sound and attach it to a scene
  69671. * @param name Name of your sound
  69672. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  69673. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  69674. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  69675. */
  69676. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  69677. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  69678. var _this = this;
  69679. /**
  69680. * Does the sound autoplay once loaded.
  69681. */
  69682. this.autoplay = false;
  69683. /**
  69684. * Does the sound loop after it finishes playing once.
  69685. */
  69686. this.loop = false;
  69687. /**
  69688. * Does the sound use a custom attenuation curve to simulate the falloff
  69689. * happening when the source gets further away from the camera.
  69690. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  69691. */
  69692. this.useCustomAttenuation = false;
  69693. /**
  69694. * Is this sound currently played.
  69695. */
  69696. this.isPlaying = false;
  69697. /**
  69698. * Is this sound currently paused.
  69699. */
  69700. this.isPaused = false;
  69701. /**
  69702. * Does this sound enables spatial sound.
  69703. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69704. */
  69705. this.spatialSound = false;
  69706. /**
  69707. * Define the reference distance the sound should be heard perfectly.
  69708. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69709. */
  69710. this.refDistance = 1;
  69711. /**
  69712. * Define the roll off factor of spatial sounds.
  69713. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69714. */
  69715. this.rolloffFactor = 1;
  69716. /**
  69717. * Define the max distance the sound should be heard (intensity just became 0 at this point).
  69718. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69719. */
  69720. this.maxDistance = 100;
  69721. /**
  69722. * Define the distance attenuation model the sound will follow.
  69723. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69724. */
  69725. this.distanceModel = "linear";
  69726. /**
  69727. * Observable event when the current playing sound finishes.
  69728. */
  69729. this.onEndedObservable = new BABYLON.Observable();
  69730. this._panningModel = "equalpower";
  69731. this._playbackRate = 1;
  69732. this._streaming = false;
  69733. this._startTime = 0;
  69734. this._startOffset = 0;
  69735. this._position = BABYLON.Vector3.Zero();
  69736. /** @hidden */
  69737. this._positionInEmitterSpace = false;
  69738. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  69739. this._volume = 1;
  69740. this._isReadyToPlay = false;
  69741. this._isDirectional = false;
  69742. // Used if you'd like to create a directional sound.
  69743. // If not set, the sound will be omnidirectional
  69744. this._coneInnerAngle = 360;
  69745. this._coneOuterAngle = 360;
  69746. this._coneOuterGain = 0;
  69747. this._isOutputConnected = false;
  69748. this._urlType = "Unknown";
  69749. this.name = name;
  69750. this._scene = scene;
  69751. var compo = scene._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  69752. if (!compo) {
  69753. compo = new BABYLON.AudioSceneComponent(scene);
  69754. scene._addComponent(compo);
  69755. }
  69756. this._readyToPlayCallback = readyToPlayCallback;
  69757. // Default custom attenuation function is a linear attenuation
  69758. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  69759. if (currentDistance < maxDistance) {
  69760. return currentVolume * (1 - currentDistance / maxDistance);
  69761. }
  69762. else {
  69763. return 0;
  69764. }
  69765. };
  69766. if (options) {
  69767. this.autoplay = options.autoplay || false;
  69768. this.loop = options.loop || false;
  69769. // if volume === 0, we need another way to check this option
  69770. if (options.volume !== undefined) {
  69771. this._volume = options.volume;
  69772. }
  69773. this.spatialSound = options.spatialSound || false;
  69774. this.maxDistance = options.maxDistance || 100;
  69775. this.useCustomAttenuation = options.useCustomAttenuation || false;
  69776. this.rolloffFactor = options.rolloffFactor || 1;
  69777. this.refDistance = options.refDistance || 1;
  69778. this.distanceModel = options.distanceModel || "linear";
  69779. this._playbackRate = options.playbackRate || 1;
  69780. this._streaming = options.streaming || false;
  69781. }
  69782. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  69783. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  69784. this._soundGain.gain.value = this._volume;
  69785. this._inputAudioNode = this._soundGain;
  69786. this._outputAudioNode = this._soundGain;
  69787. if (this.spatialSound) {
  69788. this._createSpatialParameters();
  69789. }
  69790. this._scene.mainSoundTrack.AddSound(this);
  69791. var validParameter = true;
  69792. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  69793. if (urlOrArrayBuffer) {
  69794. try {
  69795. if (typeof (urlOrArrayBuffer) === "string") {
  69796. this._urlType = "String";
  69797. }
  69798. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  69799. this._urlType = "ArrayBuffer";
  69800. }
  69801. else if (urlOrArrayBuffer instanceof MediaStream) {
  69802. this._urlType = "MediaStream";
  69803. }
  69804. else if (Array.isArray(urlOrArrayBuffer)) {
  69805. this._urlType = "Array";
  69806. }
  69807. var urls = [];
  69808. var codecSupportedFound = false;
  69809. switch (this._urlType) {
  69810. case "MediaStream":
  69811. this._streaming = true;
  69812. this._isReadyToPlay = true;
  69813. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
  69814. if (this.autoplay) {
  69815. this.play();
  69816. }
  69817. if (this._readyToPlayCallback) {
  69818. this._readyToPlayCallback();
  69819. }
  69820. break;
  69821. case "ArrayBuffer":
  69822. if (urlOrArrayBuffer.byteLength > 0) {
  69823. codecSupportedFound = true;
  69824. this._soundLoaded(urlOrArrayBuffer);
  69825. }
  69826. break;
  69827. case "String":
  69828. urls.push(urlOrArrayBuffer);
  69829. case "Array":
  69830. if (urls.length === 0) {
  69831. urls = urlOrArrayBuffer;
  69832. }
  69833. // If we found a supported format, we load it immediately and stop the loop
  69834. for (var i = 0; i < urls.length; i++) {
  69835. var url = urls[i];
  69836. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  69837. codecSupportedFound = true;
  69838. }
  69839. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  69840. codecSupportedFound = true;
  69841. }
  69842. if (url.indexOf(".wav", url.length - 4) !== -1) {
  69843. codecSupportedFound = true;
  69844. }
  69845. if (url.indexOf("blob:") !== -1) {
  69846. codecSupportedFound = true;
  69847. }
  69848. if (codecSupportedFound) {
  69849. // Loading sound using XHR2
  69850. if (!this._streaming) {
  69851. this._scene._loadFile(url, function (data) {
  69852. _this._soundLoaded(data);
  69853. }, undefined, true, true, function (exception) {
  69854. if (exception) {
  69855. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  69856. }
  69857. BABYLON.Tools.Error("Sound creation aborted.");
  69858. _this._scene.mainSoundTrack.RemoveSound(_this);
  69859. });
  69860. }
  69861. // Streaming sound using HTML5 Audio tag
  69862. else {
  69863. this._htmlAudioElement = new Audio(url);
  69864. this._htmlAudioElement.controls = false;
  69865. this._htmlAudioElement.loop = this.loop;
  69866. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  69867. this._htmlAudioElement.preload = "auto";
  69868. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  69869. _this._isReadyToPlay = true;
  69870. if (_this.autoplay) {
  69871. _this.play();
  69872. }
  69873. if (_this._readyToPlayCallback) {
  69874. _this._readyToPlayCallback();
  69875. }
  69876. });
  69877. document.body.appendChild(this._htmlAudioElement);
  69878. this._htmlAudioElement.load();
  69879. }
  69880. break;
  69881. }
  69882. }
  69883. break;
  69884. default:
  69885. validParameter = false;
  69886. break;
  69887. }
  69888. if (!validParameter) {
  69889. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  69890. }
  69891. else {
  69892. if (!codecSupportedFound) {
  69893. this._isReadyToPlay = true;
  69894. // Simulating a ready to play event to avoid breaking code path
  69895. if (this._readyToPlayCallback) {
  69896. window.setTimeout(function () {
  69897. if (_this._readyToPlayCallback) {
  69898. _this._readyToPlayCallback();
  69899. }
  69900. }, 1000);
  69901. }
  69902. }
  69903. }
  69904. }
  69905. catch (ex) {
  69906. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  69907. this._scene.mainSoundTrack.RemoveSound(this);
  69908. }
  69909. }
  69910. }
  69911. else {
  69912. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  69913. this._scene.mainSoundTrack.AddSound(this);
  69914. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  69915. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  69916. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  69917. }
  69918. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  69919. if (this._readyToPlayCallback) {
  69920. window.setTimeout(function () {
  69921. if (_this._readyToPlayCallback) {
  69922. _this._readyToPlayCallback();
  69923. }
  69924. }, 1000);
  69925. }
  69926. }
  69927. }
  69928. /**
  69929. * Release the sound and its associated resources
  69930. */
  69931. Sound.prototype.dispose = function () {
  69932. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  69933. if (this.isPlaying) {
  69934. this.stop();
  69935. }
  69936. this._isReadyToPlay = false;
  69937. if (this.soundTrackId === -1) {
  69938. this._scene.mainSoundTrack.RemoveSound(this);
  69939. }
  69940. else if (this._scene.soundTracks) {
  69941. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  69942. }
  69943. if (this._soundGain) {
  69944. this._soundGain.disconnect();
  69945. this._soundGain = null;
  69946. }
  69947. if (this._soundPanner) {
  69948. this._soundPanner.disconnect();
  69949. this._soundPanner = null;
  69950. }
  69951. if (this._soundSource) {
  69952. this._soundSource.disconnect();
  69953. this._soundSource = null;
  69954. }
  69955. this._audioBuffer = null;
  69956. if (this._htmlAudioElement) {
  69957. this._htmlAudioElement.pause();
  69958. this._htmlAudioElement.src = "";
  69959. document.body.removeChild(this._htmlAudioElement);
  69960. }
  69961. if (this._streamingSource) {
  69962. this._streamingSource.disconnect();
  69963. }
  69964. if (this._connectedMesh && this._registerFunc) {
  69965. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  69966. this._connectedMesh = null;
  69967. }
  69968. }
  69969. };
  69970. /**
  69971. * Gets if the sounds is ready to be played or not.
  69972. * @returns true if ready, otherwise false
  69973. */
  69974. Sound.prototype.isReady = function () {
  69975. return this._isReadyToPlay;
  69976. };
  69977. Sound.prototype._soundLoaded = function (audioData) {
  69978. var _this = this;
  69979. if (!BABYLON.Engine.audioEngine.audioContext) {
  69980. return;
  69981. }
  69982. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  69983. _this._audioBuffer = buffer;
  69984. _this._isReadyToPlay = true;
  69985. if (_this.autoplay) {
  69986. _this.play();
  69987. }
  69988. if (_this._readyToPlayCallback) {
  69989. _this._readyToPlayCallback();
  69990. }
  69991. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  69992. };
  69993. /**
  69994. * Sets the data of the sound from an audiobuffer
  69995. * @param audioBuffer The audioBuffer containing the data
  69996. */
  69997. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  69998. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  69999. this._audioBuffer = audioBuffer;
  70000. this._isReadyToPlay = true;
  70001. }
  70002. };
  70003. /**
  70004. * Updates the current sounds options such as maxdistance, loop...
  70005. * @param options A JSON object containing values named as the object properties
  70006. */
  70007. Sound.prototype.updateOptions = function (options) {
  70008. if (options) {
  70009. this.loop = options.loop || this.loop;
  70010. this.maxDistance = options.maxDistance || this.maxDistance;
  70011. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  70012. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  70013. this.refDistance = options.refDistance || this.refDistance;
  70014. this.distanceModel = options.distanceModel || this.distanceModel;
  70015. this._playbackRate = options.playbackRate || this._playbackRate;
  70016. this._updateSpatialParameters();
  70017. if (this.isPlaying) {
  70018. if (this._streaming && this._htmlAudioElement) {
  70019. this._htmlAudioElement.playbackRate = this._playbackRate;
  70020. }
  70021. else {
  70022. if (this._soundSource) {
  70023. this._soundSource.playbackRate.value = this._playbackRate;
  70024. }
  70025. }
  70026. }
  70027. }
  70028. };
  70029. Sound.prototype._createSpatialParameters = function () {
  70030. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  70031. if (this._scene.headphone) {
  70032. this._panningModel = "HRTF";
  70033. }
  70034. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  70035. this._updateSpatialParameters();
  70036. this._soundPanner.connect(this._outputAudioNode);
  70037. this._inputAudioNode = this._soundPanner;
  70038. }
  70039. };
  70040. Sound.prototype._updateSpatialParameters = function () {
  70041. if (this.spatialSound && this._soundPanner) {
  70042. if (this.useCustomAttenuation) {
  70043. // Tricks to disable in a way embedded Web Audio attenuation
  70044. this._soundPanner.distanceModel = "linear";
  70045. this._soundPanner.maxDistance = Number.MAX_VALUE;
  70046. this._soundPanner.refDistance = 1;
  70047. this._soundPanner.rolloffFactor = 1;
  70048. this._soundPanner.panningModel = this._panningModel;
  70049. }
  70050. else {
  70051. this._soundPanner.distanceModel = this.distanceModel;
  70052. this._soundPanner.maxDistance = this.maxDistance;
  70053. this._soundPanner.refDistance = this.refDistance;
  70054. this._soundPanner.rolloffFactor = this.rolloffFactor;
  70055. this._soundPanner.panningModel = this._panningModel;
  70056. }
  70057. }
  70058. };
  70059. /**
  70060. * Switch the panning model to HRTF:
  70061. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  70062. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  70063. */
  70064. Sound.prototype.switchPanningModelToHRTF = function () {
  70065. this._panningModel = "HRTF";
  70066. this._switchPanningModel();
  70067. };
  70068. /**
  70069. * Switch the panning model to Equal Power:
  70070. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  70071. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  70072. */
  70073. Sound.prototype.switchPanningModelToEqualPower = function () {
  70074. this._panningModel = "equalpower";
  70075. this._switchPanningModel();
  70076. };
  70077. Sound.prototype._switchPanningModel = function () {
  70078. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  70079. this._soundPanner.panningModel = this._panningModel;
  70080. }
  70081. };
  70082. /**
  70083. * Connect this sound to a sound track audio node like gain...
  70084. * @param soundTrackAudioNode the sound track audio node to connect to
  70085. */
  70086. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  70087. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  70088. if (this._isOutputConnected) {
  70089. this._outputAudioNode.disconnect();
  70090. }
  70091. this._outputAudioNode.connect(soundTrackAudioNode);
  70092. this._isOutputConnected = true;
  70093. }
  70094. };
  70095. /**
  70096. * Transform this sound into a directional source
  70097. * @param coneInnerAngle Size of the inner cone in degree
  70098. * @param coneOuterAngle Size of the outer cone in degree
  70099. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  70100. */
  70101. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  70102. if (coneOuterAngle < coneInnerAngle) {
  70103. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  70104. return;
  70105. }
  70106. this._coneInnerAngle = coneInnerAngle;
  70107. this._coneOuterAngle = coneOuterAngle;
  70108. this._coneOuterGain = coneOuterGain;
  70109. this._isDirectional = true;
  70110. if (this.isPlaying && this.loop) {
  70111. this.stop();
  70112. this.play();
  70113. }
  70114. };
  70115. Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
  70116. /**
  70117. * Gets or sets the inner angle for the directional cone.
  70118. */
  70119. get: function () {
  70120. return this._coneInnerAngle;
  70121. },
  70122. /**
  70123. * Gets or sets the inner angle for the directional cone.
  70124. */
  70125. set: function (value) {
  70126. if (value != this._coneInnerAngle) {
  70127. if (this._coneOuterAngle < value) {
  70128. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  70129. return;
  70130. }
  70131. this._coneInnerAngle = value;
  70132. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  70133. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  70134. }
  70135. }
  70136. },
  70137. enumerable: true,
  70138. configurable: true
  70139. });
  70140. Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
  70141. /**
  70142. * Gets or sets the outer angle for the directional cone.
  70143. */
  70144. get: function () {
  70145. return this._coneOuterAngle;
  70146. },
  70147. /**
  70148. * Gets or sets the outer angle for the directional cone.
  70149. */
  70150. set: function (value) {
  70151. if (value != this._coneOuterAngle) {
  70152. if (value < this._coneInnerAngle) {
  70153. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  70154. return;
  70155. }
  70156. this._coneOuterAngle = value;
  70157. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  70158. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  70159. }
  70160. }
  70161. },
  70162. enumerable: true,
  70163. configurable: true
  70164. });
  70165. /**
  70166. * Sets the position of the emitter if spatial sound is enabled
  70167. * @param newPosition Defines the new posisiton
  70168. */
  70169. Sound.prototype.setPosition = function (newPosition) {
  70170. this._position = newPosition;
  70171. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  70172. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  70173. }
  70174. };
  70175. /**
  70176. * Sets the local direction of the emitter if spatial sound is enabled
  70177. * @param newLocalDirection Defines the new local direction
  70178. */
  70179. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  70180. this._localDirection = newLocalDirection;
  70181. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  70182. this._updateDirection();
  70183. }
  70184. };
  70185. Sound.prototype._updateDirection = function () {
  70186. if (!this._connectedMesh || !this._soundPanner) {
  70187. return;
  70188. }
  70189. var mat = this._connectedMesh.getWorldMatrix();
  70190. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  70191. direction.normalize();
  70192. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  70193. };
  70194. /** @hidden */
  70195. Sound.prototype.updateDistanceFromListener = function () {
  70196. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  70197. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  70198. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  70199. }
  70200. };
  70201. /**
  70202. * Sets a new custom attenuation function for the sound.
  70203. * @param callback Defines the function used for the attenuation
  70204. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  70205. */
  70206. Sound.prototype.setAttenuationFunction = function (callback) {
  70207. this._customAttenuationFunction = callback;
  70208. };
  70209. /**
  70210. * Play the sound
  70211. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  70212. * @param offset (optional) Start the sound setting it at a specific time
  70213. */
  70214. Sound.prototype.play = function (time, offset) {
  70215. var _this = this;
  70216. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  70217. try {
  70218. if (this._startOffset < 0) {
  70219. time = -this._startOffset;
  70220. this._startOffset = 0;
  70221. }
  70222. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  70223. if (!this._soundSource || !this._streamingSource) {
  70224. if (this.spatialSound && this._soundPanner) {
  70225. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  70226. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  70227. }
  70228. if (this._isDirectional) {
  70229. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  70230. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  70231. this._soundPanner.coneOuterGain = this._coneOuterGain;
  70232. if (this._connectedMesh) {
  70233. this._updateDirection();
  70234. }
  70235. else {
  70236. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  70237. }
  70238. }
  70239. }
  70240. }
  70241. if (this._streaming) {
  70242. if (!this._streamingSource) {
  70243. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  70244. this._htmlAudioElement.onended = function () { _this._onended(); };
  70245. this._htmlAudioElement.playbackRate = this._playbackRate;
  70246. }
  70247. this._streamingSource.disconnect();
  70248. this._streamingSource.connect(this._inputAudioNode);
  70249. if (this._htmlAudioElement) {
  70250. // required to manage properly the new suspended default state of Chrome
  70251. // When the option 'streaming: true' is used, we need first to wait for
  70252. // the audio engine to be unlocked by a user gesture before trying to play
  70253. // an HTML Audio elememt
  70254. var tryToPlay = function () {
  70255. if (BABYLON.Engine.audioEngine.unlocked) {
  70256. var playPromise = _this._htmlAudioElement.play();
  70257. // In browsers that don’t yet support this functionality,
  70258. // playPromise won’t be defined.
  70259. if (playPromise !== undefined) {
  70260. playPromise.catch(function (error) {
  70261. // Automatic playback failed.
  70262. // Waiting for the audio engine to be unlocked by user click on unmute
  70263. BABYLON.Engine.audioEngine.lock();
  70264. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  70265. });
  70266. }
  70267. }
  70268. else {
  70269. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  70270. }
  70271. };
  70272. tryToPlay();
  70273. }
  70274. }
  70275. else {
  70276. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  70277. this._soundSource.buffer = this._audioBuffer;
  70278. this._soundSource.connect(this._inputAudioNode);
  70279. this._soundSource.loop = this.loop;
  70280. this._soundSource.playbackRate.value = this._playbackRate;
  70281. this._soundSource.onended = function () { _this._onended(); };
  70282. if (this._soundSource.buffer) {
  70283. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  70284. }
  70285. }
  70286. this._startTime = startTime;
  70287. this.isPlaying = true;
  70288. this.isPaused = false;
  70289. }
  70290. catch (ex) {
  70291. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  70292. }
  70293. }
  70294. };
  70295. Sound.prototype._onended = function () {
  70296. this.isPlaying = false;
  70297. if (this.onended) {
  70298. this.onended();
  70299. }
  70300. this.onEndedObservable.notifyObservers(this);
  70301. };
  70302. /**
  70303. * Stop the sound
  70304. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  70305. */
  70306. Sound.prototype.stop = function (time) {
  70307. if (this.isPlaying) {
  70308. if (this._streaming) {
  70309. if (this._htmlAudioElement) {
  70310. this._htmlAudioElement.pause();
  70311. // Test needed for Firefox or it will generate an Invalid State Error
  70312. if (this._htmlAudioElement.currentTime > 0) {
  70313. this._htmlAudioElement.currentTime = 0;
  70314. }
  70315. }
  70316. else {
  70317. this._streamingSource.disconnect();
  70318. }
  70319. }
  70320. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  70321. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  70322. this._soundSource.stop(stopTime);
  70323. this._soundSource.onended = function () { };
  70324. if (!this.isPaused) {
  70325. this._startOffset = 0;
  70326. }
  70327. }
  70328. this.isPlaying = false;
  70329. }
  70330. };
  70331. /**
  70332. * Put the sound in pause
  70333. */
  70334. Sound.prototype.pause = function () {
  70335. if (this.isPlaying) {
  70336. this.isPaused = true;
  70337. if (this._streaming) {
  70338. if (this._htmlAudioElement) {
  70339. this._htmlAudioElement.pause();
  70340. }
  70341. else {
  70342. this._streamingSource.disconnect();
  70343. }
  70344. }
  70345. else if (BABYLON.Engine.audioEngine.audioContext) {
  70346. this.stop(0);
  70347. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  70348. }
  70349. }
  70350. };
  70351. /**
  70352. * Sets a dedicated volume for this sounds
  70353. * @param newVolume Define the new volume of the sound
  70354. * @param time Define in how long the sound should be at this value
  70355. */
  70356. Sound.prototype.setVolume = function (newVolume, time) {
  70357. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  70358. if (time && BABYLON.Engine.audioEngine.audioContext) {
  70359. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  70360. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  70361. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  70362. }
  70363. else {
  70364. this._soundGain.gain.value = newVolume;
  70365. }
  70366. }
  70367. this._volume = newVolume;
  70368. };
  70369. /**
  70370. * Set the sound play back rate
  70371. * @param newPlaybackRate Define the playback rate the sound should be played at
  70372. */
  70373. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  70374. this._playbackRate = newPlaybackRate;
  70375. if (this.isPlaying) {
  70376. if (this._streaming && this._htmlAudioElement) {
  70377. this._htmlAudioElement.playbackRate = this._playbackRate;
  70378. }
  70379. else if (this._soundSource) {
  70380. this._soundSource.playbackRate.value = this._playbackRate;
  70381. }
  70382. }
  70383. };
  70384. /**
  70385. * Gets the volume of the sound.
  70386. * @returns the volume of the sound
  70387. */
  70388. Sound.prototype.getVolume = function () {
  70389. return this._volume;
  70390. };
  70391. /**
  70392. * Attach the sound to a dedicated mesh
  70393. * @param meshToConnectTo The mesh to connect the sound with
  70394. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  70395. */
  70396. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  70397. var _this = this;
  70398. if (this._connectedMesh && this._registerFunc) {
  70399. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  70400. this._registerFunc = null;
  70401. }
  70402. this._connectedMesh = meshToConnectTo;
  70403. if (!this.spatialSound) {
  70404. this.spatialSound = true;
  70405. this._createSpatialParameters();
  70406. if (this.isPlaying && this.loop) {
  70407. this.stop();
  70408. this.play();
  70409. }
  70410. }
  70411. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  70412. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  70413. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  70414. };
  70415. /**
  70416. * Detach the sound from the previously attached mesh
  70417. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  70418. */
  70419. Sound.prototype.detachFromMesh = function () {
  70420. if (this._connectedMesh && this._registerFunc) {
  70421. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  70422. this._registerFunc = null;
  70423. this._connectedMesh = null;
  70424. }
  70425. };
  70426. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  70427. if (!node.getBoundingInfo) {
  70428. return;
  70429. }
  70430. var mesh = node;
  70431. if (this._positionInEmitterSpace) {
  70432. mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
  70433. this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
  70434. }
  70435. else {
  70436. var boundingInfo = mesh.getBoundingInfo();
  70437. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  70438. }
  70439. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  70440. this._updateDirection();
  70441. }
  70442. };
  70443. /**
  70444. * Clone the current sound in the scene.
  70445. * @returns the new sound clone
  70446. */
  70447. Sound.prototype.clone = function () {
  70448. var _this = this;
  70449. if (!this._streaming) {
  70450. var setBufferAndRun = function () {
  70451. if (_this._isReadyToPlay) {
  70452. clonedSound._audioBuffer = _this.getAudioBuffer();
  70453. clonedSound._isReadyToPlay = true;
  70454. if (clonedSound.autoplay) {
  70455. clonedSound.play();
  70456. }
  70457. }
  70458. else {
  70459. window.setTimeout(setBufferAndRun, 300);
  70460. }
  70461. };
  70462. var currentOptions = {
  70463. autoplay: this.autoplay, loop: this.loop,
  70464. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  70465. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  70466. refDistance: this.refDistance, distanceModel: this.distanceModel
  70467. };
  70468. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  70469. if (this.useCustomAttenuation) {
  70470. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  70471. }
  70472. clonedSound.setPosition(this._position);
  70473. clonedSound.setPlaybackRate(this._playbackRate);
  70474. setBufferAndRun();
  70475. return clonedSound;
  70476. }
  70477. // Can't clone a streaming sound
  70478. else {
  70479. return null;
  70480. }
  70481. };
  70482. /**
  70483. * Gets the current underlying audio buffer containing the data
  70484. * @returns the audio buffer
  70485. */
  70486. Sound.prototype.getAudioBuffer = function () {
  70487. return this._audioBuffer;
  70488. };
  70489. /**
  70490. * Serializes the Sound in a JSON representation
  70491. * @returns the JSON representation of the sound
  70492. */
  70493. Sound.prototype.serialize = function () {
  70494. var serializationObject = {
  70495. name: this.name,
  70496. url: this.name,
  70497. autoplay: this.autoplay,
  70498. loop: this.loop,
  70499. volume: this._volume,
  70500. spatialSound: this.spatialSound,
  70501. maxDistance: this.maxDistance,
  70502. rolloffFactor: this.rolloffFactor,
  70503. refDistance: this.refDistance,
  70504. distanceModel: this.distanceModel,
  70505. playbackRate: this._playbackRate,
  70506. panningModel: this._panningModel,
  70507. soundTrackId: this.soundTrackId
  70508. };
  70509. if (this.spatialSound) {
  70510. if (this._connectedMesh) {
  70511. serializationObject.connectedMeshId = this._connectedMesh.id;
  70512. }
  70513. serializationObject.position = this._position.asArray();
  70514. serializationObject.refDistance = this.refDistance;
  70515. serializationObject.distanceModel = this.distanceModel;
  70516. serializationObject.isDirectional = this._isDirectional;
  70517. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  70518. serializationObject.coneInnerAngle = this._coneInnerAngle;
  70519. serializationObject.coneOuterAngle = this._coneOuterAngle;
  70520. serializationObject.coneOuterGain = this._coneOuterGain;
  70521. }
  70522. return serializationObject;
  70523. };
  70524. /**
  70525. * Parse a JSON representation of a sound to innstantiate in a given scene
  70526. * @param parsedSound Define the JSON representation of the sound (usually coming from the serialize method)
  70527. * @param scene Define the scene the new parsed sound should be created in
  70528. * @param rootUrl Define the rooturl of the load in case we need to fetch relative dependencies
  70529. * @param sourceSound Define a cound place holder if do not need to instantiate a new one
  70530. * @returns the newly parsed sound
  70531. */
  70532. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  70533. var soundName = parsedSound.name;
  70534. var soundUrl;
  70535. if (parsedSound.url) {
  70536. soundUrl = rootUrl + parsedSound.url;
  70537. }
  70538. else {
  70539. soundUrl = rootUrl + soundName;
  70540. }
  70541. var options = {
  70542. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  70543. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  70544. rolloffFactor: parsedSound.rolloffFactor,
  70545. refDistance: parsedSound.refDistance,
  70546. distanceModel: parsedSound.distanceModel,
  70547. playbackRate: parsedSound.playbackRate
  70548. };
  70549. var newSound;
  70550. if (!sourceSound) {
  70551. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  70552. scene._addPendingData(newSound);
  70553. }
  70554. else {
  70555. var setBufferAndRun = function () {
  70556. if (sourceSound._isReadyToPlay) {
  70557. newSound._audioBuffer = sourceSound.getAudioBuffer();
  70558. newSound._isReadyToPlay = true;
  70559. if (newSound.autoplay) {
  70560. newSound.play();
  70561. }
  70562. }
  70563. else {
  70564. window.setTimeout(setBufferAndRun, 300);
  70565. }
  70566. };
  70567. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  70568. setBufferAndRun();
  70569. }
  70570. if (parsedSound.position) {
  70571. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  70572. newSound.setPosition(soundPosition);
  70573. }
  70574. if (parsedSound.isDirectional) {
  70575. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  70576. if (parsedSound.localDirectionToMesh) {
  70577. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  70578. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  70579. }
  70580. }
  70581. if (parsedSound.connectedMeshId) {
  70582. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  70583. if (connectedMesh) {
  70584. newSound.attachToMesh(connectedMesh);
  70585. }
  70586. }
  70587. return newSound;
  70588. };
  70589. return Sound;
  70590. }());
  70591. BABYLON.Sound = Sound;
  70592. })(BABYLON || (BABYLON = {}));
  70593. //# sourceMappingURL=babylon.sound.js.map
  70594. var BABYLON;
  70595. (function (BABYLON) {
  70596. /**
  70597. * It could be useful to isolate your music & sounds on several tracks to better manage volume on a grouped instance of sounds.
  70598. * It will be also used in a future release to apply effects on a specific track.
  70599. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  70600. */
  70601. var SoundTrack = /** @class */ (function () {
  70602. /**
  70603. * Creates a new sound track.
  70604. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  70605. * @param scene Define the scene the sound track belongs to
  70606. * @param options
  70607. */
  70608. function SoundTrack(scene, options) {
  70609. if (options === void 0) { options = {}; }
  70610. /**
  70611. * The unique identifier of the sound track in the scene.
  70612. */
  70613. this.id = -1;
  70614. this._isMainTrack = false;
  70615. this._isInitialized = false;
  70616. this._scene = scene;
  70617. this.soundCollection = new Array();
  70618. this._options = options;
  70619. if (!this._isMainTrack && this._scene.soundTracks) {
  70620. this._scene.soundTracks.push(this);
  70621. this.id = this._scene.soundTracks.length - 1;
  70622. }
  70623. }
  70624. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  70625. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  70626. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  70627. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  70628. if (this._options) {
  70629. if (this._options.volume) {
  70630. this._outputAudioNode.gain.value = this._options.volume;
  70631. }
  70632. if (this._options.mainTrack) {
  70633. this._isMainTrack = this._options.mainTrack;
  70634. }
  70635. }
  70636. this._isInitialized = true;
  70637. }
  70638. };
  70639. /**
  70640. * Release the sound track and its associated resources
  70641. */
  70642. SoundTrack.prototype.dispose = function () {
  70643. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  70644. if (this._connectedAnalyser) {
  70645. this._connectedAnalyser.stopDebugCanvas();
  70646. }
  70647. while (this.soundCollection.length) {
  70648. this.soundCollection[0].dispose();
  70649. }
  70650. if (this._outputAudioNode) {
  70651. this._outputAudioNode.disconnect();
  70652. }
  70653. this._outputAudioNode = null;
  70654. }
  70655. };
  70656. /**
  70657. * Adds a sound to this sound track
  70658. * @param sound define the cound to add
  70659. * @ignoreNaming
  70660. */
  70661. SoundTrack.prototype.AddSound = function (sound) {
  70662. if (!this._isInitialized) {
  70663. this._initializeSoundTrackAudioGraph();
  70664. }
  70665. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  70666. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  70667. }
  70668. if (sound.soundTrackId) {
  70669. if (sound.soundTrackId === -1) {
  70670. this._scene.mainSoundTrack.RemoveSound(sound);
  70671. }
  70672. else if (this._scene.soundTracks) {
  70673. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  70674. }
  70675. }
  70676. this.soundCollection.push(sound);
  70677. sound.soundTrackId = this.id;
  70678. };
  70679. /**
  70680. * Removes a sound to this sound track
  70681. * @param sound define the cound to remove
  70682. * @ignoreNaming
  70683. */
  70684. SoundTrack.prototype.RemoveSound = function (sound) {
  70685. var index = this.soundCollection.indexOf(sound);
  70686. if (index !== -1) {
  70687. this.soundCollection.splice(index, 1);
  70688. }
  70689. };
  70690. /**
  70691. * Set a global volume for the full sound track.
  70692. * @param newVolume Define the new volume of the sound track
  70693. */
  70694. SoundTrack.prototype.setVolume = function (newVolume) {
  70695. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  70696. this._outputAudioNode.gain.value = newVolume;
  70697. }
  70698. };
  70699. /**
  70700. * Switch the panning model to HRTF:
  70701. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  70702. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  70703. */
  70704. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  70705. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  70706. for (var i = 0; i < this.soundCollection.length; i++) {
  70707. this.soundCollection[i].switchPanningModelToHRTF();
  70708. }
  70709. }
  70710. };
  70711. /**
  70712. * Switch the panning model to Equal Power:
  70713. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  70714. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  70715. */
  70716. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  70717. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  70718. for (var i = 0; i < this.soundCollection.length; i++) {
  70719. this.soundCollection[i].switchPanningModelToEqualPower();
  70720. }
  70721. }
  70722. };
  70723. /**
  70724. * Connect the sound track to an audio analyser allowing some amazing
  70725. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  70726. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  70727. * @param analyser The analyser to connect to the engine
  70728. */
  70729. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  70730. if (this._connectedAnalyser) {
  70731. this._connectedAnalyser.stopDebugCanvas();
  70732. }
  70733. this._connectedAnalyser = analyser;
  70734. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  70735. this._outputAudioNode.disconnect();
  70736. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  70737. }
  70738. };
  70739. return SoundTrack;
  70740. }());
  70741. BABYLON.SoundTrack = SoundTrack;
  70742. })(BABYLON || (BABYLON = {}));
  70743. //# sourceMappingURL=babylon.soundtrack.js.map
  70744. var BABYLON;
  70745. (function (BABYLON) {
  70746. /**
  70747. * Class used to work with sound analyzer using fast fourier transform (FFT)
  70748. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  70749. */
  70750. var Analyser = /** @class */ (function () {
  70751. /**
  70752. * Creates a new analyser
  70753. * @param scene defines hosting scene
  70754. */
  70755. function Analyser(scene) {
  70756. /**
  70757. * Gets or sets the smoothing
  70758. * @ignorenaming
  70759. */
  70760. this.SMOOTHING = 0.75;
  70761. /**
  70762. * Gets or sets the FFT table size
  70763. * @ignorenaming
  70764. */
  70765. this.FFT_SIZE = 512;
  70766. /**
  70767. * Gets or sets the bar graph amplitude
  70768. * @ignorenaming
  70769. */
  70770. this.BARGRAPHAMPLITUDE = 256;
  70771. /**
  70772. * Gets or sets the position of the debug canvas
  70773. * @ignorenaming
  70774. */
  70775. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  70776. /**
  70777. * Gets or sets the debug canvas size
  70778. * @ignorenaming
  70779. */
  70780. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  70781. this._scene = scene;
  70782. this._audioEngine = BABYLON.Engine.audioEngine;
  70783. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  70784. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  70785. this._webAudioAnalyser.minDecibels = -140;
  70786. this._webAudioAnalyser.maxDecibels = 0;
  70787. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  70788. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  70789. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  70790. }
  70791. }
  70792. /**
  70793. * Get the number of data values you will have to play with for the visualization
  70794. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  70795. * @returns a number
  70796. */
  70797. Analyser.prototype.getFrequencyBinCount = function () {
  70798. if (this._audioEngine.canUseWebAudio) {
  70799. return this._webAudioAnalyser.frequencyBinCount;
  70800. }
  70801. else {
  70802. return 0;
  70803. }
  70804. };
  70805. /**
  70806. * Gets the current frequency data as a byte array
  70807. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  70808. * @returns a Uint8Array
  70809. */
  70810. Analyser.prototype.getByteFrequencyData = function () {
  70811. if (this._audioEngine.canUseWebAudio) {
  70812. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  70813. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  70814. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  70815. }
  70816. return this._byteFreqs;
  70817. };
  70818. /**
  70819. * Gets the current waveform as a byte array
  70820. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  70821. * @returns a Uint8Array
  70822. */
  70823. Analyser.prototype.getByteTimeDomainData = function () {
  70824. if (this._audioEngine.canUseWebAudio) {
  70825. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  70826. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  70827. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  70828. }
  70829. return this._byteTime;
  70830. };
  70831. /**
  70832. * Gets the current frequency data as a float array
  70833. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  70834. * @returns a Float32Array
  70835. */
  70836. Analyser.prototype.getFloatFrequencyData = function () {
  70837. if (this._audioEngine.canUseWebAudio) {
  70838. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  70839. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  70840. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  70841. }
  70842. return this._floatFreqs;
  70843. };
  70844. /**
  70845. * Renders the debug canvas
  70846. */
  70847. Analyser.prototype.drawDebugCanvas = function () {
  70848. var _this = this;
  70849. if (this._audioEngine.canUseWebAudio) {
  70850. if (!this._debugCanvas) {
  70851. this._debugCanvas = document.createElement("canvas");
  70852. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  70853. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  70854. this._debugCanvas.style.position = "absolute";
  70855. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  70856. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  70857. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  70858. document.body.appendChild(this._debugCanvas);
  70859. this._registerFunc = function () {
  70860. _this.drawDebugCanvas();
  70861. };
  70862. this._scene.registerBeforeRender(this._registerFunc);
  70863. }
  70864. if (this._registerFunc && this._debugCanvasContext) {
  70865. var workingArray = this.getByteFrequencyData();
  70866. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  70867. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  70868. // Draw the frequency domain chart.
  70869. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  70870. var value = workingArray[i];
  70871. var percent = value / this.BARGRAPHAMPLITUDE;
  70872. var height = this.DEBUGCANVASSIZE.height * percent;
  70873. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  70874. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  70875. var hue = i / this.getFrequencyBinCount() * 360;
  70876. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  70877. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  70878. }
  70879. }
  70880. }
  70881. };
  70882. /**
  70883. * Stops rendering the debug canvas and removes it
  70884. */
  70885. Analyser.prototype.stopDebugCanvas = function () {
  70886. if (this._debugCanvas) {
  70887. if (this._registerFunc) {
  70888. this._scene.unregisterBeforeRender(this._registerFunc);
  70889. this._registerFunc = null;
  70890. }
  70891. document.body.removeChild(this._debugCanvas);
  70892. this._debugCanvas = null;
  70893. this._debugCanvasContext = null;
  70894. }
  70895. };
  70896. /**
  70897. * Connects two audio nodes
  70898. * @param inputAudioNode defines first node to connect
  70899. * @param outputAudioNode defines second node to connect
  70900. */
  70901. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  70902. if (this._audioEngine.canUseWebAudio) {
  70903. inputAudioNode.connect(this._webAudioAnalyser);
  70904. this._webAudioAnalyser.connect(outputAudioNode);
  70905. }
  70906. };
  70907. /**
  70908. * Releases all associated resources
  70909. */
  70910. Analyser.prototype.dispose = function () {
  70911. if (this._audioEngine.canUseWebAudio) {
  70912. this._webAudioAnalyser.disconnect();
  70913. }
  70914. };
  70915. return Analyser;
  70916. }());
  70917. BABYLON.Analyser = Analyser;
  70918. })(BABYLON || (BABYLON = {}));
  70919. //# sourceMappingURL=babylon.analyser.js.map
  70920. var BABYLON;
  70921. (function (BABYLON) {
  70922. /**
  70923. * Wraps one or more Sound objects and selects one with random weight for playback.
  70924. */
  70925. var WeightedSound = /** @class */ (function () {
  70926. /**
  70927. * Creates a new WeightedSound from the list of sounds given.
  70928. * @param loop When true a Sound will be selected and played when the current playing Sound completes.
  70929. * @param sounds Array of Sounds that will be selected from.
  70930. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
  70931. */
  70932. function WeightedSound(loop, sounds, weights) {
  70933. var _this = this;
  70934. /** When true a Sound will be selected and played when the current playing Sound completes. */
  70935. this.loop = false;
  70936. this._coneInnerAngle = 360;
  70937. this._coneOuterAngle = 360;
  70938. this._volume = 1;
  70939. /** A Sound is currently playing. */
  70940. this.isPlaying = false;
  70941. /** A Sound is currently paused. */
  70942. this.isPaused = false;
  70943. this._sounds = [];
  70944. this._weights = [];
  70945. if (sounds.length !== weights.length) {
  70946. throw new Error('Sounds length does not equal weights length');
  70947. }
  70948. this.loop = loop;
  70949. this._weights = weights;
  70950. // Normalize the weights
  70951. var weightSum = 0;
  70952. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  70953. var weight = weights_1[_i];
  70954. weightSum += weight;
  70955. }
  70956. var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
  70957. for (var i = 0; i < this._weights.length; i++) {
  70958. this._weights[i] *= invWeightSum;
  70959. }
  70960. this._sounds = sounds;
  70961. for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
  70962. var sound = _b[_a];
  70963. sound.onEndedObservable.add(function () { _this._onended(); });
  70964. }
  70965. }
  70966. Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
  70967. /**
  70968. * The size of cone in degrees for a directional sound in which there will be no attenuation.
  70969. */
  70970. get: function () {
  70971. return this._coneInnerAngle;
  70972. },
  70973. /**
  70974. * The size of cone in degress for a directional sound in which there will be no attenuation.
  70975. */
  70976. set: function (value) {
  70977. if (value !== this._coneInnerAngle) {
  70978. if (this._coneOuterAngle < value) {
  70979. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  70980. return;
  70981. }
  70982. this._coneInnerAngle = value;
  70983. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  70984. var sound = _a[_i];
  70985. sound.directionalConeInnerAngle = value;
  70986. }
  70987. }
  70988. },
  70989. enumerable: true,
  70990. configurable: true
  70991. });
  70992. Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
  70993. /**
  70994. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  70995. * Listener angles between innerAngle and outerAngle will falloff linearly.
  70996. */
  70997. get: function () {
  70998. return this._coneOuterAngle;
  70999. },
  71000. /**
  71001. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  71002. * Listener angles between innerAngle and outerAngle will falloff linearly.
  71003. */
  71004. set: function (value) {
  71005. if (value !== this._coneOuterAngle) {
  71006. if (value < this._coneInnerAngle) {
  71007. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  71008. return;
  71009. }
  71010. this._coneOuterAngle = value;
  71011. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  71012. var sound = _a[_i];
  71013. sound.directionalConeOuterAngle = value;
  71014. }
  71015. }
  71016. },
  71017. enumerable: true,
  71018. configurable: true
  71019. });
  71020. Object.defineProperty(WeightedSound.prototype, "volume", {
  71021. /**
  71022. * Playback volume.
  71023. */
  71024. get: function () {
  71025. return this._volume;
  71026. },
  71027. /**
  71028. * Playback volume.
  71029. */
  71030. set: function (value) {
  71031. if (value !== this._volume) {
  71032. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  71033. var sound = _a[_i];
  71034. sound.setVolume(value);
  71035. }
  71036. }
  71037. },
  71038. enumerable: true,
  71039. configurable: true
  71040. });
  71041. WeightedSound.prototype._onended = function () {
  71042. if (this._currentIndex !== undefined) {
  71043. this._sounds[this._currentIndex].autoplay = false;
  71044. }
  71045. if (this.loop && this.isPlaying) {
  71046. this.play();
  71047. }
  71048. else {
  71049. this.isPlaying = false;
  71050. }
  71051. };
  71052. /**
  71053. * Suspend playback
  71054. */
  71055. WeightedSound.prototype.pause = function () {
  71056. this.isPaused = true;
  71057. if (this._currentIndex !== undefined) {
  71058. this._sounds[this._currentIndex].pause();
  71059. }
  71060. };
  71061. /**
  71062. * Stop playback
  71063. */
  71064. WeightedSound.prototype.stop = function () {
  71065. this.isPlaying = false;
  71066. if (this._currentIndex !== undefined) {
  71067. this._sounds[this._currentIndex].stop();
  71068. }
  71069. };
  71070. /**
  71071. * Start playback.
  71072. * @param startOffset Position the clip head at a specific time in seconds.
  71073. */
  71074. WeightedSound.prototype.play = function (startOffset) {
  71075. if (!this.isPaused) {
  71076. this.stop();
  71077. var randomValue = Math.random();
  71078. var total = 0;
  71079. for (var i = 0; i < this._weights.length; i++) {
  71080. total += this._weights[i];
  71081. if (randomValue <= total) {
  71082. this._currentIndex = i;
  71083. break;
  71084. }
  71085. }
  71086. }
  71087. var sound = this._sounds[this._currentIndex];
  71088. if (sound.isReady()) {
  71089. sound.play(0, this.isPaused ? undefined : startOffset);
  71090. }
  71091. else {
  71092. sound.autoplay = true;
  71093. }
  71094. this.isPlaying = true;
  71095. this.isPaused = false;
  71096. };
  71097. return WeightedSound;
  71098. }());
  71099. BABYLON.WeightedSound = WeightedSound;
  71100. })(BABYLON || (BABYLON = {}));
  71101. //# sourceMappingURL=babylon.weightedsound.js.map
  71102. var BABYLON;
  71103. (function (BABYLON) {
  71104. // Adds the parser to the scene parsers.
  71105. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_AUDIO, function (parsedData, scene, container, rootUrl) {
  71106. // TODO: add sound
  71107. var loadedSounds = [];
  71108. var loadedSound;
  71109. container.sounds = container.sounds || [];
  71110. if (parsedData.sounds !== undefined && parsedData.sounds !== null) {
  71111. for (var index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  71112. var parsedSound = parsedData.sounds[index];
  71113. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  71114. if (!parsedSound.url) {
  71115. parsedSound.url = parsedSound.name;
  71116. }
  71117. if (!loadedSounds[parsedSound.url]) {
  71118. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  71119. loadedSounds[parsedSound.url] = loadedSound;
  71120. container.sounds.push(loadedSound);
  71121. }
  71122. else {
  71123. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  71124. }
  71125. }
  71126. else {
  71127. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  71128. }
  71129. }
  71130. }
  71131. loadedSounds = [];
  71132. });
  71133. Object.defineProperty(BABYLON.Scene.prototype, "mainSoundTrack", {
  71134. get: function () {
  71135. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  71136. if (!compo) {
  71137. compo = new AudioSceneComponent(this);
  71138. this._addComponent(compo);
  71139. }
  71140. if (!this._mainSoundTrack) {
  71141. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  71142. }
  71143. return this._mainSoundTrack;
  71144. },
  71145. enumerable: true,
  71146. configurable: true
  71147. });
  71148. BABYLON.Scene.prototype.getSoundByName = function (name) {
  71149. var index;
  71150. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  71151. if (this.mainSoundTrack.soundCollection[index].name === name) {
  71152. return this.mainSoundTrack.soundCollection[index];
  71153. }
  71154. }
  71155. if (this.soundTracks) {
  71156. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  71157. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  71158. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  71159. return this.soundTracks[sdIndex].soundCollection[index];
  71160. }
  71161. }
  71162. }
  71163. }
  71164. return null;
  71165. };
  71166. Object.defineProperty(BABYLON.Scene.prototype, "audioEnabled", {
  71167. get: function () {
  71168. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  71169. if (!compo) {
  71170. compo = new AudioSceneComponent(this);
  71171. this._addComponent(compo);
  71172. }
  71173. return compo.audioEnabled;
  71174. },
  71175. set: function (value) {
  71176. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  71177. if (!compo) {
  71178. compo = new AudioSceneComponent(this);
  71179. this._addComponent(compo);
  71180. }
  71181. if (value) {
  71182. compo.enableAudio();
  71183. }
  71184. else {
  71185. compo.disableAudio();
  71186. }
  71187. },
  71188. enumerable: true,
  71189. configurable: true
  71190. });
  71191. Object.defineProperty(BABYLON.Scene.prototype, "headphone", {
  71192. get: function () {
  71193. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  71194. if (!compo) {
  71195. compo = new AudioSceneComponent(this);
  71196. this._addComponent(compo);
  71197. }
  71198. return compo.headphone;
  71199. },
  71200. set: function (value) {
  71201. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  71202. if (!compo) {
  71203. compo = new AudioSceneComponent(this);
  71204. this._addComponent(compo);
  71205. }
  71206. if (value) {
  71207. compo.switchAudioModeForHeadphones();
  71208. }
  71209. else {
  71210. compo.switchAudioModeForNormalSpeakers();
  71211. }
  71212. },
  71213. enumerable: true,
  71214. configurable: true
  71215. });
  71216. /**
  71217. * Defines the sound scene component responsible to manage any sounds
  71218. * in a given scene.
  71219. */
  71220. var AudioSceneComponent = /** @class */ (function () {
  71221. /**
  71222. * Creates a new instance of the component for the given scene
  71223. * @param scene Defines the scene to register the component in
  71224. */
  71225. function AudioSceneComponent(scene) {
  71226. /**
  71227. * The component name helpfull to identify the component in the list of scene components.
  71228. */
  71229. this.name = BABYLON.SceneComponentConstants.NAME_AUDIO;
  71230. this._audioEnabled = true;
  71231. this._headphone = false;
  71232. this.scene = scene;
  71233. scene.soundTracks = new Array();
  71234. scene.sounds = new Array();
  71235. }
  71236. Object.defineProperty(AudioSceneComponent.prototype, "audioEnabled", {
  71237. /**
  71238. * Gets whether audio is enabled or not.
  71239. * Please use related enable/disable method to switch state.
  71240. */
  71241. get: function () {
  71242. return this._audioEnabled;
  71243. },
  71244. enumerable: true,
  71245. configurable: true
  71246. });
  71247. Object.defineProperty(AudioSceneComponent.prototype, "headphone", {
  71248. /**
  71249. * Gets whether audio is outputing to headphone or not.
  71250. * Please use the according Switch methods to change output.
  71251. */
  71252. get: function () {
  71253. return this._headphone;
  71254. },
  71255. enumerable: true,
  71256. configurable: true
  71257. });
  71258. /**
  71259. * Registers the component in a given scene
  71260. */
  71261. AudioSceneComponent.prototype.register = function () {
  71262. this.scene._afterRenderStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDER_AUDIO, this, this._afterRender);
  71263. };
  71264. /**
  71265. * Rebuilds the elements related to this component in case of
  71266. * context lost for instance.
  71267. */
  71268. AudioSceneComponent.prototype.rebuild = function () {
  71269. // Nothing to do here. (Not rendering related)
  71270. };
  71271. /**
  71272. * Serializes the component data to the specified json object
  71273. * @param serializationObject The object to serialize to
  71274. */
  71275. AudioSceneComponent.prototype.serialize = function (serializationObject) {
  71276. serializationObject.sounds = [];
  71277. if (this.scene.soundTracks) {
  71278. for (var index = 0; index < this.scene.soundTracks.length; index++) {
  71279. var soundtrack = this.scene.soundTracks[index];
  71280. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  71281. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  71282. }
  71283. }
  71284. }
  71285. };
  71286. /**
  71287. * Adds all the element from the container to the scene
  71288. * @param container the container holding the elements
  71289. */
  71290. AudioSceneComponent.prototype.addFromContainer = function (container) {
  71291. var _this = this;
  71292. if (!container.sounds) {
  71293. return;
  71294. }
  71295. container.sounds.forEach(function (sound) {
  71296. sound.play();
  71297. sound.autoplay = true;
  71298. _this.scene.mainSoundTrack.AddSound(sound);
  71299. });
  71300. };
  71301. /**
  71302. * Removes all the elements in the container from the scene
  71303. * @param container contains the elements to remove
  71304. */
  71305. AudioSceneComponent.prototype.removeFromContainer = function (container) {
  71306. var _this = this;
  71307. if (!container.sounds) {
  71308. return;
  71309. }
  71310. container.sounds.forEach(function (sound) {
  71311. sound.stop();
  71312. sound.autoplay = false;
  71313. _this.scene.mainSoundTrack.RemoveSound(sound);
  71314. });
  71315. };
  71316. /**
  71317. * Disposes the component and the associated ressources.
  71318. */
  71319. AudioSceneComponent.prototype.dispose = function () {
  71320. var scene = this.scene;
  71321. if (scene._mainSoundTrack) {
  71322. scene.mainSoundTrack.dispose();
  71323. }
  71324. if (scene.soundTracks) {
  71325. for (var scIndex = 0; scIndex < scene.soundTracks.length; scIndex++) {
  71326. scene.soundTracks[scIndex].dispose();
  71327. }
  71328. }
  71329. };
  71330. /**
  71331. * Disables audio in the associated scene.
  71332. */
  71333. AudioSceneComponent.prototype.disableAudio = function () {
  71334. var scene = this.scene;
  71335. this._audioEnabled = false;
  71336. var i;
  71337. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  71338. scene.mainSoundTrack.soundCollection[i].pause();
  71339. }
  71340. if (scene.soundTracks) {
  71341. for (i = 0; i < scene.soundTracks.length; i++) {
  71342. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  71343. scene.soundTracks[i].soundCollection[j].pause();
  71344. }
  71345. }
  71346. }
  71347. };
  71348. /**
  71349. * Enables audio in the associated scene.
  71350. */
  71351. AudioSceneComponent.prototype.enableAudio = function () {
  71352. var scene = this.scene;
  71353. this._audioEnabled = true;
  71354. var i;
  71355. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  71356. if (scene.mainSoundTrack.soundCollection[i].isPaused) {
  71357. scene.mainSoundTrack.soundCollection[i].play();
  71358. }
  71359. }
  71360. if (scene.soundTracks) {
  71361. for (i = 0; i < scene.soundTracks.length; i++) {
  71362. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  71363. if (scene.soundTracks[i].soundCollection[j].isPaused) {
  71364. scene.soundTracks[i].soundCollection[j].play();
  71365. }
  71366. }
  71367. }
  71368. }
  71369. };
  71370. /**
  71371. * Switch audio to headphone output.
  71372. */
  71373. AudioSceneComponent.prototype.switchAudioModeForHeadphones = function () {
  71374. var scene = this.scene;
  71375. this._headphone = true;
  71376. scene.mainSoundTrack.switchPanningModelToHRTF();
  71377. if (scene.soundTracks) {
  71378. for (var i = 0; i < scene.soundTracks.length; i++) {
  71379. scene.soundTracks[i].switchPanningModelToHRTF();
  71380. }
  71381. }
  71382. };
  71383. /**
  71384. * Switch audio to normal speakers.
  71385. */
  71386. AudioSceneComponent.prototype.switchAudioModeForNormalSpeakers = function () {
  71387. var scene = this.scene;
  71388. this._headphone = false;
  71389. scene.mainSoundTrack.switchPanningModelToEqualPower();
  71390. if (scene.soundTracks) {
  71391. for (var i = 0; i < scene.soundTracks.length; i++) {
  71392. scene.soundTracks[i].switchPanningModelToEqualPower();
  71393. }
  71394. }
  71395. };
  71396. AudioSceneComponent.prototype._afterRender = function () {
  71397. var scene = this.scene;
  71398. if (!this._audioEnabled || !scene._mainSoundTrack || !scene.soundTracks || (scene._mainSoundTrack.soundCollection.length === 0 && scene.soundTracks.length === 1)) {
  71399. return;
  71400. }
  71401. var listeningCamera;
  71402. var audioEngine = BABYLON.Engine.audioEngine;
  71403. if (scene.activeCameras.length > 0) {
  71404. listeningCamera = scene.activeCameras[0];
  71405. }
  71406. else {
  71407. listeningCamera = scene.activeCamera;
  71408. }
  71409. if (listeningCamera && audioEngine.audioContext) {
  71410. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  71411. // for VR cameras
  71412. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  71413. listeningCamera = listeningCamera.rigCameras[0];
  71414. }
  71415. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  71416. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  71417. cameraDirection.normalize();
  71418. // To avoid some errors on GearVR
  71419. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  71420. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  71421. }
  71422. var i;
  71423. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  71424. var sound = scene.mainSoundTrack.soundCollection[i];
  71425. if (sound.useCustomAttenuation) {
  71426. sound.updateDistanceFromListener();
  71427. }
  71428. }
  71429. if (scene.soundTracks) {
  71430. for (i = 0; i < scene.soundTracks.length; i++) {
  71431. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  71432. sound = scene.soundTracks[i].soundCollection[j];
  71433. if (sound.useCustomAttenuation) {
  71434. sound.updateDistanceFromListener();
  71435. }
  71436. }
  71437. }
  71438. }
  71439. }
  71440. };
  71441. return AudioSceneComponent;
  71442. }());
  71443. BABYLON.AudioSceneComponent = AudioSceneComponent;
  71444. })(BABYLON || (BABYLON = {}));
  71445. //# sourceMappingURL=babylon.audioSceneComponent.js.map
  71446. var BABYLON;
  71447. (function (BABYLON) {
  71448. /**
  71449. * This defines an action helpful to play a defined sound on a triggered action.
  71450. */
  71451. var PlaySoundAction = /** @class */ (function (_super) {
  71452. __extends(PlaySoundAction, _super);
  71453. /**
  71454. * Instantiate the action
  71455. * @param triggerOptions defines the trigger options
  71456. * @param sound defines the sound to play
  71457. * @param condition defines the trigger related conditions
  71458. */
  71459. function PlaySoundAction(triggerOptions, sound, condition) {
  71460. var _this = _super.call(this, triggerOptions, condition) || this;
  71461. _this._sound = sound;
  71462. return _this;
  71463. }
  71464. /** @hidden */
  71465. PlaySoundAction.prototype._prepare = function () {
  71466. };
  71467. /**
  71468. * Execute the action and play the sound.
  71469. */
  71470. PlaySoundAction.prototype.execute = function () {
  71471. if (this._sound !== undefined) {
  71472. this._sound.play();
  71473. }
  71474. };
  71475. /**
  71476. * Serializes the actions and its related information.
  71477. * @param parent defines the object to serialize in
  71478. * @returns the serialized object
  71479. */
  71480. PlaySoundAction.prototype.serialize = function (parent) {
  71481. return _super.prototype._serialize.call(this, {
  71482. name: "PlaySoundAction",
  71483. properties: [{ name: "sound", value: this._sound.name }]
  71484. }, parent);
  71485. };
  71486. return PlaySoundAction;
  71487. }(BABYLON.Action));
  71488. BABYLON.PlaySoundAction = PlaySoundAction;
  71489. /**
  71490. * This defines an action helpful to stop a defined sound on a triggered action.
  71491. */
  71492. var StopSoundAction = /** @class */ (function (_super) {
  71493. __extends(StopSoundAction, _super);
  71494. /**
  71495. * Instantiate the action
  71496. * @param triggerOptions defines the trigger options
  71497. * @param sound defines the sound to stop
  71498. * @param condition defines the trigger related conditions
  71499. */
  71500. function StopSoundAction(triggerOptions, sound, condition) {
  71501. var _this = _super.call(this, triggerOptions, condition) || this;
  71502. _this._sound = sound;
  71503. return _this;
  71504. }
  71505. /** @hidden */
  71506. StopSoundAction.prototype._prepare = function () {
  71507. };
  71508. /**
  71509. * Execute the action and stop the sound.
  71510. */
  71511. StopSoundAction.prototype.execute = function () {
  71512. if (this._sound !== undefined) {
  71513. this._sound.stop();
  71514. }
  71515. };
  71516. /**
  71517. * Serializes the actions and its related information.
  71518. * @param parent defines the object to serialize in
  71519. * @returns the serialized object
  71520. */
  71521. StopSoundAction.prototype.serialize = function (parent) {
  71522. return _super.prototype._serialize.call(this, {
  71523. name: "StopSoundAction",
  71524. properties: [{ name: "sound", value: this._sound.name }]
  71525. }, parent);
  71526. };
  71527. return StopSoundAction;
  71528. }(BABYLON.Action));
  71529. BABYLON.StopSoundAction = StopSoundAction;
  71530. })(BABYLON || (BABYLON = {}));
  71531. //# sourceMappingURL=babylon.directAudioActions.js.map
  71532. var BABYLON;
  71533. (function (BABYLON) {
  71534. /**
  71535. * Class for creating a cube texture
  71536. */
  71537. var CubeTexture = /** @class */ (function (_super) {
  71538. __extends(CubeTexture, _super);
  71539. /**
  71540. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  71541. * as prefiltered data.
  71542. * @param rootUrl defines the url of the texture or the root name of the six images
  71543. * @param scene defines the scene the texture is attached to
  71544. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  71545. * @param noMipmap defines if mipmaps should be created or not
  71546. * @param files defines the six files to load for the different faces
  71547. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  71548. * @param onError defines a callback triggered in case of error during load
  71549. * @param format defines the internal format to use for the texture once loaded
  71550. * @param prefiltered defines whether or not the texture is created from prefiltered data
  71551. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  71552. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  71553. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  71554. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  71555. * @return the cube texture
  71556. */
  71557. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  71558. if (extensions === void 0) { extensions = null; }
  71559. if (noMipmap === void 0) { noMipmap = false; }
  71560. if (files === void 0) { files = null; }
  71561. if (onLoad === void 0) { onLoad = null; }
  71562. if (onError === void 0) { onError = null; }
  71563. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  71564. if (prefiltered === void 0) { prefiltered = false; }
  71565. if (forcedExtension === void 0) { forcedExtension = null; }
  71566. if (createPolynomials === void 0) { createPolynomials = false; }
  71567. if (lodScale === void 0) { lodScale = 0.8; }
  71568. if (lodOffset === void 0) { lodOffset = 0; }
  71569. var _this = _super.call(this, scene) || this;
  71570. /**
  71571. * Gets or sets the center of the bounding box associated with the cube texture.
  71572. * It must define where the camera used to render the texture was set
  71573. * @see http://doc.babylonjs.com/how_to/reflect#using-local-cubemap-mode
  71574. */
  71575. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  71576. _this._rotationY = 0;
  71577. /** @hidden */
  71578. _this._prefiltered = false;
  71579. _this.name = rootUrl;
  71580. _this.url = rootUrl;
  71581. _this._noMipmap = noMipmap;
  71582. _this.hasAlpha = false;
  71583. _this._format = format;
  71584. _this.isCube = true;
  71585. _this._textureMatrix = BABYLON.Matrix.Identity();
  71586. _this._createPolynomials = createPolynomials;
  71587. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  71588. if (!rootUrl && !files) {
  71589. return _this;
  71590. }
  71591. var lastDot = rootUrl.lastIndexOf(".");
  71592. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  71593. var isDDS = (extension === ".dds");
  71594. var isEnv = (extension === ".env");
  71595. if (isEnv) {
  71596. _this.gammaSpace = false;
  71597. _this._prefiltered = false;
  71598. }
  71599. else {
  71600. _this._prefiltered = prefiltered;
  71601. if (prefiltered) {
  71602. _this.gammaSpace = false;
  71603. }
  71604. }
  71605. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  71606. if (!files) {
  71607. if (!isEnv && !isDDS && !extensions) {
  71608. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  71609. }
  71610. files = [];
  71611. if (extensions) {
  71612. for (var index = 0; index < extensions.length; index++) {
  71613. files.push(rootUrl + extensions[index]);
  71614. }
  71615. }
  71616. }
  71617. _this._files = files;
  71618. if (!_this._texture) {
  71619. if (!scene.useDelayedTextureLoading) {
  71620. if (prefiltered) {
  71621. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  71622. }
  71623. else {
  71624. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  71625. }
  71626. }
  71627. else {
  71628. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  71629. }
  71630. }
  71631. else if (onLoad) {
  71632. if (_this._texture.isReady) {
  71633. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  71634. }
  71635. else {
  71636. _this._texture.onLoadedObservable.add(onLoad);
  71637. }
  71638. }
  71639. return _this;
  71640. }
  71641. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  71642. /**
  71643. * Returns the bounding box size
  71644. * @see http://doc.babylonjs.com/how_to/reflect#using-local-cubemap-mode
  71645. */
  71646. get: function () {
  71647. return this._boundingBoxSize;
  71648. },
  71649. /**
  71650. * Gets or sets the size of the bounding box associated with the cube texture
  71651. * When defined, the cubemap will switch to local mode
  71652. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  71653. * @example https://www.babylonjs-playground.com/#RNASML
  71654. */
  71655. set: function (value) {
  71656. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  71657. return;
  71658. }
  71659. this._boundingBoxSize = value;
  71660. var scene = this.getScene();
  71661. if (scene) {
  71662. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  71663. }
  71664. },
  71665. enumerable: true,
  71666. configurable: true
  71667. });
  71668. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  71669. /**
  71670. * Gets texture matrix rotation angle around Y axis radians.
  71671. */
  71672. get: function () {
  71673. return this._rotationY;
  71674. },
  71675. /**
  71676. * Sets texture matrix rotation angle around Y axis in radians.
  71677. */
  71678. set: function (value) {
  71679. this._rotationY = value;
  71680. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  71681. },
  71682. enumerable: true,
  71683. configurable: true
  71684. });
  71685. /**
  71686. * Creates a cube texture from an array of image urls
  71687. * @param files defines an array of image urls
  71688. * @param scene defines the hosting scene
  71689. * @param noMipmap specifies if mip maps are not used
  71690. * @returns a cube texture
  71691. */
  71692. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  71693. var rootUrlKey = "";
  71694. files.forEach(function (url) { return rootUrlKey += url; });
  71695. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  71696. };
  71697. /**
  71698. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  71699. * @param url defines the url of the prefiltered texture
  71700. * @param scene defines the scene the texture is attached to
  71701. * @param forcedExtension defines the extension of the file if different from the url
  71702. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  71703. * @return the prefiltered texture
  71704. */
  71705. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  71706. if (forcedExtension === void 0) { forcedExtension = null; }
  71707. if (createPolynomials === void 0) { createPolynomials = true; }
  71708. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  71709. };
  71710. /**
  71711. * Delays loading of the cube texture
  71712. */
  71713. CubeTexture.prototype.delayLoad = function () {
  71714. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  71715. return;
  71716. }
  71717. var scene = this.getScene();
  71718. if (!scene) {
  71719. return;
  71720. }
  71721. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  71722. this._texture = this._getFromCache(this.url, this._noMipmap);
  71723. if (!this._texture) {
  71724. if (this._prefiltered) {
  71725. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  71726. }
  71727. else {
  71728. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  71729. }
  71730. }
  71731. };
  71732. /**
  71733. * Returns the reflection texture matrix
  71734. * @returns the reflection texture matrix
  71735. */
  71736. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  71737. return this._textureMatrix;
  71738. };
  71739. /**
  71740. * Sets the reflection texture matrix
  71741. * @param value Reflection texture matrix
  71742. */
  71743. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  71744. this._textureMatrix = value;
  71745. };
  71746. /**
  71747. * Parses text to create a cube texture
  71748. * @param parsedTexture define the serialized text to read from
  71749. * @param scene defines the hosting scene
  71750. * @param rootUrl defines the root url of the cube texture
  71751. * @returns a cube texture
  71752. */
  71753. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  71754. var texture = BABYLON.SerializationHelper.Parse(function () {
  71755. var prefiltered = false;
  71756. if (parsedTexture.prefiltered) {
  71757. prefiltered = parsedTexture.prefiltered;
  71758. }
  71759. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  71760. }, parsedTexture, scene);
  71761. // Local Cubemaps
  71762. if (parsedTexture.boundingBoxPosition) {
  71763. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  71764. }
  71765. if (parsedTexture.boundingBoxSize) {
  71766. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  71767. }
  71768. // Animations
  71769. if (parsedTexture.animations) {
  71770. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  71771. var parsedAnimation = parsedTexture.animations[animationIndex];
  71772. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  71773. }
  71774. }
  71775. return texture;
  71776. };
  71777. /**
  71778. * Makes a clone, or deep copy, of the cube texture
  71779. * @returns a new cube texture
  71780. */
  71781. CubeTexture.prototype.clone = function () {
  71782. var _this = this;
  71783. return BABYLON.SerializationHelper.Clone(function () {
  71784. var scene = _this.getScene();
  71785. if (!scene) {
  71786. return _this;
  71787. }
  71788. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  71789. }, this);
  71790. };
  71791. __decorate([
  71792. BABYLON.serialize("rotationY")
  71793. ], CubeTexture.prototype, "rotationY", null);
  71794. return CubeTexture;
  71795. }(BABYLON.BaseTexture));
  71796. BABYLON.CubeTexture = CubeTexture;
  71797. })(BABYLON || (BABYLON = {}));
  71798. //# sourceMappingURL=babylon.cubeTexture.js.map
  71799. var BABYLON;
  71800. (function (BABYLON) {
  71801. /**
  71802. * Raw cube texture where the raw buffers are passed in
  71803. */
  71804. var RawCubeTexture = /** @class */ (function (_super) {
  71805. __extends(RawCubeTexture, _super);
  71806. /**
  71807. * Creates a cube texture where the raw buffers are passed in.
  71808. * @param scene defines the scene the texture is attached to
  71809. * @param data defines the array of data to use to create each face
  71810. * @param size defines the size of the textures
  71811. * @param format defines the format of the data
  71812. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  71813. * @param generateMipMaps defines if the engine should generate the mip levels
  71814. * @param invertY defines if data must be stored with Y axis inverted
  71815. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  71816. * @param compression defines the compression used (null by default)
  71817. */
  71818. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  71819. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  71820. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71821. if (generateMipMaps === void 0) { generateMipMaps = false; }
  71822. if (invertY === void 0) { invertY = false; }
  71823. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71824. if (compression === void 0) { compression = null; }
  71825. var _this = _super.call(this, "", scene) || this;
  71826. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  71827. return _this;
  71828. }
  71829. /**
  71830. * Updates the raw cube texture.
  71831. * @param data defines the data to store
  71832. * @param format defines the data format
  71833. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  71834. * @param invertY defines if data must be stored with Y axis inverted
  71835. * @param compression defines the compression used (null by default)
  71836. * @param level defines which level of the texture to update
  71837. */
  71838. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  71839. if (compression === void 0) { compression = null; }
  71840. if (level === void 0) { level = 0; }
  71841. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  71842. };
  71843. /**
  71844. * Updates a raw cube texture with RGBD encoded data.
  71845. * @param data defines the array of data [mipmap][face] to use to create each face
  71846. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  71847. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  71848. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  71849. * @returns a promsie that resolves when the operation is complete
  71850. */
  71851. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  71852. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  71853. if (lodScale === void 0) { lodScale = 0.8; }
  71854. if (lodOffset === void 0) { lodOffset = 0; }
  71855. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  71856. };
  71857. /**
  71858. * Clones the raw cube texture.
  71859. * @return a new cube texture
  71860. */
  71861. RawCubeTexture.prototype.clone = function () {
  71862. var _this = this;
  71863. return BABYLON.SerializationHelper.Clone(function () {
  71864. var scene = _this.getScene();
  71865. var internalTexture = _this._texture;
  71866. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  71867. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  71868. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  71869. }
  71870. return texture;
  71871. }, this);
  71872. };
  71873. /** @hidden */
  71874. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  71875. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  71876. internalTexture._bufferViewArrayArray = data;
  71877. internalTexture._lodGenerationScale = lodScale;
  71878. internalTexture._lodGenerationOffset = lodOffset;
  71879. internalTexture._sphericalPolynomial = sphericalPolynomial;
  71880. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  71881. internalTexture.isReady = true;
  71882. });
  71883. };
  71884. return RawCubeTexture;
  71885. }(BABYLON.CubeTexture));
  71886. BABYLON.RawCubeTexture = RawCubeTexture;
  71887. })(BABYLON || (BABYLON = {}));
  71888. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  71889. var BABYLON;
  71890. (function (BABYLON) {
  71891. /**
  71892. * This Helps creating a texture that will be created from a camera in your scene.
  71893. * It is basically a dynamic texture that could be used to create special effects for instance.
  71894. * Actually, It is the base of lot of effects in the framework like post process, shadows, effect layers and rendering pipelines...
  71895. */
  71896. var RenderTargetTexture = /** @class */ (function (_super) {
  71897. __extends(RenderTargetTexture, _super);
  71898. /**
  71899. * Instantiate a render target texture. This is mainly used to render of screen the scene to for instance apply post processse
  71900. * or used a shadow, depth texture...
  71901. * @param name The friendly name of the texture
  71902. * @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)
  71903. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  71904. * @param generateMipMaps True if mip maps need to be generated after render.
  71905. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  71906. * @param type The type of the buffer in the RTT (int, half float, float...)
  71907. * @param isCube True if a cube texture needs to be created
  71908. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  71909. * @param generateDepthBuffer True to generate a depth buffer
  71910. * @param generateStencilBuffer True to generate a stencil buffer
  71911. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  71912. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  71913. */
  71914. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  71915. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  71916. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71917. if (isCube === void 0) { isCube = false; }
  71918. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71919. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  71920. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  71921. if (isMulti === void 0) { isMulti = false; }
  71922. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  71923. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  71924. _this.isCube = isCube;
  71925. /**
  71926. * Define if particles should be rendered in your texture.
  71927. */
  71928. _this.renderParticles = true;
  71929. /**
  71930. * Define if sprites should be rendered in your texture.
  71931. */
  71932. _this.renderSprites = false;
  71933. /**
  71934. * Override the default coordinates mode to projection for RTT as it is the most common case for rendered textures.
  71935. */
  71936. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  71937. /**
  71938. * Define if the camera viewport should be respected while rendering the texture or if the render should be done to the entire texture.
  71939. */
  71940. _this.ignoreCameraViewport = false;
  71941. /**
  71942. * An event triggered when the texture is unbind.
  71943. */
  71944. _this.onBeforeBindObservable = new BABYLON.Observable();
  71945. /**
  71946. * An event triggered when the texture is unbind.
  71947. */
  71948. _this.onAfterUnbindObservable = new BABYLON.Observable();
  71949. /**
  71950. * An event triggered before rendering the texture
  71951. */
  71952. _this.onBeforeRenderObservable = new BABYLON.Observable();
  71953. /**
  71954. * An event triggered after rendering the texture
  71955. */
  71956. _this.onAfterRenderObservable = new BABYLON.Observable();
  71957. /**
  71958. * An event triggered after the texture clear
  71959. */
  71960. _this.onClearObservable = new BABYLON.Observable();
  71961. _this._currentRefreshId = -1;
  71962. _this._refreshRate = 1;
  71963. _this._samples = 1;
  71964. /**
  71965. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  71966. * It must define where the camera used to render the texture is set
  71967. */
  71968. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  71969. scene = _this.getScene();
  71970. if (!scene) {
  71971. return _this;
  71972. }
  71973. _this.renderList = new Array();
  71974. _this._engine = scene.getEngine();
  71975. _this.name = name;
  71976. _this.isRenderTarget = true;
  71977. _this._initialSizeParameter = size;
  71978. _this._processSizeParameter(size);
  71979. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  71980. });
  71981. _this._generateMipMaps = generateMipMaps ? true : false;
  71982. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  71983. // Rendering groups
  71984. _this._renderingManager = new BABYLON.RenderingManager(scene);
  71985. _this._renderingManager._useSceneAutoClearSetup = true;
  71986. if (isMulti) {
  71987. return _this;
  71988. }
  71989. _this._renderTargetOptions = {
  71990. generateMipMaps: generateMipMaps,
  71991. type: type,
  71992. format: format,
  71993. samplingMode: samplingMode,
  71994. generateDepthBuffer: generateDepthBuffer,
  71995. generateStencilBuffer: generateStencilBuffer
  71996. };
  71997. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  71998. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71999. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72000. }
  72001. if (isCube) {
  72002. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  72003. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  72004. _this._textureMatrix = BABYLON.Matrix.Identity();
  72005. }
  72006. else {
  72007. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  72008. }
  72009. return _this;
  72010. }
  72011. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  72012. /**
  72013. * Use this list to define the list of mesh you want to render.
  72014. */
  72015. get: function () {
  72016. return this._renderList;
  72017. },
  72018. set: function (value) {
  72019. this._renderList = value;
  72020. if (this._renderList) {
  72021. this._hookArray(this._renderList);
  72022. }
  72023. },
  72024. enumerable: true,
  72025. configurable: true
  72026. });
  72027. RenderTargetTexture.prototype._hookArray = function (array) {
  72028. var _this = this;
  72029. var oldPush = array.push;
  72030. array.push = function () {
  72031. var items = [];
  72032. for (var _i = 0; _i < arguments.length; _i++) {
  72033. items[_i] = arguments[_i];
  72034. }
  72035. var wasEmpty = array.length === 0;
  72036. var result = oldPush.apply(array, items);
  72037. if (wasEmpty) {
  72038. _this.getScene().meshes.forEach(function (mesh) {
  72039. mesh._markSubMeshesAsLightDirty();
  72040. });
  72041. }
  72042. return result;
  72043. };
  72044. var oldSplice = array.splice;
  72045. array.splice = function (index, deleteCount) {
  72046. var deleted = oldSplice.apply(array, [index, deleteCount]);
  72047. if (array.length === 0) {
  72048. _this.getScene().meshes.forEach(function (mesh) {
  72049. mesh._markSubMeshesAsLightDirty();
  72050. });
  72051. }
  72052. return deleted;
  72053. };
  72054. };
  72055. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  72056. /**
  72057. * Set a after unbind callback in the texture.
  72058. * This has been kept for backward compatibility and use of onAfterUnbindObservable is recommended.
  72059. */
  72060. set: function (callback) {
  72061. if (this._onAfterUnbindObserver) {
  72062. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  72063. }
  72064. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  72065. },
  72066. enumerable: true,
  72067. configurable: true
  72068. });
  72069. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  72070. /**
  72071. * Set a before render callback in the texture.
  72072. * This has been kept for backward compatibility and use of onBeforeRenderObservable is recommended.
  72073. */
  72074. set: function (callback) {
  72075. if (this._onBeforeRenderObserver) {
  72076. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  72077. }
  72078. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  72079. },
  72080. enumerable: true,
  72081. configurable: true
  72082. });
  72083. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  72084. /**
  72085. * Set a after render callback in the texture.
  72086. * This has been kept for backward compatibility and use of onAfterRenderObservable is recommended.
  72087. */
  72088. set: function (callback) {
  72089. if (this._onAfterRenderObserver) {
  72090. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  72091. }
  72092. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  72093. },
  72094. enumerable: true,
  72095. configurable: true
  72096. });
  72097. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  72098. /**
  72099. * Set a clear callback in the texture.
  72100. * This has been kept for backward compatibility and use of onClearObservable is recommended.
  72101. */
  72102. set: function (callback) {
  72103. if (this._onClearObserver) {
  72104. this.onClearObservable.remove(this._onClearObserver);
  72105. }
  72106. this._onClearObserver = this.onClearObservable.add(callback);
  72107. },
  72108. enumerable: true,
  72109. configurable: true
  72110. });
  72111. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  72112. /**
  72113. * Gets render target creation options that were used.
  72114. */
  72115. get: function () {
  72116. return this._renderTargetOptions;
  72117. },
  72118. enumerable: true,
  72119. configurable: true
  72120. });
  72121. RenderTargetTexture.prototype._onRatioRescale = function () {
  72122. if (this._sizeRatio) {
  72123. this.resize(this._initialSizeParameter);
  72124. }
  72125. };
  72126. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  72127. get: function () {
  72128. return this._boundingBoxSize;
  72129. },
  72130. /**
  72131. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  72132. * When defined, the cubemap will switch to local mode
  72133. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  72134. * @example https://www.babylonjs-playground.com/#RNASML
  72135. */
  72136. set: function (value) {
  72137. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  72138. return;
  72139. }
  72140. this._boundingBoxSize = value;
  72141. var scene = this.getScene();
  72142. if (scene) {
  72143. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  72144. }
  72145. },
  72146. enumerable: true,
  72147. configurable: true
  72148. });
  72149. /**
  72150. * Creates a depth stencil texture.
  72151. * This is only available in WebGL 2 or with the depth texture extension available.
  72152. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  72153. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  72154. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  72155. */
  72156. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  72157. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  72158. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  72159. if (generateStencil === void 0) { generateStencil = false; }
  72160. if (!this.getScene()) {
  72161. return;
  72162. }
  72163. var engine = this.getScene().getEngine();
  72164. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  72165. bilinearFiltering: bilinearFiltering,
  72166. comparisonFunction: comparisonFunction,
  72167. generateStencil: generateStencil,
  72168. isCube: this.isCube
  72169. });
  72170. engine.setFrameBufferDepthStencilTexture(this);
  72171. };
  72172. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  72173. if (size.ratio) {
  72174. this._sizeRatio = size.ratio;
  72175. this._size = {
  72176. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  72177. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  72178. };
  72179. }
  72180. else {
  72181. this._size = size;
  72182. }
  72183. };
  72184. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  72185. /**
  72186. * Define the number of samples to use in case of MSAA.
  72187. * It defaults to one meaning no MSAA has been enabled.
  72188. */
  72189. get: function () {
  72190. return this._samples;
  72191. },
  72192. set: function (value) {
  72193. if (this._samples === value) {
  72194. return;
  72195. }
  72196. var scene = this.getScene();
  72197. if (!scene) {
  72198. return;
  72199. }
  72200. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  72201. },
  72202. enumerable: true,
  72203. configurable: true
  72204. });
  72205. /**
  72206. * Resets the refresh counter of the texture and start bak from scratch.
  72207. * Could be usefull to regenerate the texture if it is setup to render only once.
  72208. */
  72209. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  72210. this._currentRefreshId = -1;
  72211. };
  72212. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  72213. /**
  72214. * Define the refresh rate of the texture or the rendering frequency.
  72215. * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  72216. */
  72217. get: function () {
  72218. return this._refreshRate;
  72219. },
  72220. set: function (value) {
  72221. this._refreshRate = value;
  72222. this.resetRefreshCounter();
  72223. },
  72224. enumerable: true,
  72225. configurable: true
  72226. });
  72227. /**
  72228. * Adds a post process to the render target rendering passes.
  72229. * @param postProcess define the post process to add
  72230. */
  72231. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  72232. if (!this._postProcessManager) {
  72233. var scene = this.getScene();
  72234. if (!scene) {
  72235. return;
  72236. }
  72237. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  72238. this._postProcesses = new Array();
  72239. }
  72240. this._postProcesses.push(postProcess);
  72241. this._postProcesses[0].autoClear = false;
  72242. };
  72243. /**
  72244. * Clear all the post processes attached to the render target
  72245. * @param dispose define if the cleared post processesshould also be disposed (false by default)
  72246. */
  72247. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  72248. if (dispose === void 0) { dispose = false; }
  72249. if (!this._postProcesses) {
  72250. return;
  72251. }
  72252. if (dispose) {
  72253. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  72254. var postProcess = _a[_i];
  72255. postProcess.dispose();
  72256. }
  72257. }
  72258. this._postProcesses = [];
  72259. };
  72260. /**
  72261. * Remove one of the post process from the list of attached post processes to the texture
  72262. * @param postProcess define the post process to remove from the list
  72263. */
  72264. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  72265. if (!this._postProcesses) {
  72266. return;
  72267. }
  72268. var index = this._postProcesses.indexOf(postProcess);
  72269. if (index === -1) {
  72270. return;
  72271. }
  72272. this._postProcesses.splice(index, 1);
  72273. if (this._postProcesses.length > 0) {
  72274. this._postProcesses[0].autoClear = false;
  72275. }
  72276. };
  72277. /** @hidden */
  72278. RenderTargetTexture.prototype._shouldRender = function () {
  72279. if (this._currentRefreshId === -1) { // At least render once
  72280. this._currentRefreshId = 1;
  72281. return true;
  72282. }
  72283. if (this.refreshRate === this._currentRefreshId) {
  72284. this._currentRefreshId = 1;
  72285. return true;
  72286. }
  72287. this._currentRefreshId++;
  72288. return false;
  72289. };
  72290. /**
  72291. * Gets the actual render size of the texture.
  72292. * @returns the width of the render size
  72293. */
  72294. RenderTargetTexture.prototype.getRenderSize = function () {
  72295. return this.getRenderWidth();
  72296. };
  72297. /**
  72298. * Gets the actual render width of the texture.
  72299. * @returns the width of the render size
  72300. */
  72301. RenderTargetTexture.prototype.getRenderWidth = function () {
  72302. if (this._size.width) {
  72303. return this._size.width;
  72304. }
  72305. return this._size;
  72306. };
  72307. /**
  72308. * Gets the actual render height of the texture.
  72309. * @returns the height of the render size
  72310. */
  72311. RenderTargetTexture.prototype.getRenderHeight = function () {
  72312. if (this._size.width) {
  72313. return this._size.height;
  72314. }
  72315. return this._size;
  72316. };
  72317. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  72318. /**
  72319. * Get if the texture can be rescaled or not.
  72320. */
  72321. get: function () {
  72322. return true;
  72323. },
  72324. enumerable: true,
  72325. configurable: true
  72326. });
  72327. /**
  72328. * Resize the texture using a ratio.
  72329. * @param ratio the ratio to apply to the texture size in order to compute the new target size
  72330. */
  72331. RenderTargetTexture.prototype.scale = function (ratio) {
  72332. var newSize = this.getRenderSize() * ratio;
  72333. this.resize(newSize);
  72334. };
  72335. /**
  72336. * Get the texture reflection matrix used to rotate/transform the reflection.
  72337. * @returns the reflection matrix
  72338. */
  72339. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  72340. if (this.isCube) {
  72341. return this._textureMatrix;
  72342. }
  72343. return _super.prototype.getReflectionTextureMatrix.call(this);
  72344. };
  72345. /**
  72346. * Resize the texture to a new desired size.
  72347. * Be carrefull as it will recreate all the data in the new texture.
  72348. * @param size Define the new size. It can be:
  72349. * - a number for squared texture,
  72350. * - an object containing { width: number, height: number }
  72351. * - or an object containing a ratio { ratio: number }
  72352. */
  72353. RenderTargetTexture.prototype.resize = function (size) {
  72354. this.releaseInternalTexture();
  72355. var scene = this.getScene();
  72356. if (!scene) {
  72357. return;
  72358. }
  72359. this._processSizeParameter(size);
  72360. if (this.isCube) {
  72361. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  72362. }
  72363. else {
  72364. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  72365. }
  72366. };
  72367. /**
  72368. * Renders all the objects from the render list into the texture.
  72369. * @param useCameraPostProcess Define if camera post processes should be used during the rendering
  72370. * @param dumpForDebug Define if the rendering result should be dumped (copied) for debugging purpose
  72371. */
  72372. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  72373. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  72374. if (dumpForDebug === void 0) { dumpForDebug = false; }
  72375. var scene = this.getScene();
  72376. if (!scene) {
  72377. return;
  72378. }
  72379. var engine = scene.getEngine();
  72380. if (this.useCameraPostProcesses !== undefined) {
  72381. useCameraPostProcess = this.useCameraPostProcesses;
  72382. }
  72383. if (this._waitingRenderList) {
  72384. this.renderList = [];
  72385. for (var index = 0; index < this._waitingRenderList.length; index++) {
  72386. var id = this._waitingRenderList[index];
  72387. var mesh_1 = scene.getMeshByID(id);
  72388. if (mesh_1) {
  72389. this.renderList.push(mesh_1);
  72390. }
  72391. }
  72392. delete this._waitingRenderList;
  72393. }
  72394. // Is predicate defined?
  72395. if (this.renderListPredicate) {
  72396. if (this.renderList) {
  72397. this.renderList.splice(0); // Clear previous renderList
  72398. }
  72399. else {
  72400. this.renderList = [];
  72401. }
  72402. var scene = this.getScene();
  72403. if (!scene) {
  72404. return;
  72405. }
  72406. var sceneMeshes = scene.meshes;
  72407. for (var index = 0; index < sceneMeshes.length; index++) {
  72408. var mesh = sceneMeshes[index];
  72409. if (this.renderListPredicate(mesh)) {
  72410. this.renderList.push(mesh);
  72411. }
  72412. }
  72413. }
  72414. this.onBeforeBindObservable.notifyObservers(this);
  72415. // Set custom projection.
  72416. // Needs to be before binding to prevent changing the aspect ratio.
  72417. var camera;
  72418. if (this.activeCamera) {
  72419. camera = this.activeCamera;
  72420. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  72421. if (this.activeCamera !== scene.activeCamera) {
  72422. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  72423. }
  72424. }
  72425. else {
  72426. camera = scene.activeCamera;
  72427. if (camera) {
  72428. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  72429. }
  72430. }
  72431. // Prepare renderingManager
  72432. this._renderingManager.reset();
  72433. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  72434. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  72435. var sceneRenderId = scene.getRenderId();
  72436. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  72437. var mesh = currentRenderList[meshIndex];
  72438. if (mesh) {
  72439. if (!mesh.isReady(this.refreshRate === 0)) {
  72440. this.resetRefreshCounter();
  72441. continue;
  72442. }
  72443. mesh._preActivateForIntermediateRendering(sceneRenderId);
  72444. var isMasked = void 0;
  72445. if (!this.renderList && camera) {
  72446. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  72447. }
  72448. else {
  72449. isMasked = false;
  72450. }
  72451. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  72452. mesh._activate(sceneRenderId);
  72453. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  72454. var subMesh = mesh.subMeshes[subIndex];
  72455. scene._activeIndices.addCount(subMesh.indexCount, false);
  72456. this._renderingManager.dispatch(subMesh, mesh);
  72457. }
  72458. }
  72459. }
  72460. }
  72461. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  72462. var particleSystem = scene.particleSystems[particleIndex];
  72463. var emitter = particleSystem.emitter;
  72464. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  72465. continue;
  72466. }
  72467. if (currentRenderList.indexOf(emitter) >= 0) {
  72468. this._renderingManager.dispatchParticles(particleSystem);
  72469. }
  72470. }
  72471. if (this.isCube) {
  72472. for (var face = 0; face < 6; face++) {
  72473. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  72474. scene.incrementRenderId();
  72475. scene.resetCachedMaterial();
  72476. }
  72477. }
  72478. else {
  72479. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  72480. }
  72481. this.onAfterUnbindObservable.notifyObservers(this);
  72482. if (scene.activeCamera) {
  72483. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  72484. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  72485. }
  72486. engine.setViewport(scene.activeCamera.viewport);
  72487. }
  72488. scene.resetCachedMaterial();
  72489. };
  72490. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  72491. var minimum = 128;
  72492. var x = renderDimension * scale;
  72493. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  72494. // Ensure we don't exceed the render dimension (while staying POT)
  72495. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  72496. };
  72497. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  72498. var _this = this;
  72499. if (!this._texture) {
  72500. return;
  72501. }
  72502. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  72503. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  72504. });
  72505. };
  72506. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  72507. var scene = this.getScene();
  72508. if (!scene) {
  72509. return;
  72510. }
  72511. var engine = scene.getEngine();
  72512. if (!this._texture) {
  72513. return;
  72514. }
  72515. // Bind
  72516. if (this._postProcessManager) {
  72517. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  72518. }
  72519. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  72520. if (this._texture) {
  72521. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  72522. }
  72523. }
  72524. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  72525. // Clear
  72526. if (this.onClearObservable.hasObservers()) {
  72527. this.onClearObservable.notifyObservers(engine);
  72528. }
  72529. else {
  72530. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  72531. }
  72532. if (!this._doNotChangeAspectRatio) {
  72533. scene.updateTransformMatrix(true);
  72534. }
  72535. // Render
  72536. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  72537. if (this._postProcessManager) {
  72538. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  72539. }
  72540. else if (useCameraPostProcess) {
  72541. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  72542. }
  72543. if (!this._doNotChangeAspectRatio) {
  72544. scene.updateTransformMatrix(true);
  72545. }
  72546. // Dump ?
  72547. if (dumpForDebug) {
  72548. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  72549. }
  72550. // Unbind
  72551. if (!this.isCube || faceIndex === 5) {
  72552. if (this.isCube) {
  72553. if (faceIndex === 5) {
  72554. engine.generateMipMapsForCubemap(this._texture);
  72555. }
  72556. }
  72557. this.unbindFrameBuffer(engine, faceIndex);
  72558. }
  72559. else {
  72560. this.onAfterRenderObservable.notifyObservers(faceIndex);
  72561. }
  72562. };
  72563. /**
  72564. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  72565. * This allowed control for front to back rendering or reversly depending of the special needs.
  72566. *
  72567. * @param renderingGroupId The rendering group id corresponding to its index
  72568. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  72569. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  72570. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  72571. */
  72572. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  72573. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  72574. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  72575. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  72576. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  72577. };
  72578. /**
  72579. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  72580. *
  72581. * @param renderingGroupId The rendering group id corresponding to its index
  72582. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  72583. */
  72584. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  72585. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  72586. this._renderingManager._useSceneAutoClearSetup = false;
  72587. };
  72588. /**
  72589. * Clones the texture.
  72590. * @returns the cloned texture
  72591. */
  72592. RenderTargetTexture.prototype.clone = function () {
  72593. var textureSize = this.getSize();
  72594. 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);
  72595. // Base texture
  72596. newTexture.hasAlpha = this.hasAlpha;
  72597. newTexture.level = this.level;
  72598. // RenderTarget Texture
  72599. newTexture.coordinatesMode = this.coordinatesMode;
  72600. if (this.renderList) {
  72601. newTexture.renderList = this.renderList.slice(0);
  72602. }
  72603. return newTexture;
  72604. };
  72605. /**
  72606. * Serialize the texture to a JSON representation we can easily use in the resepective Parse function.
  72607. * @returns The JSON representation of the texture
  72608. */
  72609. RenderTargetTexture.prototype.serialize = function () {
  72610. if (!this.name) {
  72611. return null;
  72612. }
  72613. var serializationObject = _super.prototype.serialize.call(this);
  72614. serializationObject.renderTargetSize = this.getRenderSize();
  72615. serializationObject.renderList = [];
  72616. if (this.renderList) {
  72617. for (var index = 0; index < this.renderList.length; index++) {
  72618. serializationObject.renderList.push(this.renderList[index].id);
  72619. }
  72620. }
  72621. return serializationObject;
  72622. };
  72623. /**
  72624. * This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  72625. */
  72626. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  72627. var objBuffer = this.getInternalTexture();
  72628. var scene = this.getScene();
  72629. if (objBuffer && scene) {
  72630. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  72631. }
  72632. };
  72633. /**
  72634. * Dispose the texture and release its associated resources.
  72635. */
  72636. RenderTargetTexture.prototype.dispose = function () {
  72637. if (this._postProcessManager) {
  72638. this._postProcessManager.dispose();
  72639. this._postProcessManager = null;
  72640. }
  72641. this.clearPostProcesses(true);
  72642. if (this._resizeObserver) {
  72643. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  72644. this._resizeObserver = null;
  72645. }
  72646. this.renderList = null;
  72647. // Remove from custom render targets
  72648. var scene = this.getScene();
  72649. if (!scene) {
  72650. return;
  72651. }
  72652. var index = scene.customRenderTargets.indexOf(this);
  72653. if (index >= 0) {
  72654. scene.customRenderTargets.splice(index, 1);
  72655. }
  72656. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  72657. var camera = _a[_i];
  72658. index = camera.customRenderTargets.indexOf(this);
  72659. if (index >= 0) {
  72660. camera.customRenderTargets.splice(index, 1);
  72661. }
  72662. }
  72663. _super.prototype.dispose.call(this);
  72664. };
  72665. /** @hidden */
  72666. RenderTargetTexture.prototype._rebuild = function () {
  72667. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  72668. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  72669. }
  72670. if (this._postProcessManager) {
  72671. this._postProcessManager._rebuild();
  72672. }
  72673. };
  72674. /**
  72675. * Clear the info related to rendering groups preventing retention point in material dispose.
  72676. */
  72677. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  72678. if (this._renderingManager) {
  72679. this._renderingManager.freeRenderingGroups();
  72680. }
  72681. };
  72682. /**
  72683. * The texture will only be rendered once which can be useful to improve performance if everything in your render is static for instance.
  72684. */
  72685. RenderTargetTexture.REFRESHRATE_RENDER_ONCE = 0;
  72686. /**
  72687. * The texture will only be rendered rendered every frame and is recomended for dynamic contents.
  72688. */
  72689. RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  72690. /**
  72691. * The texture will be rendered every 2 frames which could be enough if your dynamic objects are not
  72692. * the central point of your effect and can save a lot of performances.
  72693. */
  72694. RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  72695. return RenderTargetTexture;
  72696. }(BABYLON.Texture));
  72697. BABYLON.RenderTargetTexture = RenderTargetTexture;
  72698. })(BABYLON || (BABYLON = {}));
  72699. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  72700. var BABYLON;
  72701. (function (BABYLON) {
  72702. /**
  72703. * A multi render target, like a render target provides the ability to render to a texture.
  72704. * Unlike the render target, it can render to several draw buffers in one draw.
  72705. * This is specially interesting in deferred rendering or for any effects requiring more than
  72706. * just one color from a single pass.
  72707. */
  72708. var MultiRenderTarget = /** @class */ (function (_super) {
  72709. __extends(MultiRenderTarget, _super);
  72710. /**
  72711. * Instantiate a new multi render target texture.
  72712. * A multi render target, like a render target provides the ability to render to a texture.
  72713. * Unlike the render target, it can render to several draw buffers in one draw.
  72714. * This is specially interesting in deferred rendering or for any effects requiring more than
  72715. * just one color from a single pass.
  72716. * @param name Define the name of the texture
  72717. * @param size Define the size of the buffers to render to
  72718. * @param count Define the number of target we are rendering into
  72719. * @param scene Define the scene the texture belongs to
  72720. * @param options Define the options used to create the multi render target
  72721. */
  72722. function MultiRenderTarget(name, size, count, scene, options) {
  72723. var _this = this;
  72724. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  72725. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  72726. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  72727. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  72728. _this._engine = scene.getEngine();
  72729. if (!_this.isSupported) {
  72730. _this.dispose();
  72731. return;
  72732. }
  72733. var types = [];
  72734. var samplingModes = [];
  72735. for (var i = 0; i < count; i++) {
  72736. if (options && options.types && options.types[i] !== undefined) {
  72737. types.push(options.types[i]);
  72738. }
  72739. else {
  72740. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  72741. }
  72742. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  72743. samplingModes.push(options.samplingModes[i]);
  72744. }
  72745. else {
  72746. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  72747. }
  72748. }
  72749. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  72750. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  72751. _this._size = size;
  72752. _this._multiRenderTargetOptions = {
  72753. samplingModes: samplingModes,
  72754. generateMipMaps: generateMipMaps,
  72755. generateDepthBuffer: generateDepthBuffer,
  72756. generateStencilBuffer: generateStencilBuffer,
  72757. generateDepthTexture: generateDepthTexture,
  72758. types: types,
  72759. textureCount: count
  72760. };
  72761. _this._createInternalTextures();
  72762. _this._createTextures();
  72763. return _this;
  72764. }
  72765. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  72766. /**
  72767. * Get if draw buffers are currently supported by the used hardware and browser.
  72768. */
  72769. get: function () {
  72770. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  72771. },
  72772. enumerable: true,
  72773. configurable: true
  72774. });
  72775. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  72776. /**
  72777. * Get the list of textures generated by the multi render target.
  72778. */
  72779. get: function () {
  72780. return this._textures;
  72781. },
  72782. enumerable: true,
  72783. configurable: true
  72784. });
  72785. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  72786. /**
  72787. * Get the depth texture generated by the multi render target if options.generateDepthTexture has been set
  72788. */
  72789. get: function () {
  72790. return this._textures[this._textures.length - 1];
  72791. },
  72792. enumerable: true,
  72793. configurable: true
  72794. });
  72795. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  72796. /**
  72797. * Set the wrapping mode on U of all the textures we are rendering to.
  72798. * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE)
  72799. */
  72800. set: function (wrap) {
  72801. if (this._textures) {
  72802. for (var i = 0; i < this._textures.length; i++) {
  72803. this._textures[i].wrapU = wrap;
  72804. }
  72805. }
  72806. },
  72807. enumerable: true,
  72808. configurable: true
  72809. });
  72810. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  72811. /**
  72812. * Set the wrapping mode on V of all the textures we are rendering to.
  72813. * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE)
  72814. */
  72815. set: function (wrap) {
  72816. if (this._textures) {
  72817. for (var i = 0; i < this._textures.length; i++) {
  72818. this._textures[i].wrapV = wrap;
  72819. }
  72820. }
  72821. },
  72822. enumerable: true,
  72823. configurable: true
  72824. });
  72825. /** @hidden */
  72826. MultiRenderTarget.prototype._rebuild = function () {
  72827. this.releaseInternalTextures();
  72828. this._createInternalTextures();
  72829. for (var i = 0; i < this._internalTextures.length; i++) {
  72830. var texture = this._textures[i];
  72831. texture._texture = this._internalTextures[i];
  72832. }
  72833. // Keeps references to frame buffer and stencil/depth buffer
  72834. this._texture = this._internalTextures[0];
  72835. };
  72836. MultiRenderTarget.prototype._createInternalTextures = function () {
  72837. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  72838. };
  72839. MultiRenderTarget.prototype._createTextures = function () {
  72840. this._textures = [];
  72841. for (var i = 0; i < this._internalTextures.length; i++) {
  72842. var texture = new BABYLON.Texture(null, this.getScene());
  72843. texture._texture = this._internalTextures[i];
  72844. this._textures.push(texture);
  72845. }
  72846. // Keeps references to frame buffer and stencil/depth buffer
  72847. this._texture = this._internalTextures[0];
  72848. };
  72849. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  72850. /**
  72851. * Define the number of samples used if MSAA is enabled.
  72852. */
  72853. get: function () {
  72854. return this._samples;
  72855. },
  72856. set: function (value) {
  72857. if (this._samples === value) {
  72858. return;
  72859. }
  72860. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  72861. },
  72862. enumerable: true,
  72863. configurable: true
  72864. });
  72865. /**
  72866. * Resize all the textures in the multi render target.
  72867. * Be carrefull as it will recreate all the data in the new texture.
  72868. * @param size Define the new size
  72869. */
  72870. MultiRenderTarget.prototype.resize = function (size) {
  72871. this.releaseInternalTextures();
  72872. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  72873. this._createInternalTextures();
  72874. };
  72875. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  72876. var _this = this;
  72877. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  72878. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  72879. });
  72880. };
  72881. /**
  72882. * Dispose the render targets and their associated resources
  72883. */
  72884. MultiRenderTarget.prototype.dispose = function () {
  72885. this.releaseInternalTextures();
  72886. _super.prototype.dispose.call(this);
  72887. };
  72888. /**
  72889. * Release all the underlying texture used as draw buffers.
  72890. */
  72891. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  72892. if (!this._internalTextures) {
  72893. return;
  72894. }
  72895. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  72896. if (this._internalTextures[i] !== undefined) {
  72897. this._internalTextures[i].dispose();
  72898. this._internalTextures.splice(i, 1);
  72899. }
  72900. }
  72901. };
  72902. return MultiRenderTarget;
  72903. }(BABYLON.RenderTargetTexture));
  72904. BABYLON.MultiRenderTarget = MultiRenderTarget;
  72905. })(BABYLON || (BABYLON = {}));
  72906. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  72907. var BABYLON;
  72908. (function (BABYLON) {
  72909. /**
  72910. * Mirror texture can be used to simulate the view from a mirror in a scene.
  72911. * It will dynamically be rendered every frame to adapt to the camera point of view.
  72912. * You can then easily use it as a reflectionTexture on a flat surface.
  72913. * In case the surface is not a plane, please consider relying on reflection probes.
  72914. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  72915. */
  72916. var MirrorTexture = /** @class */ (function (_super) {
  72917. __extends(MirrorTexture, _super);
  72918. /**
  72919. * Instantiates a Mirror Texture.
  72920. * Mirror texture can be used to simulate the view from a mirror in a scene.
  72921. * It will dynamically be rendered every frame to adapt to the camera point of view.
  72922. * You can then easily use it as a reflectionTexture on a flat surface.
  72923. * In case the surface is not a plane, please consider relying on reflection probes.
  72924. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  72925. * @param name
  72926. * @param size
  72927. * @param scene
  72928. * @param generateMipMaps
  72929. * @param type
  72930. * @param samplingMode
  72931. * @param generateDepthBuffer
  72932. */
  72933. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  72934. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72935. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  72936. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  72937. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  72938. _this.scene = scene;
  72939. /**
  72940. * Define the reflection plane we want to use. The mirrorPlane is usually set to the constructed reflector.
  72941. * 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.
  72942. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  72943. */
  72944. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  72945. _this._transformMatrix = BABYLON.Matrix.Zero();
  72946. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  72947. _this._adaptiveBlurKernel = 0;
  72948. _this._blurKernelX = 0;
  72949. _this._blurKernelY = 0;
  72950. _this._blurRatio = 1.0;
  72951. _this.ignoreCameraViewport = true;
  72952. _this._updateGammaSpace();
  72953. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  72954. _this._updateGammaSpace;
  72955. });
  72956. _this.onBeforeRenderObservable.add(function () {
  72957. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  72958. _this._savedViewMatrix = scene.getViewMatrix();
  72959. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  72960. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  72961. scene.clipPlane = _this.mirrorPlane;
  72962. scene.getEngine().cullBackFaces = false;
  72963. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  72964. });
  72965. _this.onAfterRenderObservable.add(function () {
  72966. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  72967. scene.getEngine().cullBackFaces = true;
  72968. scene._mirroredCameraPosition = null;
  72969. delete scene.clipPlane;
  72970. });
  72971. return _this;
  72972. }
  72973. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  72974. get: function () {
  72975. return this._blurRatio;
  72976. },
  72977. /**
  72978. * Define the blur ratio used to blur the reflection if needed.
  72979. */
  72980. set: function (value) {
  72981. if (this._blurRatio === value) {
  72982. return;
  72983. }
  72984. this._blurRatio = value;
  72985. this._preparePostProcesses();
  72986. },
  72987. enumerable: true,
  72988. configurable: true
  72989. });
  72990. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  72991. /**
  72992. * Define the adaptive blur kernel used to blur the reflection if needed.
  72993. * This will autocompute the closest best match for the `blurKernel`
  72994. */
  72995. set: function (value) {
  72996. this._adaptiveBlurKernel = value;
  72997. this._autoComputeBlurKernel();
  72998. },
  72999. enumerable: true,
  73000. configurable: true
  73001. });
  73002. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  73003. /**
  73004. * Define the blur kernel used to blur the reflection if needed.
  73005. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  73006. */
  73007. set: function (value) {
  73008. this.blurKernelX = value;
  73009. this.blurKernelY = value;
  73010. },
  73011. enumerable: true,
  73012. configurable: true
  73013. });
  73014. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  73015. get: function () {
  73016. return this._blurKernelX;
  73017. },
  73018. /**
  73019. * Define the blur kernel on the X Axis used to blur the reflection if needed.
  73020. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  73021. */
  73022. set: function (value) {
  73023. if (this._blurKernelX === value) {
  73024. return;
  73025. }
  73026. this._blurKernelX = value;
  73027. this._preparePostProcesses();
  73028. },
  73029. enumerable: true,
  73030. configurable: true
  73031. });
  73032. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  73033. get: function () {
  73034. return this._blurKernelY;
  73035. },
  73036. /**
  73037. * Define the blur kernel on the Y Axis used to blur the reflection if needed.
  73038. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  73039. */
  73040. set: function (value) {
  73041. if (this._blurKernelY === value) {
  73042. return;
  73043. }
  73044. this._blurKernelY = value;
  73045. this._preparePostProcesses();
  73046. },
  73047. enumerable: true,
  73048. configurable: true
  73049. });
  73050. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  73051. var engine = this.getScene().getEngine();
  73052. var dw = this.getRenderWidth() / engine.getRenderWidth();
  73053. var dh = this.getRenderHeight() / engine.getRenderHeight();
  73054. this.blurKernelX = this._adaptiveBlurKernel * dw;
  73055. this.blurKernelY = this._adaptiveBlurKernel * dh;
  73056. };
  73057. MirrorTexture.prototype._onRatioRescale = function () {
  73058. if (this._sizeRatio) {
  73059. this.resize(this._initialSizeParameter);
  73060. if (!this._adaptiveBlurKernel) {
  73061. this._preparePostProcesses();
  73062. }
  73063. }
  73064. if (this._adaptiveBlurKernel) {
  73065. this._autoComputeBlurKernel();
  73066. }
  73067. };
  73068. MirrorTexture.prototype._updateGammaSpace = function () {
  73069. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  73070. };
  73071. MirrorTexture.prototype._preparePostProcesses = function () {
  73072. this.clearPostProcesses(true);
  73073. if (this._blurKernelX && this._blurKernelY) {
  73074. var engine = this.getScene().getEngine();
  73075. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73076. 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);
  73077. this._blurX.autoClear = false;
  73078. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  73079. this._blurX.inputTexture = this._texture;
  73080. }
  73081. else {
  73082. this._blurX.alwaysForcePOT = true;
  73083. }
  73084. 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);
  73085. this._blurY.autoClear = false;
  73086. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  73087. this.addPostProcess(this._blurX);
  73088. this.addPostProcess(this._blurY);
  73089. }
  73090. else {
  73091. if (this._blurY) {
  73092. this.removePostProcess(this._blurY);
  73093. this._blurY.dispose();
  73094. this._blurY = null;
  73095. }
  73096. if (this._blurX) {
  73097. this.removePostProcess(this._blurX);
  73098. this._blurX.dispose();
  73099. this._blurX = null;
  73100. }
  73101. }
  73102. };
  73103. /**
  73104. * Clone the mirror texture.
  73105. * @returns the cloned texture
  73106. */
  73107. MirrorTexture.prototype.clone = function () {
  73108. var scene = this.getScene();
  73109. if (!scene) {
  73110. return this;
  73111. }
  73112. var textureSize = this.getSize();
  73113. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  73114. // Base texture
  73115. newTexture.hasAlpha = this.hasAlpha;
  73116. newTexture.level = this.level;
  73117. // Mirror Texture
  73118. newTexture.mirrorPlane = this.mirrorPlane.clone();
  73119. if (this.renderList) {
  73120. newTexture.renderList = this.renderList.slice(0);
  73121. }
  73122. return newTexture;
  73123. };
  73124. /**
  73125. * Serialize the texture to a JSON representation you could use in Parse later on
  73126. * @returns the serialized JSON representation
  73127. */
  73128. MirrorTexture.prototype.serialize = function () {
  73129. if (!this.name) {
  73130. return null;
  73131. }
  73132. var serializationObject = _super.prototype.serialize.call(this);
  73133. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  73134. return serializationObject;
  73135. };
  73136. /**
  73137. * Dispose the texture and release its associated resources.
  73138. */
  73139. MirrorTexture.prototype.dispose = function () {
  73140. _super.prototype.dispose.call(this);
  73141. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  73142. };
  73143. return MirrorTexture;
  73144. }(BABYLON.RenderTargetTexture));
  73145. BABYLON.MirrorTexture = MirrorTexture;
  73146. })(BABYLON || (BABYLON = {}));
  73147. //# sourceMappingURL=babylon.mirrorTexture.js.map
  73148. var BABYLON;
  73149. (function (BABYLON) {
  73150. /**
  73151. * Creates a refraction texture used by refraction channel of the standard material.
  73152. * It is like a mirror but to see through a material.
  73153. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  73154. */
  73155. var RefractionTexture = /** @class */ (function (_super) {
  73156. __extends(RefractionTexture, _super);
  73157. /**
  73158. * Creates a refraction texture used by refraction channel of the standard material.
  73159. * It is like a mirror but to see through a material.
  73160. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  73161. * @param name Define the texture name
  73162. * @param size Define the size of the underlying texture
  73163. * @param scene Define the scene the refraction belongs to
  73164. * @param generateMipMaps Define if we need to generate mips level for the refraction
  73165. */
  73166. function RefractionTexture(name, size, scene, generateMipMaps) {
  73167. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  73168. /**
  73169. * Define the reflection plane we want to use. The refractionPlane is usually set to the constructed refractor.
  73170. * 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.
  73171. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  73172. */
  73173. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  73174. /**
  73175. * Define how deep under the surface we should see.
  73176. */
  73177. _this.depth = 2.0;
  73178. _this.onBeforeRenderObservable.add(function () {
  73179. scene.clipPlane = _this.refractionPlane;
  73180. });
  73181. _this.onAfterRenderObservable.add(function () {
  73182. delete scene.clipPlane;
  73183. });
  73184. return _this;
  73185. }
  73186. /**
  73187. * Clone the refraction texture.
  73188. * @returns the cloned texture
  73189. */
  73190. RefractionTexture.prototype.clone = function () {
  73191. var scene = this.getScene();
  73192. if (!scene) {
  73193. return this;
  73194. }
  73195. var textureSize = this.getSize();
  73196. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  73197. // Base texture
  73198. newTexture.hasAlpha = this.hasAlpha;
  73199. newTexture.level = this.level;
  73200. // Refraction Texture
  73201. newTexture.refractionPlane = this.refractionPlane.clone();
  73202. if (this.renderList) {
  73203. newTexture.renderList = this.renderList.slice(0);
  73204. }
  73205. newTexture.depth = this.depth;
  73206. return newTexture;
  73207. };
  73208. /**
  73209. * Serialize the texture to a JSON representation you could use in Parse later on
  73210. * @returns the serialized JSON representation
  73211. */
  73212. RefractionTexture.prototype.serialize = function () {
  73213. if (!this.name) {
  73214. return null;
  73215. }
  73216. var serializationObject = _super.prototype.serialize.call(this);
  73217. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  73218. serializationObject.depth = this.depth;
  73219. return serializationObject;
  73220. };
  73221. return RefractionTexture;
  73222. }(BABYLON.RenderTargetTexture));
  73223. BABYLON.RefractionTexture = RefractionTexture;
  73224. })(BABYLON || (BABYLON = {}));
  73225. //# sourceMappingURL=babylon.refractionTexture.js.map
  73226. var BABYLON;
  73227. (function (BABYLON) {
  73228. /**
  73229. * A class extending Texture allowing drawing on a texture
  73230. * @see http://doc.babylonjs.com/how_to/dynamictexture
  73231. */
  73232. var DynamicTexture = /** @class */ (function (_super) {
  73233. __extends(DynamicTexture, _super);
  73234. /**
  73235. * Creates a DynamicTexture
  73236. * @param name defines the name of the texture
  73237. * @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
  73238. * @param scene defines the scene where you want the texture
  73239. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  73240. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  73241. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  73242. */
  73243. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  73244. if (scene === void 0) { scene = null; }
  73245. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73246. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  73247. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  73248. _this.name = name;
  73249. _this._engine = _this.getScene().getEngine();
  73250. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73251. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73252. _this._generateMipMaps = generateMipMaps;
  73253. if (options.getContext) {
  73254. _this._canvas = options;
  73255. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  73256. }
  73257. else {
  73258. _this._canvas = document.createElement("canvas");
  73259. if (options.width || options.width === 0) {
  73260. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  73261. }
  73262. else {
  73263. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  73264. }
  73265. }
  73266. var textureSize = _this.getSize();
  73267. _this._canvas.width = textureSize.width;
  73268. _this._canvas.height = textureSize.height;
  73269. _this._context = _this._canvas.getContext("2d");
  73270. return _this;
  73271. }
  73272. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  73273. /**
  73274. * Gets the current state of canRescale
  73275. */
  73276. get: function () {
  73277. return true;
  73278. },
  73279. enumerable: true,
  73280. configurable: true
  73281. });
  73282. DynamicTexture.prototype._recreate = function (textureSize) {
  73283. this._canvas.width = textureSize.width;
  73284. this._canvas.height = textureSize.height;
  73285. this.releaseInternalTexture();
  73286. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  73287. };
  73288. /**
  73289. * Scales the texture
  73290. * @param ratio the scale factor to apply to both width and height
  73291. */
  73292. DynamicTexture.prototype.scale = function (ratio) {
  73293. var textureSize = this.getSize();
  73294. textureSize.width *= ratio;
  73295. textureSize.height *= ratio;
  73296. this._recreate(textureSize);
  73297. };
  73298. /**
  73299. * Resizes the texture
  73300. * @param width the new width
  73301. * @param height the new height
  73302. */
  73303. DynamicTexture.prototype.scaleTo = function (width, height) {
  73304. var textureSize = this.getSize();
  73305. textureSize.width = width;
  73306. textureSize.height = height;
  73307. this._recreate(textureSize);
  73308. };
  73309. /**
  73310. * Gets the context of the canvas used by the texture
  73311. * @returns the canvas context of the dynamic texture
  73312. */
  73313. DynamicTexture.prototype.getContext = function () {
  73314. return this._context;
  73315. };
  73316. /**
  73317. * Clears the texture
  73318. */
  73319. DynamicTexture.prototype.clear = function () {
  73320. var size = this.getSize();
  73321. this._context.fillRect(0, 0, size.width, size.height);
  73322. };
  73323. /**
  73324. * Updates the texture
  73325. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  73326. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  73327. */
  73328. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  73329. if (premulAlpha === void 0) { premulAlpha = false; }
  73330. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  73331. };
  73332. /**
  73333. * Draws text onto the texture
  73334. * @param text defines the text to be drawn
  73335. * @param x defines the placement of the text from the left
  73336. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  73337. * @param font defines the font to be used with font-style, font-size, font-name
  73338. * @param color defines the color used for the text
  73339. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  73340. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  73341. * @param update defines whether texture is immediately update (default is true)
  73342. */
  73343. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  73344. if (update === void 0) { update = true; }
  73345. var size = this.getSize();
  73346. if (clearColor) {
  73347. this._context.fillStyle = clearColor;
  73348. this._context.fillRect(0, 0, size.width, size.height);
  73349. }
  73350. this._context.font = font;
  73351. if (x === null || x === undefined) {
  73352. var textSize = this._context.measureText(text);
  73353. x = (size.width - textSize.width) / 2;
  73354. }
  73355. if (y === null || y === undefined) {
  73356. var fontSize = parseInt((font.replace(/\D/g, '')));
  73357. y = (size.height / 2) + (fontSize / 3.65);
  73358. }
  73359. this._context.fillStyle = color;
  73360. this._context.fillText(text, x, y);
  73361. if (update) {
  73362. this.update(invertY);
  73363. }
  73364. };
  73365. /**
  73366. * Clones the texture
  73367. * @returns the clone of the texture.
  73368. */
  73369. DynamicTexture.prototype.clone = function () {
  73370. var scene = this.getScene();
  73371. if (!scene) {
  73372. return this;
  73373. }
  73374. var textureSize = this.getSize();
  73375. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  73376. // Base texture
  73377. newTexture.hasAlpha = this.hasAlpha;
  73378. newTexture.level = this.level;
  73379. // Dynamic Texture
  73380. newTexture.wrapU = this.wrapU;
  73381. newTexture.wrapV = this.wrapV;
  73382. return newTexture;
  73383. };
  73384. /**
  73385. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  73386. * @returns a serialized dynamic texture object
  73387. */
  73388. DynamicTexture.prototype.serialize = function () {
  73389. var scene = this.getScene();
  73390. if (scene && !scene.isReady()) {
  73391. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  73392. }
  73393. var serializationObject = _super.prototype.serialize.call(this);
  73394. serializationObject.base64String = this._canvas.toDataURL();
  73395. serializationObject.invertY = this._invertY;
  73396. serializationObject.samplingMode = this.samplingMode;
  73397. return serializationObject;
  73398. };
  73399. /** @hidden */
  73400. DynamicTexture.prototype._rebuild = function () {
  73401. this.update();
  73402. };
  73403. return DynamicTexture;
  73404. }(BABYLON.Texture));
  73405. BABYLON.DynamicTexture = DynamicTexture;
  73406. })(BABYLON || (BABYLON = {}));
  73407. //# sourceMappingURL=babylon.dynamicTexture.js.map
  73408. var BABYLON;
  73409. (function (BABYLON) {
  73410. /**
  73411. * If you want to display a video in your scene, this is the special texture for that.
  73412. * This special texture works similar to other textures, with the exception of a few parameters.
  73413. * @see https://doc.babylonjs.com/how_to/video_texture
  73414. */
  73415. var VideoTexture = /** @class */ (function (_super) {
  73416. __extends(VideoTexture, _super);
  73417. /**
  73418. * Creates a video texture.
  73419. * If you want to display a video in your scene, this is the special texture for that.
  73420. * This special texture works similar to other textures, with the exception of a few parameters.
  73421. * @see https://doc.babylonjs.com/how_to/video_texture
  73422. * @param name optional name, will detect from video source, if not defined
  73423. * @param src can be used to provide an url, array of urls or an already setup HTML video element.
  73424. * @param scene is obviously the current scene.
  73425. * @param generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  73426. * @param invertY is false by default but can be used to invert video on Y axis
  73427. * @param samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  73428. * @param settings allows finer control over video usage
  73429. */
  73430. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  73431. if (generateMipMaps === void 0) { generateMipMaps = false; }
  73432. if (invertY === void 0) { invertY = false; }
  73433. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73434. if (settings === void 0) { settings = {
  73435. autoPlay: true,
  73436. loop: true,
  73437. autoUpdateTexture: true,
  73438. }; }
  73439. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  73440. _this._onUserActionRequestedObservable = null;
  73441. _this._stillImageCaptured = false;
  73442. _this._poster = false;
  73443. _this._createInternalTexture = function () {
  73444. if (_this._texture != null) {
  73445. if (_this._poster) {
  73446. _this._texture.dispose();
  73447. _this._poster = false;
  73448. }
  73449. else {
  73450. return;
  73451. }
  73452. }
  73453. if (!_this._engine.needPOTTextures ||
  73454. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  73455. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73456. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73457. }
  73458. else {
  73459. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73460. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73461. _this._generateMipMaps = false;
  73462. }
  73463. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  73464. if (!_this.video.autoplay) {
  73465. var oldHandler_1 = _this.video.onplaying;
  73466. var error_1 = false;
  73467. _this.video.onplaying = function () {
  73468. _this.video.onplaying = oldHandler_1;
  73469. _this._texture.isReady = true;
  73470. _this._updateInternalTexture();
  73471. if (!error_1) {
  73472. _this.video.pause();
  73473. }
  73474. if (_this.onLoadObservable.hasObservers()) {
  73475. _this.onLoadObservable.notifyObservers(_this);
  73476. }
  73477. };
  73478. var playing = _this.video.play();
  73479. if (playing) {
  73480. playing.then(function () {
  73481. // Everything is good.
  73482. })
  73483. .catch(function () {
  73484. error_1 = true;
  73485. // On Chrome for instance, new policies might prevent playing without user interaction.
  73486. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  73487. _this._onUserActionRequestedObservable.notifyObservers(_this);
  73488. }
  73489. });
  73490. }
  73491. else {
  73492. _this.video.onplaying = oldHandler_1;
  73493. _this._texture.isReady = true;
  73494. _this._updateInternalTexture();
  73495. if (_this.onLoadObservable.hasObservers()) {
  73496. _this.onLoadObservable.notifyObservers(_this);
  73497. }
  73498. }
  73499. }
  73500. else {
  73501. _this._texture.isReady = true;
  73502. _this._updateInternalTexture();
  73503. if (_this.onLoadObservable.hasObservers()) {
  73504. _this.onLoadObservable.notifyObservers(_this);
  73505. }
  73506. }
  73507. };
  73508. _this.reset = function () {
  73509. if (_this._texture == null) {
  73510. return;
  73511. }
  73512. if (!_this._poster) {
  73513. _this._texture.dispose();
  73514. _this._texture = null;
  73515. }
  73516. };
  73517. _this._updateInternalTexture = function (e) {
  73518. if (_this._texture == null || !_this._texture.isReady) {
  73519. return;
  73520. }
  73521. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  73522. return;
  73523. }
  73524. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  73525. };
  73526. _this._engine = _this.getScene().getEngine();
  73527. _this._generateMipMaps = generateMipMaps;
  73528. _this._samplingMode = samplingMode;
  73529. _this.autoUpdateTexture = settings.autoUpdateTexture;
  73530. _this.name = name || _this._getName(src);
  73531. _this.video = _this._getVideo(src);
  73532. if (settings.poster) {
  73533. _this.video.poster = settings.poster;
  73534. }
  73535. if (settings.autoPlay !== undefined) {
  73536. _this.video.autoplay = settings.autoPlay;
  73537. }
  73538. if (settings.loop !== undefined) {
  73539. _this.video.loop = settings.loop;
  73540. }
  73541. _this.video.setAttribute("playsinline", "");
  73542. _this.video.addEventListener("canplay", _this._createInternalTexture);
  73543. _this.video.addEventListener("paused", _this._updateInternalTexture);
  73544. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  73545. _this.video.addEventListener("emptied", _this.reset);
  73546. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  73547. _this._createInternalTexture();
  73548. }
  73549. if (settings.poster) {
  73550. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  73551. _this._poster = true;
  73552. }
  73553. return _this;
  73554. }
  73555. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  73556. /**
  73557. * Event triggerd when a dom action is required by the user to play the video.
  73558. * This happens due to recent changes in browser policies preventing video to auto start.
  73559. */
  73560. get: function () {
  73561. if (!this._onUserActionRequestedObservable) {
  73562. this._onUserActionRequestedObservable = new BABYLON.Observable();
  73563. }
  73564. return this._onUserActionRequestedObservable;
  73565. },
  73566. enumerable: true,
  73567. configurable: true
  73568. });
  73569. VideoTexture.prototype._getName = function (src) {
  73570. if (src instanceof HTMLVideoElement) {
  73571. return src.currentSrc;
  73572. }
  73573. if (typeof src === "object") {
  73574. return src.toString();
  73575. }
  73576. return src;
  73577. };
  73578. VideoTexture.prototype._getVideo = function (src) {
  73579. if (src instanceof HTMLVideoElement) {
  73580. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  73581. return src;
  73582. }
  73583. var video = document.createElement("video");
  73584. if (typeof src === "string") {
  73585. BABYLON.Tools.SetCorsBehavior(src, video);
  73586. video.src = src;
  73587. }
  73588. else {
  73589. BABYLON.Tools.SetCorsBehavior(src[0], video);
  73590. src.forEach(function (url) {
  73591. var source = document.createElement("source");
  73592. source.src = url;
  73593. video.appendChild(source);
  73594. });
  73595. }
  73596. return video;
  73597. };
  73598. /**
  73599. * @hidden Internal method to initiate `update`.
  73600. */
  73601. VideoTexture.prototype._rebuild = function () {
  73602. this.update();
  73603. };
  73604. /**
  73605. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  73606. */
  73607. VideoTexture.prototype.update = function () {
  73608. if (!this.autoUpdateTexture) {
  73609. // Expecting user to call `updateTexture` manually
  73610. return;
  73611. }
  73612. this.updateTexture(true);
  73613. };
  73614. /**
  73615. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  73616. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  73617. */
  73618. VideoTexture.prototype.updateTexture = function (isVisible) {
  73619. if (!isVisible) {
  73620. return;
  73621. }
  73622. if (this.video.paused && this._stillImageCaptured) {
  73623. return;
  73624. }
  73625. this._stillImageCaptured = true;
  73626. this._updateInternalTexture();
  73627. };
  73628. /**
  73629. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  73630. * @param url New url.
  73631. */
  73632. VideoTexture.prototype.updateURL = function (url) {
  73633. this.video.src = url;
  73634. };
  73635. /**
  73636. * Dispose the texture and release its associated resources.
  73637. */
  73638. VideoTexture.prototype.dispose = function () {
  73639. _super.prototype.dispose.call(this);
  73640. if (this._onUserActionRequestedObservable) {
  73641. this._onUserActionRequestedObservable.clear();
  73642. this._onUserActionRequestedObservable = null;
  73643. }
  73644. this.video.removeEventListener("canplay", this._createInternalTexture);
  73645. this.video.removeEventListener("paused", this._updateInternalTexture);
  73646. this.video.removeEventListener("seeked", this._updateInternalTexture);
  73647. this.video.removeEventListener("emptied", this.reset);
  73648. this.video.pause();
  73649. };
  73650. /**
  73651. * Creates a video texture straight from your WebCam video feed.
  73652. * @param scene Define the scene the texture should be created in
  73653. * @param onReady Define a callback to triggered once the texture will be ready
  73654. * @param constraints Define the constraints to use to create the web cam feed from WebRTC
  73655. */
  73656. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  73657. var video = document.createElement("video");
  73658. video.setAttribute('autoplay', '');
  73659. video.setAttribute('muted', '');
  73660. video.setAttribute('playsinline', '');
  73661. var constraintsDeviceId;
  73662. if (constraints && constraints.deviceId) {
  73663. constraintsDeviceId = {
  73664. exact: constraints.deviceId,
  73665. };
  73666. }
  73667. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  73668. if (navigator.mediaDevices) {
  73669. navigator.mediaDevices.getUserMedia({ video: constraints })
  73670. .then(function (stream) {
  73671. if (video.mozSrcObject !== undefined) {
  73672. // hack for Firefox < 19
  73673. video.mozSrcObject = stream;
  73674. }
  73675. else {
  73676. video.srcObject = stream;
  73677. }
  73678. var onPlaying = function () {
  73679. if (onReady) {
  73680. onReady(new VideoTexture("video", video, scene, true, true));
  73681. }
  73682. video.removeEventListener("playing", onPlaying);
  73683. };
  73684. video.addEventListener("playing", onPlaying);
  73685. video.play();
  73686. })
  73687. .catch(function (err) {
  73688. BABYLON.Tools.Error(err.name);
  73689. });
  73690. }
  73691. else {
  73692. navigator.getUserMedia =
  73693. navigator.getUserMedia ||
  73694. navigator.webkitGetUserMedia ||
  73695. navigator.mozGetUserMedia ||
  73696. navigator.msGetUserMedia;
  73697. if (navigator.getUserMedia) {
  73698. navigator.getUserMedia({
  73699. video: {
  73700. deviceId: constraintsDeviceId,
  73701. width: {
  73702. min: (constraints && constraints.minWidth) || 256,
  73703. max: (constraints && constraints.maxWidth) || 640,
  73704. },
  73705. height: {
  73706. min: (constraints && constraints.minHeight) || 256,
  73707. max: (constraints && constraints.maxHeight) || 480,
  73708. },
  73709. },
  73710. }, function (stream) {
  73711. if (video.mozSrcObject !== undefined) {
  73712. // hack for Firefox < 19
  73713. video.mozSrcObject = stream;
  73714. }
  73715. else {
  73716. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  73717. }
  73718. video.play();
  73719. if (onReady) {
  73720. onReady(new VideoTexture("video", video, scene, true, true));
  73721. }
  73722. }, function (e) {
  73723. BABYLON.Tools.Error(e.name);
  73724. });
  73725. }
  73726. }
  73727. };
  73728. return VideoTexture;
  73729. }(BABYLON.Texture));
  73730. BABYLON.VideoTexture = VideoTexture;
  73731. })(BABYLON || (BABYLON = {}));
  73732. //# sourceMappingURL=babylon.videoTexture.js.map
  73733. var BABYLON;
  73734. (function (BABYLON) {
  73735. /**
  73736. * Raw texture can help creating a texture directly from an array of data.
  73737. * This can be super useful if you either get the data from an uncompressed source or
  73738. * if you wish to create your texture pixel by pixel.
  73739. */
  73740. var RawTexture = /** @class */ (function (_super) {
  73741. __extends(RawTexture, _super);
  73742. /**
  73743. * Instantiates a new RawTexture.
  73744. * Raw texture can help creating a texture directly from an array of data.
  73745. * This can be super useful if you either get the data from an uncompressed source or
  73746. * if you wish to create your texture pixel by pixel.
  73747. * @param data define the array of data to use to create the texture
  73748. * @param width define the width of the texture
  73749. * @param height define the height of the texture
  73750. * @param format define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx)
  73751. * @param scene define the scene the texture belongs to
  73752. * @param generateMipMaps define whether mip maps should be generated or not
  73753. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  73754. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  73755. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  73756. */
  73757. function RawTexture(data, width, height,
  73758. /**
  73759. * Define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx)
  73760. */
  73761. format, scene, generateMipMaps, invertY, samplingMode, type) {
  73762. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73763. if (invertY === void 0) { invertY = false; }
  73764. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73765. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73766. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  73767. _this.format = format;
  73768. _this._engine = scene.getEngine();
  73769. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  73770. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73771. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73772. return _this;
  73773. }
  73774. /**
  73775. * Updates the texture underlying data.
  73776. * @param data Define the new data of the texture
  73777. */
  73778. RawTexture.prototype.update = function (data) {
  73779. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  73780. };
  73781. /**
  73782. * Creates a luminance texture from some data.
  73783. * @param data Define the texture data
  73784. * @param width Define the width of the texture
  73785. * @param height Define the height of the texture
  73786. * @param scene Define the scene the texture belongs to
  73787. * @param generateMipMaps Define whether or not to create mip maps for the texture
  73788. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  73789. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  73790. * @returns the luminance texture
  73791. */
  73792. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  73793. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73794. if (invertY === void 0) { invertY = false; }
  73795. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73796. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  73797. };
  73798. /**
  73799. * Creates a luminance alpha texture from some data.
  73800. * @param data Define the texture data
  73801. * @param width Define the width of the texture
  73802. * @param height Define the height of the texture
  73803. * @param scene Define the scene the texture belongs to
  73804. * @param generateMipMaps Define whether or not to create mip maps for the texture
  73805. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  73806. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  73807. * @returns the luminance alpha texture
  73808. */
  73809. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  73810. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73811. if (invertY === void 0) { invertY = false; }
  73812. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73813. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  73814. };
  73815. /**
  73816. * Creates an alpha texture from some data.
  73817. * @param data Define the texture data
  73818. * @param width Define the width of the texture
  73819. * @param height Define the height of the texture
  73820. * @param scene Define the scene the texture belongs to
  73821. * @param generateMipMaps Define whether or not to create mip maps for the texture
  73822. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  73823. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  73824. * @returns the alpha texture
  73825. */
  73826. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  73827. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73828. if (invertY === void 0) { invertY = false; }
  73829. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73830. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  73831. };
  73832. /**
  73833. * Creates a RGB texture from some data.
  73834. * @param data Define the texture data
  73835. * @param width Define the width of the texture
  73836. * @param height Define the height of the texture
  73837. * @param scene Define the scene the texture belongs to
  73838. * @param generateMipMaps Define whether or not to create mip maps for the texture
  73839. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  73840. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  73841. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  73842. * @returns the RGB alpha texture
  73843. */
  73844. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  73845. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73846. if (invertY === void 0) { invertY = false; }
  73847. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73848. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73849. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  73850. };
  73851. /**
  73852. * Creates a RGBA texture from some data.
  73853. * @param data Define the texture data
  73854. * @param width Define the width of the texture
  73855. * @param height Define the height of the texture
  73856. * @param scene Define the scene the texture belongs to
  73857. * @param generateMipMaps Define whether or not to create mip maps for the texture
  73858. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  73859. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  73860. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  73861. * @returns the RGBA texture
  73862. */
  73863. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  73864. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73865. if (invertY === void 0) { invertY = false; }
  73866. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73867. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73868. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  73869. };
  73870. /**
  73871. * Creates a R texture from some data.
  73872. * @param data Define the texture data
  73873. * @param width Define the width of the texture
  73874. * @param height Define the height of the texture
  73875. * @param scene Define the scene the texture belongs to
  73876. * @param generateMipMaps Define whether or not to create mip maps for the texture
  73877. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  73878. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  73879. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  73880. * @returns the R texture
  73881. */
  73882. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  73883. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73884. if (invertY === void 0) { invertY = false; }
  73885. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73886. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  73887. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  73888. };
  73889. return RawTexture;
  73890. }(BABYLON.Texture));
  73891. BABYLON.RawTexture = RawTexture;
  73892. })(BABYLON || (BABYLON = {}));
  73893. //# sourceMappingURL=babylon.rawTexture.js.map
  73894. var BABYLON;
  73895. (function (BABYLON) {
  73896. /**
  73897. * Class used to store 3D textures containing user data
  73898. */
  73899. var RawTexture3D = /** @class */ (function (_super) {
  73900. __extends(RawTexture3D, _super);
  73901. /**
  73902. * Create a new RawTexture3D
  73903. * @param data defines the data of the texture
  73904. * @param width defines the width of the texture
  73905. * @param height defines the height of the texture
  73906. * @param depth defines the depth of the texture
  73907. * @param format defines the texture format to use
  73908. * @param scene defines the hosting scene
  73909. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  73910. * @param invertY defines if texture must be stored with Y axis inverted
  73911. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  73912. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  73913. */
  73914. function RawTexture3D(data, width, height, depth,
  73915. /** Gets or sets the texture format to use */
  73916. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  73917. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73918. if (invertY === void 0) { invertY = false; }
  73919. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73920. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73921. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  73922. _this.format = format;
  73923. _this._engine = scene.getEngine();
  73924. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  73925. _this.is3D = true;
  73926. return _this;
  73927. }
  73928. /**
  73929. * Update the texture with new data
  73930. * @param data defines the data to store in the texture
  73931. */
  73932. RawTexture3D.prototype.update = function (data) {
  73933. if (!this._texture) {
  73934. return;
  73935. }
  73936. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  73937. };
  73938. return RawTexture3D;
  73939. }(BABYLON.Texture));
  73940. BABYLON.RawTexture3D = RawTexture3D;
  73941. })(BABYLON || (BABYLON = {}));
  73942. //# sourceMappingURL=babylon.rawTexture3D.js.map
  73943. var BABYLON;
  73944. (function (BABYLON) {
  73945. /**
  73946. * PostProcessManager is used to manage one or more post processes or post process pipelines
  73947. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  73948. */
  73949. var PostProcessManager = /** @class */ (function () {
  73950. /**
  73951. * Creates a new instance PostProcess
  73952. * @param scene The scene that the post process is associated with.
  73953. */
  73954. function PostProcessManager(scene) {
  73955. this._vertexBuffers = {};
  73956. this._scene = scene;
  73957. }
  73958. PostProcessManager.prototype._prepareBuffers = function () {
  73959. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  73960. return;
  73961. }
  73962. // VBO
  73963. var vertices = [];
  73964. vertices.push(1, 1);
  73965. vertices.push(-1, 1);
  73966. vertices.push(-1, -1);
  73967. vertices.push(1, -1);
  73968. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  73969. this._buildIndexBuffer();
  73970. };
  73971. PostProcessManager.prototype._buildIndexBuffer = function () {
  73972. // Indices
  73973. var indices = [];
  73974. indices.push(0);
  73975. indices.push(1);
  73976. indices.push(2);
  73977. indices.push(0);
  73978. indices.push(2);
  73979. indices.push(3);
  73980. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  73981. };
  73982. /**
  73983. * Rebuilds the vertex buffers of the manager.
  73984. * @hidden
  73985. */
  73986. PostProcessManager.prototype._rebuild = function () {
  73987. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73988. if (!vb) {
  73989. return;
  73990. }
  73991. vb._rebuild();
  73992. this._buildIndexBuffer();
  73993. };
  73994. // Methods
  73995. /**
  73996. * Prepares a frame to be run through a post process.
  73997. * @param sourceTexture The input texture to the post procesess. (default: null)
  73998. * @param postProcesses An array of post processes to be run. (default: null)
  73999. * @returns True if the post processes were able to be run.
  74000. * @hidden
  74001. */
  74002. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  74003. if (sourceTexture === void 0) { sourceTexture = null; }
  74004. if (postProcesses === void 0) { postProcesses = null; }
  74005. var camera = this._scene.activeCamera;
  74006. if (!camera) {
  74007. return false;
  74008. }
  74009. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  74010. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  74011. return false;
  74012. }
  74013. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  74014. return true;
  74015. };
  74016. /**
  74017. * Manually render a set of post processes to a texture.
  74018. * @param postProcesses An array of post processes to be run.
  74019. * @param targetTexture The target texture to render to.
  74020. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  74021. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  74022. * @param lodLevel defines which lod of the texture to render to
  74023. */
  74024. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  74025. if (targetTexture === void 0) { targetTexture = null; }
  74026. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  74027. if (faceIndex === void 0) { faceIndex = 0; }
  74028. if (lodLevel === void 0) { lodLevel = 0; }
  74029. var engine = this._scene.getEngine();
  74030. for (var index = 0; index < postProcesses.length; index++) {
  74031. if (index < postProcesses.length - 1) {
  74032. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  74033. }
  74034. else {
  74035. if (targetTexture) {
  74036. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  74037. }
  74038. else {
  74039. engine.restoreDefaultFramebuffer();
  74040. }
  74041. }
  74042. var pp = postProcesses[index];
  74043. var effect = pp.apply();
  74044. if (effect) {
  74045. pp.onBeforeRenderObservable.notifyObservers(effect);
  74046. // VBOs
  74047. this._prepareBuffers();
  74048. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  74049. // Draw order
  74050. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  74051. pp.onAfterRenderObservable.notifyObservers(effect);
  74052. }
  74053. }
  74054. // Restore depth buffer
  74055. engine.setDepthBuffer(true);
  74056. engine.setDepthWrite(true);
  74057. };
  74058. /**
  74059. * Finalize the result of the output of the postprocesses.
  74060. * @param doNotPresent If true the result will not be displayed to the screen.
  74061. * @param targetTexture The target texture to render to.
  74062. * @param faceIndex The index of the face to bind the target texture to.
  74063. * @param postProcesses The array of post processes to render.
  74064. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  74065. * @hidden
  74066. */
  74067. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  74068. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  74069. var camera = this._scene.activeCamera;
  74070. if (!camera) {
  74071. return;
  74072. }
  74073. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  74074. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  74075. return;
  74076. }
  74077. var engine = this._scene.getEngine();
  74078. for (var index = 0, len = postProcesses.length; index < len; index++) {
  74079. var pp = postProcesses[index];
  74080. if (index < len - 1) {
  74081. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  74082. }
  74083. else {
  74084. if (targetTexture) {
  74085. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  74086. pp._outputTexture = targetTexture;
  74087. }
  74088. else {
  74089. engine.restoreDefaultFramebuffer();
  74090. pp._outputTexture = null;
  74091. }
  74092. }
  74093. if (doNotPresent) {
  74094. break;
  74095. }
  74096. var effect = pp.apply();
  74097. if (effect) {
  74098. pp.onBeforeRenderObservable.notifyObservers(effect);
  74099. // VBOs
  74100. this._prepareBuffers();
  74101. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  74102. // Draw order
  74103. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  74104. pp.onAfterRenderObservable.notifyObservers(effect);
  74105. }
  74106. }
  74107. // Restore states
  74108. engine.setDepthBuffer(true);
  74109. engine.setDepthWrite(true);
  74110. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  74111. };
  74112. /**
  74113. * Disposes of the post process manager.
  74114. */
  74115. PostProcessManager.prototype.dispose = function () {
  74116. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74117. if (buffer) {
  74118. buffer.dispose();
  74119. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  74120. }
  74121. if (this._indexBuffer) {
  74122. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  74123. this._indexBuffer = null;
  74124. }
  74125. };
  74126. return PostProcessManager;
  74127. }());
  74128. BABYLON.PostProcessManager = PostProcessManager;
  74129. })(BABYLON || (BABYLON = {}));
  74130. //# sourceMappingURL=babylon.postProcessManager.js.map
  74131. var BABYLON;
  74132. (function (BABYLON) {
  74133. /**
  74134. * PostProcess can be used to apply a shader to a texture after it has been rendered
  74135. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  74136. */
  74137. var PostProcess = /** @class */ (function () {
  74138. /**
  74139. * Creates a new instance PostProcess
  74140. * @param name The name of the PostProcess.
  74141. * @param fragmentUrl The url of the fragment shader to be used.
  74142. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  74143. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  74144. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  74145. * @param camera The camera to apply the render pass to.
  74146. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74147. * @param engine The engine which the post process will be applied. (default: current engine)
  74148. * @param reusable If the post process can be reused on the same frame. (default: false)
  74149. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  74150. * @param textureType Type of textures used when performing the post process. (default: 0)
  74151. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  74152. * @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
  74153. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  74154. */
  74155. function PostProcess(
  74156. /** Name of the PostProcess. */
  74157. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  74158. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  74159. if (defines === void 0) { defines = null; }
  74160. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74161. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  74162. if (blockCompilation === void 0) { blockCompilation = false; }
  74163. this.name = name;
  74164. /**
  74165. * Width of the texture to apply the post process on
  74166. */
  74167. this.width = -1;
  74168. /**
  74169. * Height of the texture to apply the post process on
  74170. */
  74171. this.height = -1;
  74172. /**
  74173. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  74174. * @hidden
  74175. */
  74176. this._outputTexture = null;
  74177. /**
  74178. * If the buffer needs to be cleared before applying the post process. (default: true)
  74179. * Should be set to false if shader will overwrite all previous pixels.
  74180. */
  74181. this.autoClear = true;
  74182. /**
  74183. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  74184. */
  74185. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  74186. /**
  74187. * Animations to be used for the post processing
  74188. */
  74189. this.animations = new Array();
  74190. /**
  74191. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  74192. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  74193. */
  74194. this.enablePixelPerfectMode = false;
  74195. /**
  74196. * Force the postprocess to be applied without taking in account viewport
  74197. */
  74198. this.forceFullscreenViewport = true;
  74199. /**
  74200. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  74201. *
  74202. * | Value | Type | Description |
  74203. * | ----- | ----------------------------------- | ----------- |
  74204. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  74205. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  74206. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  74207. *
  74208. */
  74209. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  74210. /**
  74211. * Force textures to be a power of two (default: false)
  74212. */
  74213. this.alwaysForcePOT = false;
  74214. this._samples = 1;
  74215. /**
  74216. * Modify the scale of the post process to be the same as the viewport (default: false)
  74217. */
  74218. this.adaptScaleToCurrentViewport = false;
  74219. this._reusable = false;
  74220. /**
  74221. * Smart array of input and output textures for the post process.
  74222. * @hidden
  74223. */
  74224. this._textures = new BABYLON.SmartArray(2);
  74225. /**
  74226. * The index in _textures that corresponds to the output texture.
  74227. * @hidden
  74228. */
  74229. this._currentRenderTextureInd = 0;
  74230. this._scaleRatio = new BABYLON.Vector2(1, 1);
  74231. this._texelSize = BABYLON.Vector2.Zero();
  74232. // Events
  74233. /**
  74234. * An event triggered when the postprocess is activated.
  74235. */
  74236. this.onActivateObservable = new BABYLON.Observable();
  74237. /**
  74238. * An event triggered when the postprocess changes its size.
  74239. */
  74240. this.onSizeChangedObservable = new BABYLON.Observable();
  74241. /**
  74242. * An event triggered when the postprocess applies its effect.
  74243. */
  74244. this.onApplyObservable = new BABYLON.Observable();
  74245. /**
  74246. * An event triggered before rendering the postprocess
  74247. */
  74248. this.onBeforeRenderObservable = new BABYLON.Observable();
  74249. /**
  74250. * An event triggered after rendering the postprocess
  74251. */
  74252. this.onAfterRenderObservable = new BABYLON.Observable();
  74253. if (camera != null) {
  74254. this._camera = camera;
  74255. this._scene = camera.getScene();
  74256. camera.attachPostProcess(this);
  74257. this._engine = this._scene.getEngine();
  74258. this._scene.postProcesses.push(this);
  74259. }
  74260. else if (engine) {
  74261. this._engine = engine;
  74262. this._engine.postProcesses.push(this);
  74263. }
  74264. this._options = options;
  74265. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  74266. this._reusable = reusable || false;
  74267. this._textureType = textureType;
  74268. this._samplers = samplers || [];
  74269. this._samplers.push("textureSampler");
  74270. this._fragmentUrl = fragmentUrl;
  74271. this._vertexUrl = vertexUrl;
  74272. this._parameters = parameters || [];
  74273. this._parameters.push("scale");
  74274. this._indexParameters = indexParameters;
  74275. if (!blockCompilation) {
  74276. this.updateEffect(defines);
  74277. }
  74278. }
  74279. Object.defineProperty(PostProcess.prototype, "samples", {
  74280. /**
  74281. * Number of sample textures (default: 1)
  74282. */
  74283. get: function () {
  74284. return this._samples;
  74285. },
  74286. set: function (n) {
  74287. var _this = this;
  74288. this._samples = n;
  74289. this._textures.forEach(function (texture) {
  74290. if (texture.samples !== _this._samples) {
  74291. _this._engine.updateRenderTargetTextureSampleCount(texture, _this._samples);
  74292. }
  74293. });
  74294. },
  74295. enumerable: true,
  74296. configurable: true
  74297. });
  74298. Object.defineProperty(PostProcess.prototype, "onActivate", {
  74299. /**
  74300. * A function that is added to the onActivateObservable
  74301. */
  74302. set: function (callback) {
  74303. if (this._onActivateObserver) {
  74304. this.onActivateObservable.remove(this._onActivateObserver);
  74305. }
  74306. if (callback) {
  74307. this._onActivateObserver = this.onActivateObservable.add(callback);
  74308. }
  74309. },
  74310. enumerable: true,
  74311. configurable: true
  74312. });
  74313. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  74314. /**
  74315. * A function that is added to the onSizeChangedObservable
  74316. */
  74317. set: function (callback) {
  74318. if (this._onSizeChangedObserver) {
  74319. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  74320. }
  74321. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  74322. },
  74323. enumerable: true,
  74324. configurable: true
  74325. });
  74326. Object.defineProperty(PostProcess.prototype, "onApply", {
  74327. /**
  74328. * A function that is added to the onApplyObservable
  74329. */
  74330. set: function (callback) {
  74331. if (this._onApplyObserver) {
  74332. this.onApplyObservable.remove(this._onApplyObserver);
  74333. }
  74334. this._onApplyObserver = this.onApplyObservable.add(callback);
  74335. },
  74336. enumerable: true,
  74337. configurable: true
  74338. });
  74339. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  74340. /**
  74341. * A function that is added to the onBeforeRenderObservable
  74342. */
  74343. set: function (callback) {
  74344. if (this._onBeforeRenderObserver) {
  74345. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  74346. }
  74347. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  74348. },
  74349. enumerable: true,
  74350. configurable: true
  74351. });
  74352. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  74353. /**
  74354. * A function that is added to the onAfterRenderObservable
  74355. */
  74356. set: function (callback) {
  74357. if (this._onAfterRenderObserver) {
  74358. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  74359. }
  74360. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  74361. },
  74362. enumerable: true,
  74363. configurable: true
  74364. });
  74365. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  74366. /**
  74367. * 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
  74368. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  74369. */
  74370. get: function () {
  74371. return this._textures.data[this._currentRenderTextureInd];
  74372. },
  74373. set: function (value) {
  74374. this._forcedOutputTexture = value;
  74375. },
  74376. enumerable: true,
  74377. configurable: true
  74378. });
  74379. /**
  74380. * Gets the camera which post process is applied to.
  74381. * @returns The camera the post process is applied to.
  74382. */
  74383. PostProcess.prototype.getCamera = function () {
  74384. return this._camera;
  74385. };
  74386. Object.defineProperty(PostProcess.prototype, "texelSize", {
  74387. /**
  74388. * Gets the texel size of the postprocess.
  74389. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  74390. */
  74391. get: function () {
  74392. if (this._shareOutputWithPostProcess) {
  74393. return this._shareOutputWithPostProcess.texelSize;
  74394. }
  74395. if (this._forcedOutputTexture) {
  74396. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  74397. }
  74398. return this._texelSize;
  74399. },
  74400. enumerable: true,
  74401. configurable: true
  74402. });
  74403. /**
  74404. * Gets the engine which this post process belongs to.
  74405. * @returns The engine the post process was enabled with.
  74406. */
  74407. PostProcess.prototype.getEngine = function () {
  74408. return this._engine;
  74409. };
  74410. /**
  74411. * The effect that is created when initializing the post process.
  74412. * @returns The created effect corrisponding the the postprocess.
  74413. */
  74414. PostProcess.prototype.getEffect = function () {
  74415. return this._effect;
  74416. };
  74417. /**
  74418. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  74419. * @param postProcess The post process to share the output with.
  74420. * @returns This post process.
  74421. */
  74422. PostProcess.prototype.shareOutputWith = function (postProcess) {
  74423. this._disposeTextures();
  74424. this._shareOutputWithPostProcess = postProcess;
  74425. return this;
  74426. };
  74427. /**
  74428. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  74429. * This should be called if the post process that shares output with this post process is disabled/disposed.
  74430. */
  74431. PostProcess.prototype.useOwnOutput = function () {
  74432. if (this._textures.length == 0) {
  74433. this._textures = new BABYLON.SmartArray(2);
  74434. }
  74435. this._shareOutputWithPostProcess = null;
  74436. };
  74437. /**
  74438. * Updates the effect with the current post process compile time values and recompiles the shader.
  74439. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74440. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74441. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74442. * @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
  74443. * @param onCompiled Called when the shader has been compiled.
  74444. * @param onError Called if there is an error when compiling a shader.
  74445. */
  74446. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74447. if (defines === void 0) { defines = null; }
  74448. if (uniforms === void 0) { uniforms = null; }
  74449. if (samplers === void 0) { samplers = null; }
  74450. 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);
  74451. };
  74452. /**
  74453. * The post process is reusable if it can be used multiple times within one frame.
  74454. * @returns If the post process is reusable
  74455. */
  74456. PostProcess.prototype.isReusable = function () {
  74457. return this._reusable;
  74458. };
  74459. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  74460. PostProcess.prototype.markTextureDirty = function () {
  74461. this.width = -1;
  74462. };
  74463. /**
  74464. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  74465. * 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.
  74466. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  74467. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  74468. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  74469. * @returns The target texture that was bound to be written to.
  74470. */
  74471. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  74472. var _this = this;
  74473. if (sourceTexture === void 0) { sourceTexture = null; }
  74474. camera = camera || this._camera;
  74475. var scene = camera.getScene();
  74476. var engine = scene.getEngine();
  74477. var maxSize = engine.getCaps().maxTextureSize;
  74478. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  74479. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  74480. // 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
  74481. var webVRCamera = camera.parent;
  74482. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  74483. requiredWidth /= 2;
  74484. }
  74485. var desiredWidth = (this._options.width || requiredWidth);
  74486. var desiredHeight = this._options.height || requiredHeight;
  74487. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  74488. if (this.adaptScaleToCurrentViewport) {
  74489. var currentViewport = engine.currentViewport;
  74490. if (currentViewport) {
  74491. desiredWidth *= currentViewport.width;
  74492. desiredHeight *= currentViewport.height;
  74493. }
  74494. }
  74495. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  74496. if (!this._options.width) {
  74497. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  74498. }
  74499. if (!this._options.height) {
  74500. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  74501. }
  74502. }
  74503. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  74504. if (this._textures.length > 0) {
  74505. for (var i = 0; i < this._textures.length; i++) {
  74506. this._engine._releaseTexture(this._textures.data[i]);
  74507. }
  74508. this._textures.reset();
  74509. }
  74510. this.width = desiredWidth;
  74511. this.height = desiredHeight;
  74512. var textureSize = { width: this.width, height: this.height };
  74513. var textureOptions = {
  74514. generateMipMaps: false,
  74515. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  74516. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  74517. samplingMode: this.renderTargetSamplingMode,
  74518. type: this._textureType
  74519. };
  74520. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  74521. if (this._reusable) {
  74522. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  74523. }
  74524. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  74525. this.onSizeChangedObservable.notifyObservers(this);
  74526. }
  74527. this._textures.forEach(function (texture) {
  74528. if (texture.samples !== _this.samples) {
  74529. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  74530. }
  74531. });
  74532. }
  74533. var target;
  74534. if (this._shareOutputWithPostProcess) {
  74535. target = this._shareOutputWithPostProcess.inputTexture;
  74536. }
  74537. else if (this._forcedOutputTexture) {
  74538. target = this._forcedOutputTexture;
  74539. this.width = this._forcedOutputTexture.width;
  74540. this.height = this._forcedOutputTexture.height;
  74541. }
  74542. else {
  74543. target = this.inputTexture;
  74544. }
  74545. // Bind the input of this post process to be used as the output of the previous post process.
  74546. if (this.enablePixelPerfectMode) {
  74547. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  74548. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  74549. }
  74550. else {
  74551. this._scaleRatio.copyFromFloats(1, 1);
  74552. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  74553. }
  74554. this.onActivateObservable.notifyObservers(camera);
  74555. // Clear
  74556. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  74557. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, scene._allowPostProcessClearColor, true, true);
  74558. }
  74559. if (this._reusable) {
  74560. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  74561. }
  74562. return target;
  74563. };
  74564. Object.defineProperty(PostProcess.prototype, "isSupported", {
  74565. /**
  74566. * If the post process is supported.
  74567. */
  74568. get: function () {
  74569. return this._effect.isSupported;
  74570. },
  74571. enumerable: true,
  74572. configurable: true
  74573. });
  74574. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  74575. /**
  74576. * The aspect ratio of the output texture.
  74577. */
  74578. get: function () {
  74579. if (this._shareOutputWithPostProcess) {
  74580. return this._shareOutputWithPostProcess.aspectRatio;
  74581. }
  74582. if (this._forcedOutputTexture) {
  74583. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  74584. }
  74585. return this.width / this.height;
  74586. },
  74587. enumerable: true,
  74588. configurable: true
  74589. });
  74590. /**
  74591. * Get a value indicating if the post-process is ready to be used
  74592. * @returns true if the post-process is ready (shader is compiled)
  74593. */
  74594. PostProcess.prototype.isReady = function () {
  74595. return this._effect && this._effect.isReady();
  74596. };
  74597. /**
  74598. * Binds all textures and uniforms to the shader, this will be run on every pass.
  74599. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  74600. */
  74601. PostProcess.prototype.apply = function () {
  74602. // Check
  74603. if (!this._effect || !this._effect.isReady()) {
  74604. return null;
  74605. }
  74606. // States
  74607. this._engine.enableEffect(this._effect);
  74608. this._engine.setState(false);
  74609. this._engine.setDepthBuffer(false);
  74610. this._engine.setDepthWrite(false);
  74611. // Alpha
  74612. this._engine.setAlphaMode(this.alphaMode);
  74613. if (this.alphaConstants) {
  74614. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  74615. }
  74616. // Bind the output texture of the preivous post process as the input to this post process.
  74617. var source;
  74618. if (this._shareOutputWithPostProcess) {
  74619. source = this._shareOutputWithPostProcess.inputTexture;
  74620. }
  74621. else if (this._forcedOutputTexture) {
  74622. source = this._forcedOutputTexture;
  74623. }
  74624. else {
  74625. source = this.inputTexture;
  74626. }
  74627. this._effect._bindTexture("textureSampler", source);
  74628. // Parameters
  74629. this._effect.setVector2("scale", this._scaleRatio);
  74630. this.onApplyObservable.notifyObservers(this._effect);
  74631. return this._effect;
  74632. };
  74633. PostProcess.prototype._disposeTextures = function () {
  74634. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  74635. return;
  74636. }
  74637. if (this._textures.length > 0) {
  74638. for (var i = 0; i < this._textures.length; i++) {
  74639. this._engine._releaseTexture(this._textures.data[i]);
  74640. }
  74641. }
  74642. this._textures.dispose();
  74643. };
  74644. /**
  74645. * Disposes the post process.
  74646. * @param camera The camera to dispose the post process on.
  74647. */
  74648. PostProcess.prototype.dispose = function (camera) {
  74649. camera = camera || this._camera;
  74650. this._disposeTextures();
  74651. if (this._scene) {
  74652. var index_1 = this._scene.postProcesses.indexOf(this);
  74653. if (index_1 !== -1) {
  74654. this._scene.postProcesses.splice(index_1, 1);
  74655. }
  74656. }
  74657. else {
  74658. var index_2 = this._engine.postProcesses.indexOf(this);
  74659. if (index_2 !== -1) {
  74660. this._engine.postProcesses.splice(index_2, 1);
  74661. }
  74662. }
  74663. if (!camera) {
  74664. return;
  74665. }
  74666. camera.detachPostProcess(this);
  74667. var index = camera._postProcesses.indexOf(this);
  74668. if (index === 0 && camera._postProcesses.length > 0) {
  74669. var firstPostProcess = this._camera._getFirstPostProcess();
  74670. if (firstPostProcess) {
  74671. firstPostProcess.markTextureDirty();
  74672. }
  74673. }
  74674. this.onActivateObservable.clear();
  74675. this.onAfterRenderObservable.clear();
  74676. this.onApplyObservable.clear();
  74677. this.onBeforeRenderObservable.clear();
  74678. this.onSizeChangedObservable.clear();
  74679. };
  74680. return PostProcess;
  74681. }());
  74682. BABYLON.PostProcess = PostProcess;
  74683. })(BABYLON || (BABYLON = {}));
  74684. //# sourceMappingURL=babylon.postProcess.js.map
  74685. var BABYLON;
  74686. (function (BABYLON) {
  74687. /**
  74688. * PassPostProcess which produces an output the same as it's input
  74689. */
  74690. var PassPostProcess = /** @class */ (function (_super) {
  74691. __extends(PassPostProcess, _super);
  74692. /**
  74693. * Creates the PassPostProcess
  74694. * @param name The name of the effect.
  74695. * @param options The required width/height ratio to downsize to before computing the render pass.
  74696. * @param camera The camera to apply the render pass to.
  74697. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74698. * @param engine The engine which the post process will be applied. (default: current engine)
  74699. * @param reusable If the post process can be reused on the same frame. (default: false)
  74700. * @param textureType The type of texture to be used when performing the post processing.
  74701. * @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)
  74702. */
  74703. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74704. if (camera === void 0) { camera = null; }
  74705. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74706. if (blockCompilation === void 0) { blockCompilation = false; }
  74707. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  74708. }
  74709. return PassPostProcess;
  74710. }(BABYLON.PostProcess));
  74711. BABYLON.PassPostProcess = PassPostProcess;
  74712. })(BABYLON || (BABYLON = {}));
  74713. //# sourceMappingURL=babylon.passPostProcess.js.map
  74714. var __assign = (this && this.__assign) || function () {
  74715. __assign = Object.assign || function(t) {
  74716. for (var s, i = 1, n = arguments.length; i < n; i++) {
  74717. s = arguments[i];
  74718. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  74719. t[p] = s[p];
  74720. }
  74721. return t;
  74722. };
  74723. return __assign.apply(this, arguments);
  74724. };
  74725. var BABYLON;
  74726. (function (BABYLON) {
  74727. /**
  74728. * Default implementation IShadowGenerator.
  74729. * This is the main object responsible of generating shadows in the framework.
  74730. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  74731. */
  74732. var ShadowGenerator = /** @class */ (function () {
  74733. /**
  74734. * Creates a ShadowGenerator object.
  74735. * A ShadowGenerator is the required tool to use the shadows.
  74736. * Each light casting shadows needs to use its own ShadowGenerator.
  74737. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  74738. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  74739. * @param light The light object generating the shadows.
  74740. * @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.
  74741. */
  74742. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  74743. this._bias = 0.00005;
  74744. this._normalBias = 0;
  74745. this._blurBoxOffset = 1;
  74746. this._blurScale = 2;
  74747. this._blurKernel = 1;
  74748. this._useKernelBlur = false;
  74749. this._filter = ShadowGenerator.FILTER_NONE;
  74750. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  74751. this._contactHardeningLightSizeUVRatio = 0.1;
  74752. this._darkness = 0;
  74753. this._transparencyShadow = false;
  74754. /**
  74755. * Controls the extent to which the shadows fade out at the edge of the frustum
  74756. * Used only by directionals and spots
  74757. */
  74758. this.frustumEdgeFalloff = 0;
  74759. /**
  74760. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  74761. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  74762. * It might on the other hand introduce peter panning.
  74763. */
  74764. this.forceBackFacesOnly = false;
  74765. this._lightDirection = BABYLON.Vector3.Zero();
  74766. this._viewMatrix = BABYLON.Matrix.Zero();
  74767. this._projectionMatrix = BABYLON.Matrix.Zero();
  74768. this._transformMatrix = BABYLON.Matrix.Zero();
  74769. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  74770. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  74771. this._currentFaceIndex = 0;
  74772. this._currentFaceIndexCache = 0;
  74773. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  74774. this._mapSize = mapSize;
  74775. this._light = light;
  74776. this._scene = light.getScene();
  74777. light._shadowGenerator = this;
  74778. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR);
  74779. if (!component) {
  74780. component = new BABYLON.ShadowGeneratorSceneComponent(this._scene);
  74781. this._scene._addComponent(component);
  74782. }
  74783. // Texture type fallback from float to int if not supported.
  74784. var caps = this._scene.getEngine().getCaps();
  74785. if (!useFullFloatFirst) {
  74786. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  74787. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74788. }
  74789. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  74790. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  74791. }
  74792. else {
  74793. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  74794. }
  74795. }
  74796. else {
  74797. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  74798. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  74799. }
  74800. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  74801. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74802. }
  74803. else {
  74804. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  74805. }
  74806. }
  74807. this._initializeGenerator();
  74808. this._applyFilterValues();
  74809. }
  74810. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  74811. /**
  74812. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  74813. */
  74814. get: function () {
  74815. return this._bias;
  74816. },
  74817. /**
  74818. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  74819. */
  74820. set: function (bias) {
  74821. this._bias = bias;
  74822. },
  74823. enumerable: true,
  74824. configurable: true
  74825. });
  74826. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  74827. /**
  74828. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  74829. */
  74830. get: function () {
  74831. return this._normalBias;
  74832. },
  74833. /**
  74834. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  74835. */
  74836. set: function (normalBias) {
  74837. this._normalBias = normalBias;
  74838. },
  74839. enumerable: true,
  74840. configurable: true
  74841. });
  74842. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  74843. /**
  74844. * Gets the blur box offset: offset applied during the blur pass.
  74845. * Only usefull if useKernelBlur = false
  74846. */
  74847. get: function () {
  74848. return this._blurBoxOffset;
  74849. },
  74850. /**
  74851. * Sets the blur box offset: offset applied during the blur pass.
  74852. * Only usefull if useKernelBlur = false
  74853. */
  74854. set: function (value) {
  74855. if (this._blurBoxOffset === value) {
  74856. return;
  74857. }
  74858. this._blurBoxOffset = value;
  74859. this._disposeBlurPostProcesses();
  74860. },
  74861. enumerable: true,
  74862. configurable: true
  74863. });
  74864. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  74865. /**
  74866. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  74867. * 2 means half of the size.
  74868. */
  74869. get: function () {
  74870. return this._blurScale;
  74871. },
  74872. /**
  74873. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  74874. * 2 means half of the size.
  74875. */
  74876. set: function (value) {
  74877. if (this._blurScale === value) {
  74878. return;
  74879. }
  74880. this._blurScale = value;
  74881. this._disposeBlurPostProcesses();
  74882. },
  74883. enumerable: true,
  74884. configurable: true
  74885. });
  74886. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  74887. /**
  74888. * Gets the blur kernel: kernel size of the blur pass.
  74889. * Only usefull if useKernelBlur = true
  74890. */
  74891. get: function () {
  74892. return this._blurKernel;
  74893. },
  74894. /**
  74895. * Sets the blur kernel: kernel size of the blur pass.
  74896. * Only usefull if useKernelBlur = true
  74897. */
  74898. set: function (value) {
  74899. if (this._blurKernel === value) {
  74900. return;
  74901. }
  74902. this._blurKernel = value;
  74903. this._disposeBlurPostProcesses();
  74904. },
  74905. enumerable: true,
  74906. configurable: true
  74907. });
  74908. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  74909. /**
  74910. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  74911. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  74912. */
  74913. get: function () {
  74914. return this._useKernelBlur;
  74915. },
  74916. /**
  74917. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  74918. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  74919. */
  74920. set: function (value) {
  74921. if (this._useKernelBlur === value) {
  74922. return;
  74923. }
  74924. this._useKernelBlur = value;
  74925. this._disposeBlurPostProcesses();
  74926. },
  74927. enumerable: true,
  74928. configurable: true
  74929. });
  74930. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  74931. /**
  74932. * Gets the depth scale used in ESM mode.
  74933. */
  74934. get: function () {
  74935. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  74936. },
  74937. /**
  74938. * Sets the depth scale used in ESM mode.
  74939. * This can override the scale stored on the light.
  74940. */
  74941. set: function (value) {
  74942. this._depthScale = value;
  74943. },
  74944. enumerable: true,
  74945. configurable: true
  74946. });
  74947. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  74948. /**
  74949. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  74950. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  74951. */
  74952. get: function () {
  74953. return this._filter;
  74954. },
  74955. /**
  74956. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  74957. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  74958. */
  74959. set: function (value) {
  74960. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  74961. if (this._light.needCube()) {
  74962. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  74963. this.useExponentialShadowMap = true;
  74964. return;
  74965. }
  74966. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  74967. this.useCloseExponentialShadowMap = true;
  74968. return;
  74969. }
  74970. // PCF on cubemap would also be expensive
  74971. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  74972. this.usePoissonSampling = true;
  74973. return;
  74974. }
  74975. }
  74976. // Weblg1 fallback for PCF.
  74977. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  74978. if (this._scene.getEngine().webGLVersion === 1) {
  74979. this.usePoissonSampling = true;
  74980. return;
  74981. }
  74982. }
  74983. if (this._filter === value) {
  74984. return;
  74985. }
  74986. this._filter = value;
  74987. this._disposeBlurPostProcesses();
  74988. this._applyFilterValues();
  74989. this._light._markMeshesAsLightDirty();
  74990. },
  74991. enumerable: true,
  74992. configurable: true
  74993. });
  74994. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  74995. /**
  74996. * Gets if the current filter is set to Poisson Sampling.
  74997. */
  74998. get: function () {
  74999. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  75000. },
  75001. /**
  75002. * Sets the current filter to Poisson Sampling.
  75003. */
  75004. set: function (value) {
  75005. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  75006. return;
  75007. }
  75008. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  75009. },
  75010. enumerable: true,
  75011. configurable: true
  75012. });
  75013. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  75014. /**
  75015. * Gets if the current filter is set to VSM.
  75016. * DEPRECATED. Should use useExponentialShadowMap instead.
  75017. */
  75018. get: function () {
  75019. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  75020. return this.useExponentialShadowMap;
  75021. },
  75022. /**
  75023. * Sets the current filter is to VSM.
  75024. * DEPRECATED. Should use useExponentialShadowMap instead.
  75025. */
  75026. set: function (value) {
  75027. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  75028. this.useExponentialShadowMap = value;
  75029. },
  75030. enumerable: true,
  75031. configurable: true
  75032. });
  75033. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  75034. /**
  75035. * Gets if the current filter is set to blurred VSM.
  75036. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  75037. */
  75038. get: function () {
  75039. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  75040. return this.useBlurExponentialShadowMap;
  75041. },
  75042. /**
  75043. * Sets the current filter is to blurred VSM.
  75044. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  75045. */
  75046. set: function (value) {
  75047. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  75048. this.useBlurExponentialShadowMap = value;
  75049. },
  75050. enumerable: true,
  75051. configurable: true
  75052. });
  75053. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  75054. /**
  75055. * Gets if the current filter is set to ESM.
  75056. */
  75057. get: function () {
  75058. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  75059. },
  75060. /**
  75061. * Sets the current filter is to ESM.
  75062. */
  75063. set: function (value) {
  75064. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  75065. return;
  75066. }
  75067. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  75068. },
  75069. enumerable: true,
  75070. configurable: true
  75071. });
  75072. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  75073. /**
  75074. * Gets if the current filter is set to filtered ESM.
  75075. */
  75076. get: function () {
  75077. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  75078. },
  75079. /**
  75080. * Gets if the current filter is set to filtered ESM.
  75081. */
  75082. set: function (value) {
  75083. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  75084. return;
  75085. }
  75086. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  75087. },
  75088. enumerable: true,
  75089. configurable: true
  75090. });
  75091. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  75092. /**
  75093. * Gets if the current filter is set to "close ESM" (using the inverse of the
  75094. * exponential to prevent steep falloff artifacts).
  75095. */
  75096. get: function () {
  75097. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  75098. },
  75099. /**
  75100. * Sets the current filter to "close ESM" (using the inverse of the
  75101. * exponential to prevent steep falloff artifacts).
  75102. */
  75103. set: function (value) {
  75104. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  75105. return;
  75106. }
  75107. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  75108. },
  75109. enumerable: true,
  75110. configurable: true
  75111. });
  75112. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  75113. /**
  75114. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  75115. * exponential to prevent steep falloff artifacts).
  75116. */
  75117. get: function () {
  75118. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  75119. },
  75120. /**
  75121. * Sets the current filter to filtered "close ESM" (using the inverse of the
  75122. * exponential to prevent steep falloff artifacts).
  75123. */
  75124. set: function (value) {
  75125. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  75126. return;
  75127. }
  75128. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  75129. },
  75130. enumerable: true,
  75131. configurable: true
  75132. });
  75133. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  75134. /**
  75135. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  75136. */
  75137. get: function () {
  75138. return this.filter === ShadowGenerator.FILTER_PCF;
  75139. },
  75140. /**
  75141. * Sets the current filter to "PCF" (percentage closer filtering).
  75142. */
  75143. set: function (value) {
  75144. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  75145. return;
  75146. }
  75147. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  75148. },
  75149. enumerable: true,
  75150. configurable: true
  75151. });
  75152. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  75153. /**
  75154. * Gets the PCF or PCSS Quality.
  75155. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  75156. */
  75157. get: function () {
  75158. return this._filteringQuality;
  75159. },
  75160. /**
  75161. * Sets the PCF or PCSS Quality.
  75162. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  75163. */
  75164. set: function (filteringQuality) {
  75165. this._filteringQuality = filteringQuality;
  75166. },
  75167. enumerable: true,
  75168. configurable: true
  75169. });
  75170. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  75171. /**
  75172. * Gets if the current filter is set to "PCSS" (contact hardening).
  75173. */
  75174. get: function () {
  75175. return this.filter === ShadowGenerator.FILTER_PCSS;
  75176. },
  75177. /**
  75178. * Sets the current filter to "PCSS" (contact hardening).
  75179. */
  75180. set: function (value) {
  75181. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  75182. return;
  75183. }
  75184. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  75185. },
  75186. enumerable: true,
  75187. configurable: true
  75188. });
  75189. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  75190. /**
  75191. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  75192. * Using a ratio helps keeping shape stability independently of the map size.
  75193. *
  75194. * It does not account for the light projection as it was having too much
  75195. * instability during the light setup or during light position changes.
  75196. *
  75197. * Only valid if useContactHardeningShadow is true.
  75198. */
  75199. get: function () {
  75200. return this._contactHardeningLightSizeUVRatio;
  75201. },
  75202. /**
  75203. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  75204. * Using a ratio helps keeping shape stability independently of the map size.
  75205. *
  75206. * It does not account for the light projection as it was having too much
  75207. * instability during the light setup or during light position changes.
  75208. *
  75209. * Only valid if useContactHardeningShadow is true.
  75210. */
  75211. set: function (contactHardeningLightSizeUVRatio) {
  75212. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  75213. },
  75214. enumerable: true,
  75215. configurable: true
  75216. });
  75217. /**
  75218. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  75219. * 0 means strongest and 1 would means no shadow.
  75220. * @returns the darkness.
  75221. */
  75222. ShadowGenerator.prototype.getDarkness = function () {
  75223. return this._darkness;
  75224. };
  75225. /**
  75226. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  75227. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  75228. * @returns the shadow generator allowing fluent coding.
  75229. */
  75230. ShadowGenerator.prototype.setDarkness = function (darkness) {
  75231. if (darkness >= 1.0) {
  75232. this._darkness = 1.0;
  75233. }
  75234. else if (darkness <= 0.0) {
  75235. this._darkness = 0.0;
  75236. }
  75237. else {
  75238. this._darkness = darkness;
  75239. }
  75240. return this;
  75241. };
  75242. /**
  75243. * Sets the ability to have transparent shadow (boolean).
  75244. * @param transparent True if transparent else False
  75245. * @returns the shadow generator allowing fluent coding
  75246. */
  75247. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  75248. this._transparencyShadow = transparent;
  75249. return this;
  75250. };
  75251. /**
  75252. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  75253. * @returns The render target texture if present otherwise, null
  75254. */
  75255. ShadowGenerator.prototype.getShadowMap = function () {
  75256. return this._shadowMap;
  75257. };
  75258. /**
  75259. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  75260. * @returns The render target texture if the shadow map is present otherwise, null
  75261. */
  75262. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  75263. if (this._shadowMap2) {
  75264. return this._shadowMap2;
  75265. }
  75266. return this._shadowMap;
  75267. };
  75268. /**
  75269. * Helper function to add a mesh and its descendants to the list of shadow casters.
  75270. * @param mesh Mesh to add
  75271. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  75272. * @returns the Shadow Generator itself
  75273. */
  75274. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  75275. if (includeDescendants === void 0) { includeDescendants = true; }
  75276. var _a;
  75277. if (!this._shadowMap) {
  75278. return this;
  75279. }
  75280. if (!this._shadowMap.renderList) {
  75281. this._shadowMap.renderList = [];
  75282. }
  75283. this._shadowMap.renderList.push(mesh);
  75284. if (includeDescendants) {
  75285. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  75286. }
  75287. return this;
  75288. };
  75289. /**
  75290. * Helper function to remove a mesh and its descendants from the list of shadow casters
  75291. * @param mesh Mesh to remove
  75292. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  75293. * @returns the Shadow Generator itself
  75294. */
  75295. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  75296. if (includeDescendants === void 0) { includeDescendants = true; }
  75297. if (!this._shadowMap || !this._shadowMap.renderList) {
  75298. return this;
  75299. }
  75300. var index = this._shadowMap.renderList.indexOf(mesh);
  75301. if (index !== -1) {
  75302. this._shadowMap.renderList.splice(index, 1);
  75303. }
  75304. if (includeDescendants) {
  75305. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  75306. var child = _a[_i];
  75307. this.removeShadowCaster(child);
  75308. }
  75309. }
  75310. return this;
  75311. };
  75312. /**
  75313. * Returns the associated light object.
  75314. * @returns the light generating the shadow
  75315. */
  75316. ShadowGenerator.prototype.getLight = function () {
  75317. return this._light;
  75318. };
  75319. ShadowGenerator.prototype._initializeGenerator = function () {
  75320. this._light._markMeshesAsLightDirty();
  75321. this._initializeShadowMap();
  75322. };
  75323. ShadowGenerator.prototype._initializeShadowMap = function () {
  75324. var _this = this;
  75325. // Render target
  75326. var engine = this._scene.getEngine();
  75327. if (engine.webGLVersion > 1) {
  75328. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  75329. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  75330. }
  75331. else {
  75332. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  75333. }
  75334. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75335. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75336. this._shadowMap.anisotropicFilteringLevel = 1;
  75337. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  75338. this._shadowMap.renderParticles = false;
  75339. this._shadowMap.ignoreCameraViewport = true;
  75340. // Record Face Index before render.
  75341. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  75342. _this._currentFaceIndex = faceIndex;
  75343. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  75344. engine.setColorWrite(false);
  75345. }
  75346. });
  75347. // Custom render function.
  75348. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  75349. // Blur if required afer render.
  75350. this._shadowMap.onAfterUnbindObservable.add(function () {
  75351. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  75352. engine.setColorWrite(true);
  75353. }
  75354. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  75355. return;
  75356. }
  75357. var shadowMap = _this.getShadowMapForRendering();
  75358. if (shadowMap) {
  75359. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  75360. }
  75361. });
  75362. // Clear according to the chosen filter.
  75363. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  75364. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  75365. this._shadowMap.onClearObservable.add(function (engine) {
  75366. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  75367. engine.clear(clearOne, false, true, false);
  75368. }
  75369. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  75370. engine.clear(clearZero, true, true, false);
  75371. }
  75372. else {
  75373. engine.clear(clearOne, true, true, false);
  75374. }
  75375. });
  75376. };
  75377. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  75378. var _this = this;
  75379. var engine = this._scene.getEngine();
  75380. var targetSize = this._mapSize / this.blurScale;
  75381. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  75382. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  75383. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75384. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75385. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  75386. }
  75387. if (this.useKernelBlur) {
  75388. 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);
  75389. this._kernelBlurXPostprocess.width = targetSize;
  75390. this._kernelBlurXPostprocess.height = targetSize;
  75391. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  75392. effect.setTexture("textureSampler", _this._shadowMap);
  75393. });
  75394. 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);
  75395. this._kernelBlurXPostprocess.autoClear = false;
  75396. this._kernelBlurYPostprocess.autoClear = false;
  75397. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  75398. this._kernelBlurXPostprocess.packedFloat = true;
  75399. this._kernelBlurYPostprocess.packedFloat = true;
  75400. }
  75401. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  75402. }
  75403. else {
  75404. 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);
  75405. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  75406. effect.setFloat2("screenSize", targetSize, targetSize);
  75407. effect.setTexture("textureSampler", _this._shadowMap);
  75408. });
  75409. this._boxBlurPostprocess.autoClear = false;
  75410. this._blurPostProcesses = [this._boxBlurPostprocess];
  75411. }
  75412. };
  75413. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  75414. var index;
  75415. var engine = this._scene.getEngine();
  75416. if (depthOnlySubMeshes.length) {
  75417. engine.setColorWrite(false);
  75418. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  75419. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  75420. }
  75421. engine.setColorWrite(true);
  75422. }
  75423. for (index = 0; index < opaqueSubMeshes.length; index++) {
  75424. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  75425. }
  75426. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  75427. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  75428. }
  75429. if (this._transparencyShadow) {
  75430. for (index = 0; index < transparentSubMeshes.length; index++) {
  75431. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  75432. }
  75433. }
  75434. };
  75435. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  75436. var _this = this;
  75437. var mesh = subMesh.getRenderingMesh();
  75438. var scene = this._scene;
  75439. var engine = scene.getEngine();
  75440. var material = subMesh.getMaterial();
  75441. if (!material) {
  75442. return;
  75443. }
  75444. // Culling
  75445. engine.setState(material.backFaceCulling);
  75446. // Managing instances
  75447. var batch = mesh._getInstancesRenderList(subMesh._id);
  75448. if (batch.mustReturn) {
  75449. return;
  75450. }
  75451. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  75452. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  75453. engine.enableEffect(this._effect);
  75454. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  75455. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  75456. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  75457. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  75458. this._effect.setVector3("lightData", this._cachedDirection);
  75459. }
  75460. else {
  75461. this._effect.setVector3("lightData", this._cachedPosition);
  75462. }
  75463. if (scene.activeCamera) {
  75464. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  75465. }
  75466. // Alpha test
  75467. if (material && material.needAlphaTesting()) {
  75468. var alphaTexture = material.getAlphaTestTexture();
  75469. if (alphaTexture) {
  75470. this._effect.setTexture("diffuseSampler", alphaTexture);
  75471. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  75472. }
  75473. }
  75474. // Bones
  75475. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  75476. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  75477. }
  75478. // Morph targets
  75479. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  75480. if (this.forceBackFacesOnly) {
  75481. engine.setState(true, 0, false, true);
  75482. }
  75483. // Draw
  75484. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  75485. if (this.forceBackFacesOnly) {
  75486. engine.setState(true, 0, false, false);
  75487. }
  75488. }
  75489. else {
  75490. // Need to reset refresh rate of the shadowMap
  75491. if (this._shadowMap) {
  75492. this._shadowMap.resetRefreshCounter();
  75493. }
  75494. }
  75495. };
  75496. ShadowGenerator.prototype._applyFilterValues = function () {
  75497. if (!this._shadowMap) {
  75498. return;
  75499. }
  75500. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  75501. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  75502. }
  75503. else {
  75504. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  75505. }
  75506. };
  75507. /**
  75508. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  75509. * @param onCompiled Callback triggered at the and of the effects compilation
  75510. * @param options Sets of optional options forcing the compilation with different modes
  75511. */
  75512. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  75513. var _this = this;
  75514. var localOptions = __assign({ useInstances: false }, options);
  75515. var shadowMap = this.getShadowMap();
  75516. if (!shadowMap) {
  75517. if (onCompiled) {
  75518. onCompiled(this);
  75519. }
  75520. return;
  75521. }
  75522. var renderList = shadowMap.renderList;
  75523. if (!renderList) {
  75524. if (onCompiled) {
  75525. onCompiled(this);
  75526. }
  75527. return;
  75528. }
  75529. var subMeshes = new Array();
  75530. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  75531. var mesh = renderList_1[_i];
  75532. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  75533. }
  75534. if (subMeshes.length === 0) {
  75535. if (onCompiled) {
  75536. onCompiled(this);
  75537. }
  75538. return;
  75539. }
  75540. var currentIndex = 0;
  75541. var checkReady = function () {
  75542. if (!_this._scene || !_this._scene.getEngine()) {
  75543. return;
  75544. }
  75545. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  75546. currentIndex++;
  75547. if (currentIndex >= subMeshes.length) {
  75548. if (onCompiled) {
  75549. onCompiled(_this);
  75550. }
  75551. return;
  75552. }
  75553. }
  75554. setTimeout(checkReady, 16);
  75555. };
  75556. checkReady();
  75557. };
  75558. /**
  75559. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  75560. * @param options Sets of optional options forcing the compilation with different modes
  75561. * @returns A promise that resolves when the compilation completes
  75562. */
  75563. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  75564. var _this = this;
  75565. return new Promise(function (resolve) {
  75566. _this.forceCompilation(function () {
  75567. resolve();
  75568. }, options);
  75569. });
  75570. };
  75571. /**
  75572. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  75573. * @param subMesh The submesh we want to render in the shadow map
  75574. * @param useInstances Defines wether will draw in the map using instances
  75575. * @returns true if ready otherwise, false
  75576. */
  75577. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  75578. var defines = [];
  75579. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  75580. defines.push("#define FLOAT");
  75581. }
  75582. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  75583. defines.push("#define ESM");
  75584. }
  75585. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  75586. defines.push("#define DEPTHTEXTURE");
  75587. }
  75588. var attribs = [BABYLON.VertexBuffer.PositionKind];
  75589. var mesh = subMesh.getMesh();
  75590. var material = subMesh.getMaterial();
  75591. // Normal bias.
  75592. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  75593. attribs.push(BABYLON.VertexBuffer.NormalKind);
  75594. defines.push("#define NORMAL");
  75595. if (mesh.nonUniformScaling) {
  75596. defines.push("#define NONUNIFORMSCALING");
  75597. }
  75598. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  75599. defines.push("#define DIRECTIONINLIGHTDATA");
  75600. }
  75601. }
  75602. // Alpha test
  75603. if (material && material.needAlphaTesting()) {
  75604. var alphaTexture = material.getAlphaTestTexture();
  75605. if (alphaTexture) {
  75606. defines.push("#define ALPHATEST");
  75607. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  75608. attribs.push(BABYLON.VertexBuffer.UVKind);
  75609. defines.push("#define UV1");
  75610. }
  75611. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  75612. if (alphaTexture.coordinatesIndex === 1) {
  75613. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  75614. defines.push("#define UV2");
  75615. }
  75616. }
  75617. }
  75618. }
  75619. // Bones
  75620. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  75621. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  75622. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  75623. if (mesh.numBoneInfluencers > 4) {
  75624. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  75625. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  75626. }
  75627. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  75628. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  75629. }
  75630. else {
  75631. defines.push("#define NUM_BONE_INFLUENCERS 0");
  75632. }
  75633. // Morph targets
  75634. var manager = mesh.morphTargetManager;
  75635. var morphInfluencers = 0;
  75636. if (manager) {
  75637. if (manager.numInfluencers > 0) {
  75638. defines.push("#define MORPHTARGETS");
  75639. morphInfluencers = manager.numInfluencers;
  75640. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  75641. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  75642. }
  75643. }
  75644. // Instances
  75645. if (useInstances) {
  75646. defines.push("#define INSTANCES");
  75647. attribs.push("world0");
  75648. attribs.push("world1");
  75649. attribs.push("world2");
  75650. attribs.push("world3");
  75651. }
  75652. // Get correct effect
  75653. var join = defines.join("\n");
  75654. if (this._cachedDefines !== join) {
  75655. this._cachedDefines = join;
  75656. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  75657. }
  75658. if (!this._effect.isReady()) {
  75659. return false;
  75660. }
  75661. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  75662. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  75663. this._initializeBlurRTTAndPostProcesses();
  75664. }
  75665. }
  75666. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  75667. return false;
  75668. }
  75669. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  75670. return false;
  75671. }
  75672. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  75673. return false;
  75674. }
  75675. return true;
  75676. };
  75677. /**
  75678. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  75679. * @param defines Defines of the material we want to update
  75680. * @param lightIndex Index of the light in the enabled light list of the material
  75681. */
  75682. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  75683. var scene = this._scene;
  75684. var light = this._light;
  75685. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  75686. return;
  75687. }
  75688. defines["SHADOW" + lightIndex] = true;
  75689. if (this.useContactHardeningShadow) {
  75690. defines["SHADOWPCSS" + lightIndex] = true;
  75691. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  75692. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  75693. }
  75694. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  75695. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  75696. }
  75697. // else default to high.
  75698. }
  75699. if (this.usePercentageCloserFiltering) {
  75700. defines["SHADOWPCF" + lightIndex] = true;
  75701. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  75702. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  75703. }
  75704. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  75705. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  75706. }
  75707. // else default to high.
  75708. }
  75709. else if (this.usePoissonSampling) {
  75710. defines["SHADOWPOISSON" + lightIndex] = true;
  75711. }
  75712. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  75713. defines["SHADOWESM" + lightIndex] = true;
  75714. }
  75715. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  75716. defines["SHADOWCLOSEESM" + lightIndex] = true;
  75717. }
  75718. if (light.needCube()) {
  75719. defines["SHADOWCUBE" + lightIndex] = true;
  75720. }
  75721. };
  75722. /**
  75723. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  75724. * defined in the generator but impacting the effect).
  75725. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  75726. * @param effect The effect we are binfing the information for
  75727. */
  75728. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  75729. var light = this._light;
  75730. var scene = this._scene;
  75731. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  75732. return;
  75733. }
  75734. var camera = scene.activeCamera;
  75735. if (!camera) {
  75736. return;
  75737. }
  75738. var shadowMap = this.getShadowMap();
  75739. if (!shadowMap) {
  75740. return;
  75741. }
  75742. if (!light.needCube()) {
  75743. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  75744. }
  75745. // Only PCF uses depth stencil texture.
  75746. if (this._filter === ShadowGenerator.FILTER_PCF) {
  75747. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  75748. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  75749. }
  75750. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  75751. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  75752. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  75753. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  75754. }
  75755. else {
  75756. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  75757. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  75758. }
  75759. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  75760. };
  75761. /**
  75762. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  75763. * (eq to shadow prjection matrix * light transform matrix)
  75764. * @returns The transform matrix used to create the shadow map
  75765. */
  75766. ShadowGenerator.prototype.getTransformMatrix = function () {
  75767. var scene = this._scene;
  75768. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  75769. return this._transformMatrix;
  75770. }
  75771. this._currentRenderID = scene.getRenderId();
  75772. this._currentFaceIndexCache = this._currentFaceIndex;
  75773. var lightPosition = this._light.position;
  75774. if (this._light.computeTransformedInformation()) {
  75775. lightPosition = this._light.transformedPosition;
  75776. }
  75777. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  75778. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  75779. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  75780. }
  75781. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  75782. this._cachedPosition.copyFrom(lightPosition);
  75783. this._cachedDirection.copyFrom(this._lightDirection);
  75784. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  75785. var shadowMap = this.getShadowMap();
  75786. if (shadowMap) {
  75787. var renderList = shadowMap.renderList;
  75788. if (renderList) {
  75789. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  75790. }
  75791. }
  75792. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  75793. }
  75794. return this._transformMatrix;
  75795. };
  75796. /**
  75797. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  75798. * Cube and 2D textures for instance.
  75799. */
  75800. ShadowGenerator.prototype.recreateShadowMap = function () {
  75801. var shadowMap = this._shadowMap;
  75802. if (!shadowMap) {
  75803. return;
  75804. }
  75805. // Track render list.
  75806. var renderList = shadowMap.renderList;
  75807. // Clean up existing data.
  75808. this._disposeRTTandPostProcesses();
  75809. // Reinitializes.
  75810. this._initializeGenerator();
  75811. // Reaffect the filter to ensure a correct fallback if necessary.
  75812. this.filter = this.filter;
  75813. // Reaffect the filter.
  75814. this._applyFilterValues();
  75815. // Reaffect Render List.
  75816. this._shadowMap.renderList = renderList;
  75817. };
  75818. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  75819. if (this._shadowMap2) {
  75820. this._shadowMap2.dispose();
  75821. this._shadowMap2 = null;
  75822. }
  75823. if (this._boxBlurPostprocess) {
  75824. this._boxBlurPostprocess.dispose();
  75825. this._boxBlurPostprocess = null;
  75826. }
  75827. if (this._kernelBlurXPostprocess) {
  75828. this._kernelBlurXPostprocess.dispose();
  75829. this._kernelBlurXPostprocess = null;
  75830. }
  75831. if (this._kernelBlurYPostprocess) {
  75832. this._kernelBlurYPostprocess.dispose();
  75833. this._kernelBlurYPostprocess = null;
  75834. }
  75835. this._blurPostProcesses = [];
  75836. };
  75837. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  75838. if (this._shadowMap) {
  75839. this._shadowMap.dispose();
  75840. this._shadowMap = null;
  75841. }
  75842. this._disposeBlurPostProcesses();
  75843. };
  75844. /**
  75845. * Disposes the ShadowGenerator.
  75846. * Returns nothing.
  75847. */
  75848. ShadowGenerator.prototype.dispose = function () {
  75849. this._disposeRTTandPostProcesses();
  75850. if (this._light) {
  75851. this._light._shadowGenerator = null;
  75852. this._light._markMeshesAsLightDirty();
  75853. }
  75854. };
  75855. /**
  75856. * Serializes the shadow generator setup to a json object.
  75857. * @returns The serialized JSON object
  75858. */
  75859. ShadowGenerator.prototype.serialize = function () {
  75860. var serializationObject = {};
  75861. var shadowMap = this.getShadowMap();
  75862. if (!shadowMap) {
  75863. return serializationObject;
  75864. }
  75865. serializationObject.lightId = this._light.id;
  75866. serializationObject.mapSize = shadowMap.getRenderSize();
  75867. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  75868. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  75869. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  75870. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  75871. serializationObject.usePoissonSampling = this.usePoissonSampling;
  75872. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  75873. serializationObject.depthScale = this.depthScale;
  75874. serializationObject.darkness = this.getDarkness();
  75875. serializationObject.blurBoxOffset = this.blurBoxOffset;
  75876. serializationObject.blurKernel = this.blurKernel;
  75877. serializationObject.blurScale = this.blurScale;
  75878. serializationObject.useKernelBlur = this.useKernelBlur;
  75879. serializationObject.transparencyShadow = this._transparencyShadow;
  75880. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  75881. serializationObject.bias = this.bias;
  75882. serializationObject.normalBias = this.normalBias;
  75883. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  75884. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  75885. serializationObject.filteringQuality = this.filteringQuality;
  75886. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  75887. serializationObject.renderList = [];
  75888. if (shadowMap.renderList) {
  75889. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  75890. var mesh = shadowMap.renderList[meshIndex];
  75891. serializationObject.renderList.push(mesh.id);
  75892. }
  75893. }
  75894. return serializationObject;
  75895. };
  75896. /**
  75897. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  75898. * @param parsedShadowGenerator The JSON object to parse
  75899. * @param scene The scene to create the shadow map for
  75900. * @returns The parsed shadow generator
  75901. */
  75902. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  75903. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  75904. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  75905. var shadowMap = shadowGenerator.getShadowMap();
  75906. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  75907. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  75908. meshes.forEach(function (mesh) {
  75909. if (!shadowMap) {
  75910. return;
  75911. }
  75912. if (!shadowMap.renderList) {
  75913. shadowMap.renderList = [];
  75914. }
  75915. shadowMap.renderList.push(mesh);
  75916. });
  75917. }
  75918. if (parsedShadowGenerator.usePoissonSampling) {
  75919. shadowGenerator.usePoissonSampling = true;
  75920. }
  75921. else if (parsedShadowGenerator.useExponentialShadowMap) {
  75922. shadowGenerator.useExponentialShadowMap = true;
  75923. }
  75924. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  75925. shadowGenerator.useBlurExponentialShadowMap = true;
  75926. }
  75927. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  75928. shadowGenerator.useCloseExponentialShadowMap = true;
  75929. }
  75930. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  75931. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  75932. }
  75933. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  75934. shadowGenerator.usePercentageCloserFiltering = true;
  75935. }
  75936. else if (parsedShadowGenerator.useContactHardeningShadow) {
  75937. shadowGenerator.useContactHardeningShadow = true;
  75938. }
  75939. if (parsedShadowGenerator.filteringQuality) {
  75940. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  75941. }
  75942. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  75943. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  75944. }
  75945. // Backward compat
  75946. else if (parsedShadowGenerator.useVarianceShadowMap) {
  75947. shadowGenerator.useExponentialShadowMap = true;
  75948. }
  75949. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  75950. shadowGenerator.useBlurExponentialShadowMap = true;
  75951. }
  75952. if (parsedShadowGenerator.depthScale) {
  75953. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  75954. }
  75955. if (parsedShadowGenerator.blurScale) {
  75956. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  75957. }
  75958. if (parsedShadowGenerator.blurBoxOffset) {
  75959. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  75960. }
  75961. if (parsedShadowGenerator.useKernelBlur) {
  75962. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  75963. }
  75964. if (parsedShadowGenerator.blurKernel) {
  75965. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  75966. }
  75967. if (parsedShadowGenerator.bias !== undefined) {
  75968. shadowGenerator.bias = parsedShadowGenerator.bias;
  75969. }
  75970. if (parsedShadowGenerator.normalBias !== undefined) {
  75971. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  75972. }
  75973. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  75974. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  75975. }
  75976. if (parsedShadowGenerator.darkness) {
  75977. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  75978. }
  75979. if (parsedShadowGenerator.transparencyShadow) {
  75980. shadowGenerator.setTransparencyShadow(true);
  75981. }
  75982. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  75983. return shadowGenerator;
  75984. };
  75985. /**
  75986. * Shadow generator mode None: no filtering applied.
  75987. */
  75988. ShadowGenerator.FILTER_NONE = 0;
  75989. /**
  75990. * Shadow generator mode ESM: Exponential Shadow Mapping.
  75991. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  75992. */
  75993. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  75994. /**
  75995. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  75996. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  75997. */
  75998. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  75999. /**
  76000. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  76001. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  76002. */
  76003. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  76004. /**
  76005. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  76006. * edge artifacts on steep falloff.
  76007. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  76008. */
  76009. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  76010. /**
  76011. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  76012. * edge artifacts on steep falloff.
  76013. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  76014. */
  76015. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  76016. /**
  76017. * Shadow generator mode PCF: Percentage Closer Filtering
  76018. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  76019. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  76020. */
  76021. ShadowGenerator.FILTER_PCF = 6;
  76022. /**
  76023. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  76024. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  76025. * Contact Hardening
  76026. */
  76027. ShadowGenerator.FILTER_PCSS = 7;
  76028. /**
  76029. * Reserved for PCF and PCSS
  76030. * Highest Quality.
  76031. *
  76032. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  76033. *
  76034. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  76035. */
  76036. ShadowGenerator.QUALITY_HIGH = 0;
  76037. /**
  76038. * Reserved for PCF and PCSS
  76039. * Good tradeoff for quality/perf cross devices
  76040. *
  76041. * Execute PCF on a 3*3 kernel.
  76042. *
  76043. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  76044. */
  76045. ShadowGenerator.QUALITY_MEDIUM = 1;
  76046. /**
  76047. * Reserved for PCF and PCSS
  76048. * The lowest quality but the fastest.
  76049. *
  76050. * Execute PCF on a 1*1 kernel.
  76051. *
  76052. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  76053. */
  76054. ShadowGenerator.QUALITY_LOW = 2;
  76055. return ShadowGenerator;
  76056. }());
  76057. BABYLON.ShadowGenerator = ShadowGenerator;
  76058. })(BABYLON || (BABYLON = {}));
  76059. //# sourceMappingURL=babylon.shadowGenerator.js.map
  76060. var BABYLON;
  76061. (function (BABYLON) {
  76062. // Adds the parser to the scene parsers.
  76063. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR, function (parsedData, scene, container, rootUrl) {
  76064. // Shadows
  76065. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  76066. for (var index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  76067. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  76068. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  76069. // SG would be available on their associated lights
  76070. }
  76071. }
  76072. });
  76073. /**
  76074. * Defines the shadow generator component responsible to manage any shadow generators
  76075. * in a given scene.
  76076. */
  76077. var ShadowGeneratorSceneComponent = /** @class */ (function () {
  76078. /**
  76079. * Creates a new instance of the component for the given scene
  76080. * @param scene Defines the scene to register the component in
  76081. */
  76082. function ShadowGeneratorSceneComponent(scene) {
  76083. /**
  76084. * The component name helpfull to identify the component in the list of scene components.
  76085. */
  76086. this.name = BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR;
  76087. this.scene = scene;
  76088. }
  76089. /**
  76090. * Registers the component in a given scene
  76091. */
  76092. ShadowGeneratorSceneComponent.prototype.register = function () {
  76093. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets);
  76094. };
  76095. /**
  76096. * Rebuilds the elements related to this component in case of
  76097. * context lost for instance.
  76098. */
  76099. ShadowGeneratorSceneComponent.prototype.rebuild = function () {
  76100. // Nothing To Do Here.
  76101. };
  76102. /**
  76103. * Serializes the component data to the specified json object
  76104. * @param serializationObject The object to serialize to
  76105. */
  76106. ShadowGeneratorSceneComponent.prototype.serialize = function (serializationObject) {
  76107. // Shadows
  76108. serializationObject.shadowGenerators = [];
  76109. var lights = this.scene.lights;
  76110. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  76111. var light = lights_1[_i];
  76112. var shadowGenerator = light.getShadowGenerator();
  76113. if (shadowGenerator) {
  76114. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  76115. }
  76116. }
  76117. };
  76118. /**
  76119. * Adds all the element from the container to the scene
  76120. * @param container the container holding the elements
  76121. */
  76122. ShadowGeneratorSceneComponent.prototype.addFromContainer = function (container) {
  76123. // Nothing To Do Here. (directly attached to a light)
  76124. };
  76125. /**
  76126. * Removes all the elements in the container from the scene
  76127. * @param container contains the elements to remove
  76128. */
  76129. ShadowGeneratorSceneComponent.prototype.removeFromContainer = function (container) {
  76130. // Nothing To Do Here. (directly attached to a light)
  76131. };
  76132. /**
  76133. * Rebuilds the elements related to this component in case of
  76134. * context lost for instance.
  76135. */
  76136. ShadowGeneratorSceneComponent.prototype.dispose = function () {
  76137. // Nothing To Do Here.
  76138. };
  76139. ShadowGeneratorSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  76140. // Shadows
  76141. var scene = this.scene;
  76142. if (this.scene.shadowsEnabled) {
  76143. for (var lightIndex = 0; lightIndex < scene.lights.length; lightIndex++) {
  76144. var light = scene.lights[lightIndex];
  76145. var shadowGenerator = light.getShadowGenerator();
  76146. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  76147. var shadowMap = (shadowGenerator.getShadowMap());
  76148. if (scene.textures.indexOf(shadowMap) !== -1) {
  76149. renderTargets.push(shadowMap);
  76150. }
  76151. }
  76152. }
  76153. }
  76154. };
  76155. return ShadowGeneratorSceneComponent;
  76156. }());
  76157. BABYLON.ShadowGeneratorSceneComponent = ShadowGeneratorSceneComponent;
  76158. })(BABYLON || (BABYLON = {}));
  76159. //# sourceMappingURL=babylon.shadowGeneratorSceneComponent.js.map
  76160. var BABYLON;
  76161. (function (BABYLON) {
  76162. /**
  76163. * Class used for the default loading screen
  76164. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  76165. */
  76166. var DefaultLoadingScreen = /** @class */ (function () {
  76167. /**
  76168. * Creates a new default loading screen
  76169. * @param _renderingCanvas defines the canvas used to render the scene
  76170. * @param _loadingText defines the default text to display
  76171. * @param _loadingDivBackgroundColor defines the default background color
  76172. */
  76173. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  76174. if (_loadingText === void 0) { _loadingText = ""; }
  76175. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  76176. var _this = this;
  76177. this._renderingCanvas = _renderingCanvas;
  76178. this._loadingText = _loadingText;
  76179. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  76180. // Resize
  76181. this._resizeLoadingUI = function () {
  76182. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  76183. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  76184. if (!_this._loadingDiv) {
  76185. return;
  76186. }
  76187. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  76188. _this._loadingDiv.style.left = canvasRect.left + "px";
  76189. _this._loadingDiv.style.top = canvasRect.top + "px";
  76190. _this._loadingDiv.style.width = canvasRect.width + "px";
  76191. _this._loadingDiv.style.height = canvasRect.height + "px";
  76192. };
  76193. }
  76194. /**
  76195. * Function called to display the loading screen
  76196. */
  76197. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  76198. if (this._loadingDiv) {
  76199. // Do not add a loading screen if there is already one
  76200. return;
  76201. }
  76202. this._loadingDiv = document.createElement("div");
  76203. this._loadingDiv.id = "babylonjsLoadingDiv";
  76204. this._loadingDiv.style.opacity = "0";
  76205. this._loadingDiv.style.transition = "opacity 1.5s ease";
  76206. this._loadingDiv.style.pointerEvents = "none";
  76207. // Loading text
  76208. this._loadingTextDiv = document.createElement("div");
  76209. this._loadingTextDiv.style.position = "absolute";
  76210. this._loadingTextDiv.style.left = "0";
  76211. this._loadingTextDiv.style.top = "50%";
  76212. this._loadingTextDiv.style.marginTop = "80px";
  76213. this._loadingTextDiv.style.width = "100%";
  76214. this._loadingTextDiv.style.height = "20px";
  76215. this._loadingTextDiv.style.fontFamily = "Arial";
  76216. this._loadingTextDiv.style.fontSize = "14px";
  76217. this._loadingTextDiv.style.color = "white";
  76218. this._loadingTextDiv.style.textAlign = "center";
  76219. this._loadingTextDiv.innerHTML = "Loading";
  76220. this._loadingDiv.appendChild(this._loadingTextDiv);
  76221. //set the predefined text
  76222. this._loadingTextDiv.innerHTML = this._loadingText;
  76223. // Generating keyframes
  76224. var style = document.createElement('style');
  76225. style.type = 'text/css';
  76226. 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 }";
  76227. style.innerHTML = keyFrames;
  76228. document.getElementsByTagName('head')[0].appendChild(style);
  76229. // Loading img
  76230. var imgBack = new Image();
  76231. 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";
  76232. imgBack.style.position = "absolute";
  76233. imgBack.style.left = "50%";
  76234. imgBack.style.top = "50%";
  76235. imgBack.style.marginLeft = "-60px";
  76236. imgBack.style.marginTop = "-60px";
  76237. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  76238. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  76239. imgBack.style.transformOrigin = "50% 50%";
  76240. imgBack.style.webkitTransformOrigin = "50% 50%";
  76241. this._loadingDiv.appendChild(imgBack);
  76242. this._resizeLoadingUI();
  76243. window.addEventListener("resize", this._resizeLoadingUI);
  76244. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  76245. document.body.appendChild(this._loadingDiv);
  76246. this._loadingDiv.style.opacity = "1";
  76247. };
  76248. /**
  76249. * Function called to hide the loading screen
  76250. */
  76251. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  76252. var _this = this;
  76253. if (!this._loadingDiv) {
  76254. return;
  76255. }
  76256. var onTransitionEnd = function () {
  76257. if (!_this._loadingDiv) {
  76258. return;
  76259. }
  76260. document.body.removeChild(_this._loadingDiv);
  76261. window.removeEventListener("resize", _this._resizeLoadingUI);
  76262. _this._loadingDiv = null;
  76263. };
  76264. this._loadingDiv.style.opacity = "0";
  76265. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  76266. };
  76267. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  76268. get: function () {
  76269. return this._loadingText;
  76270. },
  76271. /**
  76272. * Gets or sets the text to display while loading
  76273. */
  76274. set: function (text) {
  76275. this._loadingText = text;
  76276. if (this._loadingTextDiv) {
  76277. this._loadingTextDiv.innerHTML = this._loadingText;
  76278. }
  76279. },
  76280. enumerable: true,
  76281. configurable: true
  76282. });
  76283. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  76284. /**
  76285. * Gets or sets the color to use for the background
  76286. */
  76287. get: function () {
  76288. return this._loadingDivBackgroundColor;
  76289. },
  76290. set: function (color) {
  76291. this._loadingDivBackgroundColor = color;
  76292. if (!this._loadingDiv) {
  76293. return;
  76294. }
  76295. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  76296. },
  76297. enumerable: true,
  76298. configurable: true
  76299. });
  76300. return DefaultLoadingScreen;
  76301. }());
  76302. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  76303. })(BABYLON || (BABYLON = {}));
  76304. //# sourceMappingURL=babylon.loadingScreen.js.map
  76305. var BABYLON;
  76306. (function (BABYLON) {
  76307. /**
  76308. * Class used to represent data loading progression
  76309. */
  76310. var SceneLoaderProgressEvent = /** @class */ (function () {
  76311. /**
  76312. * Create a new progress event
  76313. * @param lengthComputable defines if data length to load can be evaluated
  76314. * @param loaded defines the loaded data length
  76315. * @param total defines the data length to load
  76316. */
  76317. function SceneLoaderProgressEvent(
  76318. /** defines if data length to load can be evaluated */
  76319. lengthComputable,
  76320. /** defines the loaded data length */
  76321. loaded,
  76322. /** defines the data length to load */
  76323. total) {
  76324. this.lengthComputable = lengthComputable;
  76325. this.loaded = loaded;
  76326. this.total = total;
  76327. }
  76328. /**
  76329. * Creates a new SceneLoaderProgressEvent from a ProgressEvent
  76330. * @param event defines the source event
  76331. * @returns a new SceneLoaderProgressEvent
  76332. */
  76333. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  76334. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  76335. };
  76336. return SceneLoaderProgressEvent;
  76337. }());
  76338. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  76339. /**
  76340. * Class used to load scene from various file formats using registered plugins
  76341. * @see http://doc.babylonjs.com/how_to/load_from_any_file_type
  76342. */
  76343. var SceneLoader = /** @class */ (function () {
  76344. function SceneLoader() {
  76345. }
  76346. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  76347. /**
  76348. * Gets or sets a boolean indicating if entire scene must be loaded even if scene contains incremental data
  76349. */
  76350. get: function () {
  76351. return SceneLoader._ForceFullSceneLoadingForIncremental;
  76352. },
  76353. set: function (value) {
  76354. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  76355. },
  76356. enumerable: true,
  76357. configurable: true
  76358. });
  76359. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  76360. /**
  76361. * Gets or sets a boolean indicating if loading screen must be displayed while loading a scene
  76362. */
  76363. get: function () {
  76364. return SceneLoader._ShowLoadingScreen;
  76365. },
  76366. set: function (value) {
  76367. SceneLoader._ShowLoadingScreen = value;
  76368. },
  76369. enumerable: true,
  76370. configurable: true
  76371. });
  76372. Object.defineProperty(SceneLoader, "loggingLevel", {
  76373. /**
  76374. * Defines the current logging level (while loading the scene)
  76375. * @ignorenaming
  76376. */
  76377. get: function () {
  76378. return SceneLoader._loggingLevel;
  76379. },
  76380. set: function (value) {
  76381. SceneLoader._loggingLevel = value;
  76382. },
  76383. enumerable: true,
  76384. configurable: true
  76385. });
  76386. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  76387. /**
  76388. * Gets or set a boolean indicating if matrix weights must be cleaned upon loading
  76389. */
  76390. get: function () {
  76391. return SceneLoader._CleanBoneMatrixWeights;
  76392. },
  76393. set: function (value) {
  76394. SceneLoader._CleanBoneMatrixWeights = value;
  76395. },
  76396. enumerable: true,
  76397. configurable: true
  76398. });
  76399. SceneLoader._getDefaultPlugin = function () {
  76400. return SceneLoader._registeredPlugins[".babylon"];
  76401. };
  76402. SceneLoader._getPluginForExtension = function (extension) {
  76403. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  76404. if (registeredPlugin) {
  76405. return registeredPlugin;
  76406. }
  76407. 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");
  76408. return SceneLoader._getDefaultPlugin();
  76409. };
  76410. SceneLoader._getPluginForDirectLoad = function (data) {
  76411. for (var extension in SceneLoader._registeredPlugins) {
  76412. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  76413. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  76414. return SceneLoader._registeredPlugins[extension];
  76415. }
  76416. }
  76417. return SceneLoader._getDefaultPlugin();
  76418. };
  76419. SceneLoader._getPluginForFilename = function (sceneFilename) {
  76420. var queryStringPosition = sceneFilename.indexOf("?");
  76421. if (queryStringPosition !== -1) {
  76422. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  76423. }
  76424. var dotPosition = sceneFilename.lastIndexOf(".");
  76425. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  76426. return SceneLoader._getPluginForExtension(extension);
  76427. };
  76428. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  76429. SceneLoader._getDirectLoad = function (sceneFilename) {
  76430. if (sceneFilename.substr(0, 5) === "data:") {
  76431. return sceneFilename.substr(5);
  76432. }
  76433. return null;
  76434. };
  76435. SceneLoader._loadData = function (fileInfo, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  76436. var directLoad = SceneLoader._getDirectLoad(fileInfo.name);
  76437. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(fileInfo.name) : SceneLoader._getPluginForFilename(fileInfo.name));
  76438. var plugin;
  76439. if (registeredPlugin.plugin.createPlugin) {
  76440. plugin = registeredPlugin.plugin.createPlugin();
  76441. }
  76442. else {
  76443. plugin = registeredPlugin.plugin;
  76444. }
  76445. var useArrayBuffer = registeredPlugin.isBinary;
  76446. var database;
  76447. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  76448. var dataCallback = function (data, responseURL) {
  76449. if (scene.isDisposed) {
  76450. onError("Scene has been disposed");
  76451. return;
  76452. }
  76453. scene.database = database;
  76454. onSuccess(plugin, data, responseURL);
  76455. };
  76456. var request = null;
  76457. var pluginDisposed = false;
  76458. var onDisposeObservable = plugin.onDisposeObservable;
  76459. if (onDisposeObservable) {
  76460. onDisposeObservable.add(function () {
  76461. pluginDisposed = true;
  76462. if (request) {
  76463. request.abort();
  76464. request = null;
  76465. }
  76466. onDispose();
  76467. });
  76468. }
  76469. var manifestChecked = function () {
  76470. if (pluginDisposed) {
  76471. return;
  76472. }
  76473. request = BABYLON.Tools.LoadFile(fileInfo.url, dataCallback, onProgress ? function (event) {
  76474. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  76475. } : undefined, database, useArrayBuffer, function (request, exception) {
  76476. onError("Failed to load scene." + (exception ? " " + exception.message : ""), exception);
  76477. });
  76478. };
  76479. if (directLoad) {
  76480. dataCallback(directLoad);
  76481. return plugin;
  76482. }
  76483. if (fileInfo.rootUrl.indexOf("file:") === -1) {
  76484. var engine = scene.getEngine();
  76485. var canUseOfflineSupport = engine.enableOfflineSupport;
  76486. if (canUseOfflineSupport) {
  76487. // Also check for exceptions
  76488. var exceptionFound = false;
  76489. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  76490. var regex = _a[_i];
  76491. if (regex.test(fileInfo.url)) {
  76492. exceptionFound = true;
  76493. break;
  76494. }
  76495. }
  76496. canUseOfflineSupport = !exceptionFound;
  76497. }
  76498. if (canUseOfflineSupport) {
  76499. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  76500. database = new BABYLON.Database(fileInfo.url, manifestChecked, engine.disableManifestCheck);
  76501. }
  76502. else {
  76503. manifestChecked();
  76504. }
  76505. }
  76506. // Loading file from disk via input file or drag'n'drop
  76507. else {
  76508. var file = BABYLON.FilesInput.FilesToLoad[fileInfo.name.toLowerCase()];
  76509. if (file) {
  76510. request = BABYLON.Tools.ReadFile(file, dataCallback, onProgress, useArrayBuffer);
  76511. }
  76512. else {
  76513. onError("Unable to find file named " + fileInfo.name);
  76514. }
  76515. }
  76516. return plugin;
  76517. };
  76518. SceneLoader._getFileInfo = function (rootUrl, sceneFilename) {
  76519. var url;
  76520. var name;
  76521. if (!sceneFilename) {
  76522. url = rootUrl;
  76523. name = BABYLON.Tools.GetFilename(rootUrl);
  76524. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  76525. }
  76526. else {
  76527. if (sceneFilename.substr(0, 1) === "/") {
  76528. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  76529. return null;
  76530. }
  76531. url = rootUrl + sceneFilename;
  76532. name = sceneFilename;
  76533. }
  76534. return {
  76535. url: url,
  76536. rootUrl: rootUrl,
  76537. name: name
  76538. };
  76539. };
  76540. // Public functions
  76541. /**
  76542. * Gets a plugin that can load the given extension
  76543. * @param extension defines the extension to load
  76544. * @returns a plugin or null if none works
  76545. */
  76546. SceneLoader.GetPluginForExtension = function (extension) {
  76547. return SceneLoader._getPluginForExtension(extension).plugin;
  76548. };
  76549. /**
  76550. * Gets a boolean indicating that the given extension can be loaded
  76551. * @param extension defines the extension to load
  76552. * @returns true if the extension is supported
  76553. */
  76554. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  76555. return !!SceneLoader._registeredPlugins[extension];
  76556. };
  76557. /**
  76558. * Adds a new plugin to the list of registered plugins
  76559. * @param plugin defines the plugin to add
  76560. */
  76561. SceneLoader.RegisterPlugin = function (plugin) {
  76562. if (typeof plugin.extensions === "string") {
  76563. var extension = plugin.extensions;
  76564. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  76565. plugin: plugin,
  76566. isBinary: false
  76567. };
  76568. }
  76569. else {
  76570. var extensions = plugin.extensions;
  76571. Object.keys(extensions).forEach(function (extension) {
  76572. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  76573. plugin: plugin,
  76574. isBinary: extensions[extension].isBinary
  76575. };
  76576. });
  76577. }
  76578. };
  76579. /**
  76580. * Import meshes into a scene
  76581. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  76582. * @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)
  76583. * @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)
  76584. * @param scene the instance of BABYLON.Scene to append to
  76585. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  76586. * @param onProgress a callback with a progress event for each file being loaded
  76587. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  76588. * @param pluginExtension the extension used to determine the plugin
  76589. * @returns The loaded plugin
  76590. */
  76591. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  76592. if (sceneFilename === void 0) { sceneFilename = ""; }
  76593. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76594. if (onSuccess === void 0) { onSuccess = null; }
  76595. if (onProgress === void 0) { onProgress = null; }
  76596. if (onError === void 0) { onError = null; }
  76597. if (pluginExtension === void 0) { pluginExtension = null; }
  76598. if (!scene) {
  76599. BABYLON.Tools.Error("No scene available to import mesh to");
  76600. return null;
  76601. }
  76602. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  76603. if (!fileInfo) {
  76604. return null;
  76605. }
  76606. var loadingToken = {};
  76607. scene._addPendingData(loadingToken);
  76608. var disposeHandler = function () {
  76609. scene._removePendingData(loadingToken);
  76610. };
  76611. var errorHandler = function (message, exception) {
  76612. var errorMessage = "Unable to import meshes from " + fileInfo.url + ": " + message;
  76613. if (onError) {
  76614. onError(scene, errorMessage, exception);
  76615. }
  76616. else {
  76617. BABYLON.Tools.Error(errorMessage);
  76618. // should the exception be thrown?
  76619. }
  76620. disposeHandler();
  76621. };
  76622. var progressHandler = onProgress ? function (event) {
  76623. try {
  76624. onProgress(event);
  76625. }
  76626. catch (e) {
  76627. errorHandler("Error in onProgress callback", e);
  76628. }
  76629. } : undefined;
  76630. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  76631. scene.importedMeshesFiles.push(fileInfo.url);
  76632. if (onSuccess) {
  76633. try {
  76634. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  76635. }
  76636. catch (e) {
  76637. errorHandler("Error in onSuccess callback", e);
  76638. }
  76639. }
  76640. scene._removePendingData(loadingToken);
  76641. };
  76642. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  76643. if (plugin.rewriteRootURL) {
  76644. fileInfo.rootUrl = plugin.rewriteRootURL(fileInfo.rootUrl, responseURL);
  76645. }
  76646. if (plugin.importMesh) {
  76647. var syncedPlugin = plugin;
  76648. var meshes = new Array();
  76649. var particleSystems = new Array();
  76650. var skeletons = new Array();
  76651. if (!syncedPlugin.importMesh(meshNames, scene, data, fileInfo.rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  76652. return;
  76653. }
  76654. scene.loadingPluginName = plugin.name;
  76655. successHandler(meshes, particleSystems, skeletons, []);
  76656. }
  76657. else {
  76658. var asyncedPlugin = plugin;
  76659. asyncedPlugin.importMeshAsync(meshNames, scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (result) {
  76660. scene.loadingPluginName = plugin.name;
  76661. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  76662. }).catch(function (error) {
  76663. errorHandler(error.message, error);
  76664. });
  76665. }
  76666. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  76667. };
  76668. /**
  76669. * Import meshes into a scene
  76670. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  76671. * @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)
  76672. * @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)
  76673. * @param scene the instance of BABYLON.Scene to append to
  76674. * @param onProgress a callback with a progress event for each file being loaded
  76675. * @param pluginExtension the extension used to determine the plugin
  76676. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  76677. */
  76678. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  76679. if (sceneFilename === void 0) { sceneFilename = ""; }
  76680. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76681. if (onProgress === void 0) { onProgress = null; }
  76682. if (pluginExtension === void 0) { pluginExtension = null; }
  76683. return new Promise(function (resolve, reject) {
  76684. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  76685. resolve({
  76686. meshes: meshes,
  76687. particleSystems: particleSystems,
  76688. skeletons: skeletons,
  76689. animationGroups: animationGroups
  76690. });
  76691. }, onProgress, function (scene, message, exception) {
  76692. reject(exception || new Error(message));
  76693. }, pluginExtension);
  76694. });
  76695. };
  76696. /**
  76697. * Load a scene
  76698. * @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)
  76699. * @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)
  76700. * @param engine is the instance of BABYLON.Engine to use to create the scene
  76701. * @param onSuccess a callback with the scene when import succeeds
  76702. * @param onProgress a callback with a progress event for each file being loaded
  76703. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  76704. * @param pluginExtension the extension used to determine the plugin
  76705. * @returns The loaded plugin
  76706. */
  76707. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  76708. if (onSuccess === void 0) { onSuccess = null; }
  76709. if (onProgress === void 0) { onProgress = null; }
  76710. if (onError === void 0) { onError = null; }
  76711. if (pluginExtension === void 0) { pluginExtension = null; }
  76712. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  76713. };
  76714. /**
  76715. * Load a scene
  76716. * @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)
  76717. * @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)
  76718. * @param engine is the instance of BABYLON.Engine to use to create the scene
  76719. * @param onProgress a callback with a progress event for each file being loaded
  76720. * @param pluginExtension the extension used to determine the plugin
  76721. * @returns The loaded scene
  76722. */
  76723. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  76724. if (onProgress === void 0) { onProgress = null; }
  76725. if (pluginExtension === void 0) { pluginExtension = null; }
  76726. return new Promise(function (resolve, reject) {
  76727. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  76728. resolve(scene);
  76729. }, onProgress, function (scene, message, exception) {
  76730. reject(exception || new Error(message));
  76731. }, pluginExtension);
  76732. });
  76733. };
  76734. /**
  76735. * Append a scene
  76736. * @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)
  76737. * @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)
  76738. * @param scene is the instance of BABYLON.Scene to append to
  76739. * @param onSuccess a callback with the scene when import succeeds
  76740. * @param onProgress a callback with a progress event for each file being loaded
  76741. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  76742. * @param pluginExtension the extension used to determine the plugin
  76743. * @returns The loaded plugin
  76744. */
  76745. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  76746. if (sceneFilename === void 0) { sceneFilename = ""; }
  76747. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76748. if (onSuccess === void 0) { onSuccess = null; }
  76749. if (onProgress === void 0) { onProgress = null; }
  76750. if (onError === void 0) { onError = null; }
  76751. if (pluginExtension === void 0) { pluginExtension = null; }
  76752. if (!scene) {
  76753. BABYLON.Tools.Error("No scene available to append to");
  76754. return null;
  76755. }
  76756. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  76757. if (!fileInfo) {
  76758. return null;
  76759. }
  76760. if (SceneLoader.ShowLoadingScreen) {
  76761. scene.getEngine().displayLoadingUI();
  76762. }
  76763. var loadingToken = {};
  76764. scene._addPendingData(loadingToken);
  76765. var disposeHandler = function () {
  76766. scene._removePendingData(loadingToken);
  76767. scene.getEngine().hideLoadingUI();
  76768. };
  76769. var errorHandler = function (message, exception) {
  76770. var errorMessage = "Unable to load from " + fileInfo.url + (message ? ": " + message : "");
  76771. if (onError) {
  76772. onError(scene, errorMessage, exception);
  76773. }
  76774. else {
  76775. BABYLON.Tools.Error(errorMessage);
  76776. // should the exception be thrown?
  76777. }
  76778. disposeHandler();
  76779. };
  76780. var progressHandler = onProgress ? function (event) {
  76781. try {
  76782. onProgress(event);
  76783. }
  76784. catch (e) {
  76785. errorHandler("Error in onProgress callback", e);
  76786. }
  76787. } : undefined;
  76788. var successHandler = function () {
  76789. if (onSuccess) {
  76790. try {
  76791. onSuccess(scene);
  76792. }
  76793. catch (e) {
  76794. errorHandler("Error in onSuccess callback", e);
  76795. }
  76796. }
  76797. scene._removePendingData(loadingToken);
  76798. };
  76799. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  76800. if (plugin.load) {
  76801. var syncedPlugin = plugin;
  76802. if (!syncedPlugin.load(scene, data, fileInfo.rootUrl, errorHandler)) {
  76803. return;
  76804. }
  76805. scene.loadingPluginName = plugin.name;
  76806. successHandler();
  76807. }
  76808. else {
  76809. var asyncedPlugin = plugin;
  76810. asyncedPlugin.loadAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function () {
  76811. scene.loadingPluginName = plugin.name;
  76812. successHandler();
  76813. }).catch(function (error) {
  76814. errorHandler(error.message, error);
  76815. });
  76816. }
  76817. if (SceneLoader.ShowLoadingScreen) {
  76818. scene.executeWhenReady(function () {
  76819. scene.getEngine().hideLoadingUI();
  76820. });
  76821. }
  76822. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  76823. };
  76824. /**
  76825. * Append a scene
  76826. * @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)
  76827. * @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)
  76828. * @param scene is the instance of BABYLON.Scene to append to
  76829. * @param onProgress a callback with a progress event for each file being loaded
  76830. * @param pluginExtension the extension used to determine the plugin
  76831. * @returns The given scene
  76832. */
  76833. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  76834. if (sceneFilename === void 0) { sceneFilename = ""; }
  76835. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76836. if (onProgress === void 0) { onProgress = null; }
  76837. if (pluginExtension === void 0) { pluginExtension = null; }
  76838. return new Promise(function (resolve, reject) {
  76839. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  76840. resolve(scene);
  76841. }, onProgress, function (scene, message, exception) {
  76842. reject(exception || new Error(message));
  76843. }, pluginExtension);
  76844. });
  76845. };
  76846. /**
  76847. * Load a scene into an asset container
  76848. * @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)
  76849. * @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)
  76850. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  76851. * @param onSuccess a callback with the scene when import succeeds
  76852. * @param onProgress a callback with a progress event for each file being loaded
  76853. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  76854. * @param pluginExtension the extension used to determine the plugin
  76855. * @returns The loaded plugin
  76856. */
  76857. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  76858. if (sceneFilename === void 0) { sceneFilename = ""; }
  76859. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76860. if (onSuccess === void 0) { onSuccess = null; }
  76861. if (onProgress === void 0) { onProgress = null; }
  76862. if (onError === void 0) { onError = null; }
  76863. if (pluginExtension === void 0) { pluginExtension = null; }
  76864. if (!scene) {
  76865. BABYLON.Tools.Error("No scene available to load asset container to");
  76866. return null;
  76867. }
  76868. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  76869. if (!fileInfo) {
  76870. return null;
  76871. }
  76872. var loadingToken = {};
  76873. scene._addPendingData(loadingToken);
  76874. var disposeHandler = function () {
  76875. scene._removePendingData(loadingToken);
  76876. };
  76877. var errorHandler = function (message, exception) {
  76878. var errorMessage = "Unable to load assets from " + fileInfo.url + (message ? ": " + message : "");
  76879. if (onError) {
  76880. onError(scene, errorMessage, exception);
  76881. }
  76882. else {
  76883. BABYLON.Tools.Error(errorMessage);
  76884. // should the exception be thrown?
  76885. }
  76886. disposeHandler();
  76887. };
  76888. var progressHandler = onProgress ? function (event) {
  76889. try {
  76890. onProgress(event);
  76891. }
  76892. catch (e) {
  76893. errorHandler("Error in onProgress callback", e);
  76894. }
  76895. } : undefined;
  76896. var successHandler = function (assets) {
  76897. if (onSuccess) {
  76898. try {
  76899. onSuccess(assets);
  76900. }
  76901. catch (e) {
  76902. errorHandler("Error in onSuccess callback", e);
  76903. }
  76904. }
  76905. scene._removePendingData(loadingToken);
  76906. };
  76907. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  76908. if (plugin.loadAssetContainer) {
  76909. var syncedPlugin = plugin;
  76910. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, fileInfo.rootUrl, errorHandler);
  76911. if (!assetContainer) {
  76912. return;
  76913. }
  76914. scene.loadingPluginName = plugin.name;
  76915. successHandler(assetContainer);
  76916. }
  76917. else if (plugin.loadAssetContainerAsync) {
  76918. var asyncedPlugin = plugin;
  76919. asyncedPlugin.loadAssetContainerAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (assetContainer) {
  76920. scene.loadingPluginName = plugin.name;
  76921. successHandler(assetContainer);
  76922. }).catch(function (error) {
  76923. errorHandler(error.message, error);
  76924. });
  76925. }
  76926. else {
  76927. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  76928. }
  76929. if (SceneLoader.ShowLoadingScreen) {
  76930. scene.executeWhenReady(function () {
  76931. scene.getEngine().hideLoadingUI();
  76932. });
  76933. }
  76934. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  76935. };
  76936. /**
  76937. * Load a scene into an asset container
  76938. * @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)
  76939. * @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)
  76940. * @param scene is the instance of BABYLON.Scene to append to
  76941. * @param onProgress a callback with a progress event for each file being loaded
  76942. * @param pluginExtension the extension used to determine the plugin
  76943. * @returns The loaded asset container
  76944. */
  76945. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  76946. if (sceneFilename === void 0) { sceneFilename = ""; }
  76947. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76948. if (onProgress === void 0) { onProgress = null; }
  76949. if (pluginExtension === void 0) { pluginExtension = null; }
  76950. return new Promise(function (resolve, reject) {
  76951. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  76952. resolve(assetContainer);
  76953. }, onProgress, function (scene, message, exception) {
  76954. reject(exception || new Error(message));
  76955. }, pluginExtension);
  76956. });
  76957. };
  76958. // Flags
  76959. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  76960. SceneLoader._ShowLoadingScreen = true;
  76961. SceneLoader._CleanBoneMatrixWeights = false;
  76962. /**
  76963. * No logging while loading
  76964. */
  76965. SceneLoader.NO_LOGGING = 0;
  76966. /**
  76967. * Minimal logging while loading
  76968. */
  76969. SceneLoader.MINIMAL_LOGGING = 1;
  76970. /**
  76971. * Summary logging while loading
  76972. */
  76973. SceneLoader.SUMMARY_LOGGING = 2;
  76974. /**
  76975. * Detailled logging while loading
  76976. */
  76977. SceneLoader.DETAILED_LOGGING = 3;
  76978. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  76979. // Members
  76980. /**
  76981. * Event raised when a plugin is used to load a scene
  76982. */
  76983. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  76984. SceneLoader._registeredPlugins = {};
  76985. return SceneLoader;
  76986. }());
  76987. BABYLON.SceneLoader = SceneLoader;
  76988. })(BABYLON || (BABYLON = {}));
  76989. //# sourceMappingURL=babylon.sceneLoader.js.map
  76990. var BABYLON;
  76991. (function (BABYLON) {
  76992. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  76993. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  76994. var parsedMaterial = parsedData.materials[index];
  76995. if (parsedMaterial.id === id) {
  76996. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  76997. }
  76998. }
  76999. return null;
  77000. };
  77001. var isDescendantOf = function (mesh, names, hierarchyIds) {
  77002. for (var i in names) {
  77003. if (mesh.name === names[i]) {
  77004. hierarchyIds.push(mesh.id);
  77005. return true;
  77006. }
  77007. }
  77008. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  77009. hierarchyIds.push(mesh.id);
  77010. return true;
  77011. }
  77012. return false;
  77013. };
  77014. var logOperation = function (operation, producer) {
  77015. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  77016. };
  77017. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  77018. if (addToScene === void 0) { addToScene = false; }
  77019. var container = new BABYLON.AssetContainer(scene);
  77020. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  77021. // when SceneLoader.debugLogging = true (default), or exception encountered.
  77022. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  77023. // and avoid problems with multiple concurrent .babylon loads.
  77024. var log = "importScene has failed JSON parse";
  77025. try {
  77026. var parsedData = JSON.parse(data);
  77027. log = "";
  77028. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  77029. var index;
  77030. var cache;
  77031. // Lights
  77032. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  77033. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  77034. var parsedLight = parsedData.lights[index];
  77035. var light = BABYLON.Light.Parse(parsedLight, scene);
  77036. if (light) {
  77037. container.lights.push(light);
  77038. log += (index === 0 ? "\n\tLights:" : "");
  77039. log += "\n\t\t" + light.toString(fullDetails);
  77040. }
  77041. }
  77042. }
  77043. // Animations
  77044. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  77045. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  77046. var parsedAnimation = parsedData.animations[index];
  77047. var animation = BABYLON.Animation.Parse(parsedAnimation);
  77048. scene.animations.push(animation);
  77049. container.animations.push(animation);
  77050. log += (index === 0 ? "\n\tAnimations:" : "");
  77051. log += "\n\t\t" + animation.toString(fullDetails);
  77052. }
  77053. }
  77054. // Materials
  77055. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  77056. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  77057. var parsedMaterial = parsedData.materials[index];
  77058. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  77059. container.materials.push(mat);
  77060. log += (index === 0 ? "\n\tMaterials:" : "");
  77061. log += "\n\t\t" + mat.toString(fullDetails);
  77062. }
  77063. }
  77064. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  77065. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  77066. var parsedMultiMaterial = parsedData.multiMaterials[index];
  77067. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  77068. container.multiMaterials.push(mmat);
  77069. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  77070. log += "\n\t\t" + mmat.toString(fullDetails);
  77071. }
  77072. }
  77073. // Morph targets
  77074. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  77075. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  77076. var managerData = _a[_i];
  77077. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  77078. }
  77079. }
  77080. // Skeletons
  77081. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  77082. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  77083. var parsedSkeleton = parsedData.skeletons[index];
  77084. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  77085. container.skeletons.push(skeleton);
  77086. log += (index === 0 ? "\n\tSkeletons:" : "");
  77087. log += "\n\t\t" + skeleton.toString(fullDetails);
  77088. }
  77089. }
  77090. // Geometries
  77091. var geometries = parsedData.geometries;
  77092. if (geometries !== undefined && geometries !== null) {
  77093. var addedGeometry = new Array();
  77094. // Boxes
  77095. var boxes = geometries.boxes;
  77096. if (boxes !== undefined && boxes !== null) {
  77097. for (index = 0, cache = boxes.length; index < cache; index++) {
  77098. var parsedBox = boxes[index];
  77099. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  77100. }
  77101. }
  77102. // Spheres
  77103. var spheres = geometries.spheres;
  77104. if (spheres !== undefined && spheres !== null) {
  77105. for (index = 0, cache = spheres.length; index < cache; index++) {
  77106. var parsedSphere = spheres[index];
  77107. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  77108. }
  77109. }
  77110. // Cylinders
  77111. var cylinders = geometries.cylinders;
  77112. if (cylinders !== undefined && cylinders !== null) {
  77113. for (index = 0, cache = cylinders.length; index < cache; index++) {
  77114. var parsedCylinder = cylinders[index];
  77115. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  77116. }
  77117. }
  77118. // Toruses
  77119. var toruses = geometries.toruses;
  77120. if (toruses !== undefined && toruses !== null) {
  77121. for (index = 0, cache = toruses.length; index < cache; index++) {
  77122. var parsedTorus = toruses[index];
  77123. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  77124. }
  77125. }
  77126. // Grounds
  77127. var grounds = geometries.grounds;
  77128. if (grounds !== undefined && grounds !== null) {
  77129. for (index = 0, cache = grounds.length; index < cache; index++) {
  77130. var parsedGround = grounds[index];
  77131. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  77132. }
  77133. }
  77134. // Planes
  77135. var planes = geometries.planes;
  77136. if (planes !== undefined && planes !== null) {
  77137. for (index = 0, cache = planes.length; index < cache; index++) {
  77138. var parsedPlane = planes[index];
  77139. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  77140. }
  77141. }
  77142. // TorusKnots
  77143. var torusKnots = geometries.torusKnots;
  77144. if (torusKnots !== undefined && torusKnots !== null) {
  77145. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  77146. var parsedTorusKnot = torusKnots[index];
  77147. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  77148. }
  77149. }
  77150. // VertexData
  77151. var vertexData = geometries.vertexData;
  77152. if (vertexData !== undefined && vertexData !== null) {
  77153. for (index = 0, cache = vertexData.length; index < cache; index++) {
  77154. var parsedVertexData = vertexData[index];
  77155. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  77156. }
  77157. }
  77158. addedGeometry.forEach(function (g) {
  77159. if (g) {
  77160. container.geometries.push(g);
  77161. }
  77162. });
  77163. }
  77164. // Transform nodes
  77165. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  77166. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  77167. var parsedTransformNode = parsedData.transformNodes[index];
  77168. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  77169. container.transformNodes.push(node);
  77170. }
  77171. }
  77172. // Meshes
  77173. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  77174. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  77175. var parsedMesh = parsedData.meshes[index];
  77176. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  77177. container.meshes.push(mesh);
  77178. log += (index === 0 ? "\n\tMeshes:" : "");
  77179. log += "\n\t\t" + mesh.toString(fullDetails);
  77180. }
  77181. }
  77182. // Cameras
  77183. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  77184. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  77185. var parsedCamera = parsedData.cameras[index];
  77186. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  77187. container.cameras.push(camera);
  77188. log += (index === 0 ? "\n\tCameras:" : "");
  77189. log += "\n\t\t" + camera.toString(fullDetails);
  77190. }
  77191. }
  77192. // Animation Groups
  77193. if (parsedData.animationGroups !== undefined && parsedData.animationGroups !== null) {
  77194. for (index = 0, cache = parsedData.animationGroups.length; index < cache; index++) {
  77195. var parsedAnimationGroup = parsedData.animationGroups[index];
  77196. var animationGroup = BABYLON.AnimationGroup.Parse(parsedAnimationGroup, scene);
  77197. container.animationGroups.push(animationGroup);
  77198. log += (index === 0 ? "\n\tAnimationGroups:" : "");
  77199. log += "\n\t\t" + animationGroup.toString(fullDetails);
  77200. }
  77201. }
  77202. // Browsing all the graph to connect the dots
  77203. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  77204. var camera = scene.cameras[index];
  77205. if (camera._waitingParentId) {
  77206. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  77207. camera._waitingParentId = null;
  77208. }
  77209. }
  77210. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  77211. var light_1 = scene.lights[index];
  77212. if (light_1 && light_1._waitingParentId) {
  77213. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  77214. light_1._waitingParentId = null;
  77215. }
  77216. }
  77217. // Connect parents & children and parse actions
  77218. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  77219. var transformNode = scene.transformNodes[index];
  77220. if (transformNode._waitingParentId) {
  77221. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  77222. transformNode._waitingParentId = null;
  77223. }
  77224. }
  77225. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  77226. var mesh = scene.meshes[index];
  77227. if (mesh._waitingParentId) {
  77228. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  77229. mesh._waitingParentId = null;
  77230. }
  77231. }
  77232. // freeze world matrix application
  77233. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  77234. var currentMesh = scene.meshes[index];
  77235. if (currentMesh._waitingFreezeWorldMatrix) {
  77236. currentMesh.freezeWorldMatrix();
  77237. currentMesh._waitingFreezeWorldMatrix = null;
  77238. }
  77239. else {
  77240. currentMesh.computeWorldMatrix(true);
  77241. }
  77242. }
  77243. // Lights exclusions / inclusions
  77244. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  77245. var light_2 = scene.lights[index];
  77246. // Excluded check
  77247. if (light_2._excludedMeshesIds.length > 0) {
  77248. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  77249. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  77250. if (excludedMesh) {
  77251. light_2.excludedMeshes.push(excludedMesh);
  77252. }
  77253. }
  77254. light_2._excludedMeshesIds = [];
  77255. }
  77256. // Included check
  77257. if (light_2._includedOnlyMeshesIds.length > 0) {
  77258. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  77259. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  77260. if (includedOnlyMesh) {
  77261. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  77262. }
  77263. }
  77264. light_2._includedOnlyMeshesIds = [];
  77265. }
  77266. }
  77267. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  77268. // Actions (scene) Done last as it can access other objects.
  77269. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  77270. var mesh = scene.meshes[index];
  77271. if (mesh._waitingActions) {
  77272. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  77273. mesh._waitingActions = null;
  77274. }
  77275. }
  77276. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  77277. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  77278. }
  77279. if (!addToScene) {
  77280. container.removeAllFromScene();
  77281. }
  77282. }
  77283. catch (err) {
  77284. var msg = logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + log;
  77285. if (onError) {
  77286. onError(msg, err);
  77287. }
  77288. else {
  77289. BABYLON.Tools.Log(msg);
  77290. throw err;
  77291. }
  77292. }
  77293. finally {
  77294. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  77295. BABYLON.Tools.Log(logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  77296. }
  77297. }
  77298. return container;
  77299. };
  77300. BABYLON.SceneLoader.RegisterPlugin({
  77301. name: "babylon.js",
  77302. extensions: ".babylon",
  77303. canDirectLoad: function (data) {
  77304. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  77305. return true;
  77306. }
  77307. return false;
  77308. },
  77309. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  77310. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  77311. // when SceneLoader.debugLogging = true (default), or exception encountered.
  77312. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  77313. // and avoid problems with multiple concurrent .babylon loads.
  77314. var log = "importMesh has failed JSON parse";
  77315. try {
  77316. var parsedData = JSON.parse(data);
  77317. log = "";
  77318. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  77319. if (!meshesNames) {
  77320. meshesNames = null;
  77321. }
  77322. else if (!Array.isArray(meshesNames)) {
  77323. meshesNames = [meshesNames];
  77324. }
  77325. var hierarchyIds = new Array();
  77326. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  77327. var loadedSkeletonsIds = [];
  77328. var loadedMaterialsIds = [];
  77329. var index;
  77330. var cache;
  77331. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  77332. var parsedMesh = parsedData.meshes[index];
  77333. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  77334. if (meshesNames !== null) {
  77335. // Remove found mesh name from list.
  77336. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  77337. }
  77338. //Geometry?
  77339. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  77340. //does the file contain geometries?
  77341. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  77342. //find the correct geometry and add it to the scene
  77343. var found = false;
  77344. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  77345. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  77346. return;
  77347. }
  77348. else {
  77349. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  77350. if (parsedGeometryData.id === parsedMesh.geometryId) {
  77351. switch (geometryType) {
  77352. case "boxes":
  77353. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  77354. break;
  77355. case "spheres":
  77356. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  77357. break;
  77358. case "cylinders":
  77359. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  77360. break;
  77361. case "toruses":
  77362. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  77363. break;
  77364. case "grounds":
  77365. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  77366. break;
  77367. case "planes":
  77368. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  77369. break;
  77370. case "torusKnots":
  77371. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  77372. break;
  77373. case "vertexData":
  77374. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  77375. break;
  77376. }
  77377. found = true;
  77378. }
  77379. });
  77380. }
  77381. });
  77382. if (found === false) {
  77383. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  77384. }
  77385. }
  77386. }
  77387. // Material ?
  77388. if (parsedMesh.materialId) {
  77389. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  77390. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  77391. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  77392. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  77393. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  77394. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  77395. var subMatId = parsedMultiMaterial.materials[matIndex];
  77396. loadedMaterialsIds.push(subMatId);
  77397. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  77398. if (mat) {
  77399. log += "\n\tMaterial " + mat.toString(fullDetails);
  77400. }
  77401. }
  77402. loadedMaterialsIds.push(parsedMultiMaterial.id);
  77403. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  77404. if (mmat) {
  77405. materialFound = true;
  77406. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  77407. }
  77408. break;
  77409. }
  77410. }
  77411. }
  77412. if (materialFound === false) {
  77413. loadedMaterialsIds.push(parsedMesh.materialId);
  77414. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  77415. if (!mat) {
  77416. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  77417. }
  77418. else {
  77419. log += "\n\tMaterial " + mat.toString(fullDetails);
  77420. }
  77421. }
  77422. }
  77423. // Skeleton ?
  77424. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  77425. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  77426. if (skeletonAlreadyLoaded === false) {
  77427. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  77428. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  77429. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  77430. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  77431. skeletons.push(skeleton);
  77432. loadedSkeletonsIds.push(parsedSkeleton.id);
  77433. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  77434. }
  77435. }
  77436. }
  77437. }
  77438. // Morph targets ?
  77439. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  77440. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  77441. var managerData = _a[_i];
  77442. BABYLON.MorphTargetManager.Parse(managerData, scene);
  77443. }
  77444. }
  77445. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  77446. meshes.push(mesh);
  77447. log += "\n\tMesh " + mesh.toString(fullDetails);
  77448. }
  77449. }
  77450. // Connecting parents
  77451. var currentMesh;
  77452. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  77453. currentMesh = scene.meshes[index];
  77454. if (currentMesh._waitingParentId) {
  77455. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  77456. currentMesh._waitingParentId = null;
  77457. }
  77458. }
  77459. // freeze and compute world matrix application
  77460. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  77461. currentMesh = scene.meshes[index];
  77462. if (currentMesh._waitingFreezeWorldMatrix) {
  77463. currentMesh.freezeWorldMatrix();
  77464. currentMesh._waitingFreezeWorldMatrix = null;
  77465. }
  77466. else {
  77467. currentMesh.computeWorldMatrix(true);
  77468. }
  77469. }
  77470. }
  77471. // Particles
  77472. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  77473. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  77474. if (parser) {
  77475. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  77476. var parsedParticleSystem = parsedData.particleSystems[index];
  77477. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  77478. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  77479. }
  77480. }
  77481. }
  77482. }
  77483. return true;
  77484. }
  77485. catch (err) {
  77486. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  77487. if (onError) {
  77488. onError(msg, err);
  77489. }
  77490. else {
  77491. BABYLON.Tools.Log(msg);
  77492. throw err;
  77493. }
  77494. }
  77495. finally {
  77496. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  77497. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  77498. }
  77499. }
  77500. return false;
  77501. },
  77502. load: function (scene, data, rootUrl, onError) {
  77503. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  77504. // when SceneLoader.debugLogging = true (default), or exception encountered.
  77505. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  77506. // and avoid problems with multiple concurrent .babylon loads.
  77507. var log = "importScene has failed JSON parse";
  77508. try {
  77509. var parsedData = JSON.parse(data);
  77510. log = "";
  77511. // Scene
  77512. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  77513. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  77514. }
  77515. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  77516. scene.autoClear = parsedData.autoClear;
  77517. }
  77518. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  77519. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  77520. }
  77521. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  77522. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  77523. }
  77524. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  77525. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  77526. }
  77527. // Fog
  77528. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  77529. scene.fogMode = parsedData.fogMode;
  77530. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  77531. scene.fogStart = parsedData.fogStart;
  77532. scene.fogEnd = parsedData.fogEnd;
  77533. scene.fogDensity = parsedData.fogDensity;
  77534. log += "\tFog mode for scene: ";
  77535. switch (scene.fogMode) {
  77536. // getters not compiling, so using hardcoded
  77537. case 1:
  77538. log += "exp\n";
  77539. break;
  77540. case 2:
  77541. log += "exp2\n";
  77542. break;
  77543. case 3:
  77544. log += "linear\n";
  77545. break;
  77546. }
  77547. }
  77548. //Physics
  77549. if (parsedData.physicsEnabled) {
  77550. var physicsPlugin;
  77551. if (parsedData.physicsEngine === "cannon") {
  77552. physicsPlugin = new BABYLON.CannonJSPlugin();
  77553. }
  77554. else if (parsedData.physicsEngine === "oimo") {
  77555. physicsPlugin = new BABYLON.OimoJSPlugin();
  77556. }
  77557. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  77558. //else - default engine, which is currently oimo
  77559. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  77560. scene.enablePhysics(physicsGravity, physicsPlugin);
  77561. }
  77562. // Metadata
  77563. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  77564. scene.metadata = parsedData.metadata;
  77565. }
  77566. //collisions, if defined. otherwise, default is true
  77567. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  77568. scene.collisionsEnabled = parsedData.collisionsEnabled;
  77569. }
  77570. scene.workerCollisions = !!parsedData.workerCollisions;
  77571. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  77572. if (!container) {
  77573. return false;
  77574. }
  77575. if (parsedData.autoAnimate) {
  77576. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  77577. }
  77578. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  77579. scene.setActiveCameraByID(parsedData.activeCameraID);
  77580. }
  77581. // Environment texture
  77582. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  77583. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  77584. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  77585. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  77586. if (parsedData.environmentTextureRotationY) {
  77587. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  77588. }
  77589. scene.environmentTexture = hdrTexture;
  77590. }
  77591. else {
  77592. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  77593. if (parsedData.environmentTextureRotationY) {
  77594. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  77595. }
  77596. scene.environmentTexture = cubeTexture;
  77597. }
  77598. if (parsedData.createDefaultSkybox === true) {
  77599. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  77600. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  77601. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  77602. }
  77603. }
  77604. // Finish
  77605. return true;
  77606. }
  77607. catch (err) {
  77608. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  77609. if (onError) {
  77610. onError(msg, err);
  77611. }
  77612. else {
  77613. BABYLON.Tools.Log(msg);
  77614. throw err;
  77615. }
  77616. }
  77617. finally {
  77618. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  77619. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  77620. }
  77621. }
  77622. return false;
  77623. },
  77624. loadAssetContainer: function (scene, data, rootUrl, onError) {
  77625. var container = loadAssetContainer(scene, data, rootUrl, onError);
  77626. return container;
  77627. }
  77628. });
  77629. })(BABYLON || (BABYLON = {}));
  77630. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  77631. var BABYLON;
  77632. (function (BABYLON) {
  77633. /**
  77634. * Class used to help managing file picking and drag'n'drop
  77635. */
  77636. var FilesInput = /** @class */ (function () {
  77637. /**
  77638. * Creates a new FilesInput
  77639. * @param engine defines the rendering engine
  77640. * @param scene defines the hosting scene
  77641. * @param sceneLoadedCallback callback called when scene is loaded
  77642. * @param progressCallback callback called to track progress
  77643. * @param additionalRenderLoopLogicCallback callback called to add user logic to the rendering loop
  77644. * @param textureLoadingCallback callback called when a texture is loading
  77645. * @param startingProcessingFilesCallback callback called when the system is about to process all files
  77646. * @param onReloadCallback callback called when a reload is requested
  77647. * @param errorCallback callback call if an error occurs
  77648. */
  77649. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  77650. /**
  77651. * Callback called when a file is processed
  77652. */
  77653. this.onProcessFileCallback = function () { return true; };
  77654. this._engine = engine;
  77655. this._currentScene = scene;
  77656. this._sceneLoadedCallback = sceneLoadedCallback;
  77657. this._progressCallback = progressCallback;
  77658. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  77659. this._textureLoadingCallback = textureLoadingCallback;
  77660. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  77661. this._onReloadCallback = onReloadCallback;
  77662. this._errorCallback = errorCallback;
  77663. }
  77664. /**
  77665. * Calls this function to listen to drag'n'drop events on a specific DOM element
  77666. * @param elementToMonitor defines the DOM element to track
  77667. */
  77668. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  77669. var _this = this;
  77670. if (elementToMonitor) {
  77671. this._elementToMonitor = elementToMonitor;
  77672. this._dragEnterHandler = function (e) { _this.drag(e); };
  77673. this._dragOverHandler = function (e) { _this.drag(e); };
  77674. this._dropHandler = function (e) { _this.drop(e); };
  77675. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  77676. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  77677. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  77678. }
  77679. };
  77680. /**
  77681. * Release all associated resources
  77682. */
  77683. FilesInput.prototype.dispose = function () {
  77684. if (!this._elementToMonitor) {
  77685. return;
  77686. }
  77687. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  77688. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  77689. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  77690. };
  77691. FilesInput.prototype.renderFunction = function () {
  77692. if (this._additionalRenderLoopLogicCallback) {
  77693. this._additionalRenderLoopLogicCallback();
  77694. }
  77695. if (this._currentScene) {
  77696. if (this._textureLoadingCallback) {
  77697. var remaining = this._currentScene.getWaitingItemsCount();
  77698. if (remaining > 0) {
  77699. this._textureLoadingCallback(remaining);
  77700. }
  77701. }
  77702. this._currentScene.render();
  77703. }
  77704. };
  77705. FilesInput.prototype.drag = function (e) {
  77706. e.stopPropagation();
  77707. e.preventDefault();
  77708. };
  77709. FilesInput.prototype.drop = function (eventDrop) {
  77710. eventDrop.stopPropagation();
  77711. eventDrop.preventDefault();
  77712. this.loadFiles(eventDrop);
  77713. };
  77714. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  77715. var _this = this;
  77716. var reader = folder.createReader();
  77717. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  77718. reader.readEntries(function (entries) {
  77719. remaining.count += entries.length;
  77720. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  77721. var entry = entries_1[_i];
  77722. if (entry.isFile) {
  77723. entry.file(function (file) {
  77724. file.correctName = relativePath + file.name;
  77725. files.push(file);
  77726. if (--remaining.count === 0) {
  77727. callback();
  77728. }
  77729. });
  77730. }
  77731. else if (entry.isDirectory) {
  77732. _this._traverseFolder(entry, files, remaining, callback);
  77733. }
  77734. }
  77735. if (--remaining.count) {
  77736. callback();
  77737. }
  77738. });
  77739. };
  77740. FilesInput.prototype._processFiles = function (files) {
  77741. for (var i = 0; i < files.length; i++) {
  77742. var name = files[i].correctName.toLowerCase();
  77743. var extension = name.split('.').pop();
  77744. if (!this.onProcessFileCallback(files[i], name, extension)) {
  77745. continue;
  77746. }
  77747. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  77748. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  77749. this._sceneFileToLoad = files[i];
  77750. }
  77751. FilesInput.FilesToLoad[name] = files[i];
  77752. }
  77753. };
  77754. /**
  77755. * Load files from a drop event
  77756. * @param event defines the drop event to use as source
  77757. */
  77758. FilesInput.prototype.loadFiles = function (event) {
  77759. var _this = this;
  77760. // Handling data transfer via drag'n'drop
  77761. if (event && event.dataTransfer && event.dataTransfer.files) {
  77762. this._filesToLoad = event.dataTransfer.files;
  77763. }
  77764. // Handling files from input files
  77765. if (event && event.target && event.target.files) {
  77766. this._filesToLoad = event.target.files;
  77767. }
  77768. if (!this._filesToLoad || this._filesToLoad.length === 0) {
  77769. return;
  77770. }
  77771. if (this._startingProcessingFilesCallback) {
  77772. this._startingProcessingFilesCallback(this._filesToLoad);
  77773. }
  77774. if (this._filesToLoad && this._filesToLoad.length > 0) {
  77775. var files_1 = new Array();
  77776. var folders = [];
  77777. var items = event.dataTransfer ? event.dataTransfer.items : null;
  77778. for (var i = 0; i < this._filesToLoad.length; i++) {
  77779. var fileToLoad = this._filesToLoad[i];
  77780. var name_1 = fileToLoad.name.toLowerCase();
  77781. var entry = void 0;
  77782. fileToLoad.correctName = name_1;
  77783. if (items) {
  77784. var item = items[i];
  77785. if (item.getAsEntry) {
  77786. entry = item.getAsEntry();
  77787. }
  77788. else if (item.webkitGetAsEntry) {
  77789. entry = item.webkitGetAsEntry();
  77790. }
  77791. }
  77792. if (!entry) {
  77793. files_1.push(fileToLoad);
  77794. }
  77795. else {
  77796. if (entry.isDirectory) {
  77797. folders.push(entry);
  77798. }
  77799. else {
  77800. files_1.push(fileToLoad);
  77801. }
  77802. }
  77803. }
  77804. if (folders.length === 0) {
  77805. this._processFiles(files_1);
  77806. this._processReload();
  77807. }
  77808. else {
  77809. var remaining = { count: folders.length };
  77810. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  77811. var folder = folders_1[_i];
  77812. this._traverseFolder(folder, files_1, remaining, function () {
  77813. _this._processFiles(files_1);
  77814. if (remaining.count === 0) {
  77815. _this._processReload();
  77816. }
  77817. });
  77818. }
  77819. }
  77820. }
  77821. };
  77822. FilesInput.prototype._processReload = function () {
  77823. if (this._onReloadCallback) {
  77824. this._onReloadCallback(this._sceneFileToLoad);
  77825. }
  77826. else {
  77827. this.reload();
  77828. }
  77829. };
  77830. /**
  77831. * Reload the current scene from the loaded files
  77832. */
  77833. FilesInput.prototype.reload = function () {
  77834. var _this = this;
  77835. // If a scene file has been provided
  77836. if (this._sceneFileToLoad) {
  77837. if (this._currentScene) {
  77838. if (BABYLON.Tools.errorsCount > 0) {
  77839. BABYLON.Tools.ClearLogCache();
  77840. }
  77841. this._engine.stopRenderLoop();
  77842. }
  77843. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad.name, this._engine, function (progress) {
  77844. if (_this._progressCallback) {
  77845. _this._progressCallback(progress);
  77846. }
  77847. }).then(function (scene) {
  77848. if (_this._currentScene) {
  77849. _this._currentScene.dispose();
  77850. }
  77851. _this._currentScene = scene;
  77852. if (_this._sceneLoadedCallback) {
  77853. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  77854. }
  77855. // Wait for textures and shaders to be ready
  77856. _this._currentScene.executeWhenReady(function () {
  77857. _this._engine.runRenderLoop(function () {
  77858. _this.renderFunction();
  77859. });
  77860. });
  77861. }).catch(function (error) {
  77862. if (_this._errorCallback) {
  77863. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  77864. }
  77865. });
  77866. }
  77867. else {
  77868. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  77869. }
  77870. };
  77871. /**
  77872. * List of files ready to be loaded
  77873. */
  77874. FilesInput.FilesToLoad = {};
  77875. return FilesInput;
  77876. }());
  77877. BABYLON.FilesInput = FilesInput;
  77878. })(BABYLON || (BABYLON = {}));
  77879. //# sourceMappingURL=babylon.filesInput.js.map
  77880. var BABYLON;
  77881. (function (BABYLON) {
  77882. /**
  77883. * Class used to store custom tags
  77884. */
  77885. var Tags = /** @class */ (function () {
  77886. function Tags() {
  77887. }
  77888. /**
  77889. * Adds support for tags on the given object
  77890. * @param obj defines the object to use
  77891. */
  77892. Tags.EnableFor = function (obj) {
  77893. obj._tags = obj._tags || {};
  77894. obj.hasTags = function () {
  77895. return Tags.HasTags(obj);
  77896. };
  77897. obj.addTags = function (tagsString) {
  77898. return Tags.AddTagsTo(obj, tagsString);
  77899. };
  77900. obj.removeTags = function (tagsString) {
  77901. return Tags.RemoveTagsFrom(obj, tagsString);
  77902. };
  77903. obj.matchesTagsQuery = function (tagsQuery) {
  77904. return Tags.MatchesQuery(obj, tagsQuery);
  77905. };
  77906. };
  77907. /**
  77908. * Removes tags support
  77909. * @param obj defines the object to use
  77910. */
  77911. Tags.DisableFor = function (obj) {
  77912. delete obj._tags;
  77913. delete obj.hasTags;
  77914. delete obj.addTags;
  77915. delete obj.removeTags;
  77916. delete obj.matchesTagsQuery;
  77917. };
  77918. /**
  77919. * Gets a boolean indicating if the given object has tags
  77920. * @param obj defines the object to use
  77921. * @returns a boolean
  77922. */
  77923. Tags.HasTags = function (obj) {
  77924. if (!obj._tags) {
  77925. return false;
  77926. }
  77927. return !BABYLON.Tools.IsEmpty(obj._tags);
  77928. };
  77929. /**
  77930. * Gets the tags available on a given object
  77931. * @param obj defines the object to use
  77932. * @param asString defines if the tags must be returned as a string instead of an array of strings
  77933. * @returns the tags
  77934. */
  77935. Tags.GetTags = function (obj, asString) {
  77936. if (asString === void 0) { asString = true; }
  77937. if (!obj._tags) {
  77938. return null;
  77939. }
  77940. if (asString) {
  77941. var tagsArray = [];
  77942. for (var tag in obj._tags) {
  77943. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  77944. tagsArray.push(tag);
  77945. }
  77946. }
  77947. return tagsArray.join(" ");
  77948. }
  77949. else {
  77950. return obj._tags;
  77951. }
  77952. };
  77953. /**
  77954. * Adds tags to an object
  77955. * @param obj defines the object to use
  77956. * @param tagsString defines the tag string. The tags 'true' and 'false' are reserved and cannot be used as tags.
  77957. * A tag cannot start with '||', '&&', and '!'. It cannot contain whitespaces
  77958. */
  77959. Tags.AddTagsTo = function (obj, tagsString) {
  77960. if (!tagsString) {
  77961. return;
  77962. }
  77963. if (typeof tagsString !== "string") {
  77964. return;
  77965. }
  77966. var tags = tagsString.split(" ");
  77967. tags.forEach(function (tag, index, array) {
  77968. Tags._AddTagTo(obj, tag);
  77969. });
  77970. };
  77971. /**
  77972. * @hidden
  77973. */
  77974. Tags._AddTagTo = function (obj, tag) {
  77975. tag = tag.trim();
  77976. if (tag === "" || tag === "true" || tag === "false") {
  77977. return;
  77978. }
  77979. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  77980. return;
  77981. }
  77982. Tags.EnableFor(obj);
  77983. obj._tags[tag] = true;
  77984. };
  77985. /**
  77986. * Removes specific tags from a specific object
  77987. * @param obj defines the object to use
  77988. * @param tagsString defines the tags to remove
  77989. */
  77990. Tags.RemoveTagsFrom = function (obj, tagsString) {
  77991. if (!Tags.HasTags(obj)) {
  77992. return;
  77993. }
  77994. var tags = tagsString.split(" ");
  77995. for (var t in tags) {
  77996. Tags._RemoveTagFrom(obj, tags[t]);
  77997. }
  77998. };
  77999. /**
  78000. * @hidden
  78001. */
  78002. Tags._RemoveTagFrom = function (obj, tag) {
  78003. delete obj._tags[tag];
  78004. };
  78005. /**
  78006. * Defines if tags hosted on an object match a given query
  78007. * @param obj defines the object to use
  78008. * @param tagsQuery defines the tag query
  78009. * @returns a boolean
  78010. */
  78011. Tags.MatchesQuery = function (obj, tagsQuery) {
  78012. if (tagsQuery === undefined) {
  78013. return true;
  78014. }
  78015. if (tagsQuery === "") {
  78016. return Tags.HasTags(obj);
  78017. }
  78018. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  78019. };
  78020. return Tags;
  78021. }());
  78022. BABYLON.Tags = Tags;
  78023. })(BABYLON || (BABYLON = {}));
  78024. //# sourceMappingURL=babylon.tags.js.map
  78025. var BABYLON;
  78026. (function (BABYLON) {
  78027. /**
  78028. * Class used to evalaute queries containing `and` and `or` operators
  78029. */
  78030. var AndOrNotEvaluator = /** @class */ (function () {
  78031. function AndOrNotEvaluator() {
  78032. }
  78033. /**
  78034. * Evaluate a query
  78035. * @param query defines the query to evaluate
  78036. * @param evaluateCallback defines the callback used to filter result
  78037. * @returns true if the query matches
  78038. */
  78039. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  78040. if (!query.match(/\([^\(\)]*\)/g)) {
  78041. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  78042. }
  78043. else {
  78044. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  78045. // remove parenthesis
  78046. r = r.slice(1, r.length - 1);
  78047. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  78048. });
  78049. }
  78050. if (query === "true") {
  78051. return true;
  78052. }
  78053. if (query === "false") {
  78054. return false;
  78055. }
  78056. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  78057. };
  78058. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  78059. evaluateCallback = evaluateCallback || (function (r) {
  78060. return r === "true" ? true : false;
  78061. });
  78062. var result;
  78063. var or = parenthesisContent.split("||");
  78064. for (var i in or) {
  78065. if (or.hasOwnProperty(i)) {
  78066. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  78067. var and = ori.split("&&");
  78068. if (and.length > 1) {
  78069. for (var j = 0; j < and.length; ++j) {
  78070. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  78071. if (andj !== "true" && andj !== "false") {
  78072. if (andj[0] === "!") {
  78073. result = !evaluateCallback(andj.substring(1));
  78074. }
  78075. else {
  78076. result = evaluateCallback(andj);
  78077. }
  78078. }
  78079. else {
  78080. result = andj === "true" ? true : false;
  78081. }
  78082. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  78083. ori = "false";
  78084. break;
  78085. }
  78086. }
  78087. }
  78088. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  78089. result = true;
  78090. break;
  78091. }
  78092. // result equals false (or undefined)
  78093. if (ori !== "true" && ori !== "false") {
  78094. if (ori[0] === "!") {
  78095. result = !evaluateCallback(ori.substring(1));
  78096. }
  78097. else {
  78098. result = evaluateCallback(ori);
  78099. }
  78100. }
  78101. else {
  78102. result = ori === "true" ? true : false;
  78103. }
  78104. }
  78105. }
  78106. // the whole parenthesis scope is replaced by 'true' or 'false'
  78107. return result ? "true" : "false";
  78108. };
  78109. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  78110. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  78111. // remove whitespaces
  78112. r = r.replace(/[\s]/g, function () { return ""; });
  78113. return r.length % 2 ? "!" : "";
  78114. });
  78115. booleanString = booleanString.trim();
  78116. if (booleanString === "!true") {
  78117. booleanString = "false";
  78118. }
  78119. else if (booleanString === "!false") {
  78120. booleanString = "true";
  78121. }
  78122. return booleanString;
  78123. };
  78124. return AndOrNotEvaluator;
  78125. }());
  78126. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  78127. })(BABYLON || (BABYLON = {}));
  78128. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  78129. var BABYLON;
  78130. (function (BABYLON) {
  78131. /**
  78132. * Class used to enable access to IndexedDB
  78133. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  78134. */
  78135. var Database = /** @class */ (function () {
  78136. /**
  78137. * Creates a new Database
  78138. * @param urlToScene defines the url to load the scene
  78139. * @param callbackManifestChecked defines the callback to use when manifest is checked
  78140. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  78141. */
  78142. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  78143. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  78144. var _this = this;
  78145. // Handling various flavors of prefixed version of IndexedDB
  78146. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  78147. this.callbackManifestChecked = callbackManifestChecked;
  78148. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  78149. this.db = null;
  78150. this._enableSceneOffline = false;
  78151. this._enableTexturesOffline = false;
  78152. this.manifestVersionFound = 0;
  78153. this.mustUpdateRessources = false;
  78154. this.hasReachedQuota = false;
  78155. if (!Database.IDBStorageEnabled) {
  78156. this.callbackManifestChecked(true);
  78157. }
  78158. else {
  78159. if (disableManifestCheck) {
  78160. this._enableSceneOffline = true;
  78161. this._enableTexturesOffline = true;
  78162. this.manifestVersionFound = 1;
  78163. BABYLON.Tools.SetImmediate(function () {
  78164. _this.callbackManifestChecked(true);
  78165. });
  78166. }
  78167. else {
  78168. this._checkManifestFile();
  78169. }
  78170. }
  78171. }
  78172. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  78173. /**
  78174. * Gets a boolean indicating if scene must be saved in the database
  78175. */
  78176. get: function () {
  78177. return this._enableSceneOffline;
  78178. },
  78179. enumerable: true,
  78180. configurable: true
  78181. });
  78182. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  78183. /**
  78184. * Gets a boolean indicating if textures must be saved in the database
  78185. */
  78186. get: function () {
  78187. return this._enableTexturesOffline;
  78188. },
  78189. enumerable: true,
  78190. configurable: true
  78191. });
  78192. Database.prototype._checkManifestFile = function () {
  78193. var _this = this;
  78194. var noManifestFile = function () {
  78195. _this._enableSceneOffline = false;
  78196. _this._enableTexturesOffline = false;
  78197. _this.callbackManifestChecked(false);
  78198. };
  78199. var timeStampUsed = false;
  78200. var manifestURL = this.currentSceneUrl + ".manifest";
  78201. var xhr = new XMLHttpRequest();
  78202. if (navigator.onLine) {
  78203. // Adding a timestamp to by-pass browsers' cache
  78204. timeStampUsed = true;
  78205. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  78206. }
  78207. xhr.open("GET", manifestURL, true);
  78208. xhr.addEventListener("load", function () {
  78209. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  78210. try {
  78211. var manifestFile = JSON.parse(xhr.response);
  78212. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  78213. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  78214. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  78215. _this.manifestVersionFound = manifestFile.version;
  78216. }
  78217. if (_this.callbackManifestChecked) {
  78218. _this.callbackManifestChecked(true);
  78219. }
  78220. }
  78221. catch (ex) {
  78222. noManifestFile();
  78223. }
  78224. }
  78225. else {
  78226. noManifestFile();
  78227. }
  78228. }, false);
  78229. xhr.addEventListener("error", function (event) {
  78230. if (timeStampUsed) {
  78231. timeStampUsed = false;
  78232. // Let's retry without the timeStamp
  78233. // It could fail when coupled with HTML5 Offline API
  78234. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  78235. xhr.open("GET", retryManifestURL, true);
  78236. xhr.send();
  78237. }
  78238. else {
  78239. noManifestFile();
  78240. }
  78241. }, false);
  78242. try {
  78243. xhr.send();
  78244. }
  78245. catch (ex) {
  78246. BABYLON.Tools.Error("Error on XHR send request.");
  78247. this.callbackManifestChecked(false);
  78248. }
  78249. };
  78250. /**
  78251. * Open the database and make it available
  78252. * @param successCallback defines the callback to call on success
  78253. * @param errorCallback defines the callback to call on error
  78254. */
  78255. Database.prototype.openAsync = function (successCallback, errorCallback) {
  78256. var _this = this;
  78257. var handleError = function () {
  78258. _this.isSupported = false;
  78259. if (errorCallback) {
  78260. errorCallback();
  78261. }
  78262. };
  78263. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  78264. // Your browser doesn't support IndexedDB
  78265. this.isSupported = false;
  78266. if (errorCallback) {
  78267. errorCallback();
  78268. }
  78269. }
  78270. else {
  78271. // If the DB hasn't been opened or created yet
  78272. if (!this.db) {
  78273. this.hasReachedQuota = false;
  78274. this.isSupported = true;
  78275. var request = this.idbFactory.open("babylonjs", 1);
  78276. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  78277. request.onerror = function (event) {
  78278. handleError();
  78279. };
  78280. // executes when a version change transaction cannot complete due to other active transactions
  78281. request.onblocked = function (event) {
  78282. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  78283. handleError();
  78284. };
  78285. // DB has been opened successfully
  78286. request.onsuccess = function (event) {
  78287. _this.db = request.result;
  78288. successCallback();
  78289. };
  78290. // Initialization of the DB. Creating Scenes & Textures stores
  78291. request.onupgradeneeded = function (event) {
  78292. _this.db = (event.target).result;
  78293. if (_this.db) {
  78294. try {
  78295. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  78296. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  78297. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  78298. }
  78299. catch (ex) {
  78300. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  78301. handleError();
  78302. }
  78303. }
  78304. };
  78305. }
  78306. // DB has already been created and opened
  78307. else {
  78308. if (successCallback) {
  78309. successCallback();
  78310. }
  78311. }
  78312. }
  78313. };
  78314. /**
  78315. * Loads an image from the database
  78316. * @param url defines the url to load from
  78317. * @param image defines the target DOM image
  78318. */
  78319. Database.prototype.loadImageFromDB = function (url, image) {
  78320. var _this = this;
  78321. var completeURL = Database._ReturnFullUrlLocation(url);
  78322. var saveAndLoadImage = function () {
  78323. if (!_this.hasReachedQuota && _this.db !== null) {
  78324. // the texture is not yet in the DB, let's try to save it
  78325. _this._saveImageIntoDBAsync(completeURL, image);
  78326. }
  78327. // If the texture is not in the DB and we've reached the DB quota limit
  78328. // let's load it directly from the web
  78329. else {
  78330. image.src = url;
  78331. }
  78332. };
  78333. if (!this.mustUpdateRessources) {
  78334. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  78335. }
  78336. // First time we're download the images or update requested in the manifest file by a version change
  78337. else {
  78338. saveAndLoadImage();
  78339. }
  78340. };
  78341. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  78342. if (this.isSupported && this.db !== null) {
  78343. var texture;
  78344. var transaction = this.db.transaction(["textures"]);
  78345. transaction.onabort = function (event) {
  78346. image.src = url;
  78347. };
  78348. transaction.oncomplete = function (event) {
  78349. var blobTextureURL;
  78350. if (texture) {
  78351. var URL = window.URL || window.webkitURL;
  78352. blobTextureURL = URL.createObjectURL(texture.data);
  78353. image.onerror = function () {
  78354. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  78355. image.src = url;
  78356. };
  78357. image.src = blobTextureURL;
  78358. }
  78359. else {
  78360. notInDBCallback();
  78361. }
  78362. };
  78363. var getRequest = transaction.objectStore("textures").get(url);
  78364. getRequest.onsuccess = function (event) {
  78365. texture = (event.target).result;
  78366. };
  78367. getRequest.onerror = function (event) {
  78368. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  78369. image.src = url;
  78370. };
  78371. }
  78372. else {
  78373. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  78374. image.src = url;
  78375. }
  78376. };
  78377. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  78378. var _this = this;
  78379. if (this.isSupported) {
  78380. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  78381. var generateBlobUrl = function () {
  78382. var blobTextureURL;
  78383. if (blob) {
  78384. var URL = window.URL || window.webkitURL;
  78385. try {
  78386. blobTextureURL = URL.createObjectURL(blob);
  78387. }
  78388. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  78389. catch (ex) {
  78390. blobTextureURL = URL.createObjectURL(blob);
  78391. }
  78392. }
  78393. if (blobTextureURL) {
  78394. image.src = blobTextureURL;
  78395. }
  78396. };
  78397. if (Database.IsUASupportingBlobStorage) { // Create XHR
  78398. var xhr = new XMLHttpRequest(), blob;
  78399. xhr.open("GET", url, true);
  78400. xhr.responseType = "blob";
  78401. xhr.addEventListener("load", function () {
  78402. if (xhr.status === 200 && _this.db) {
  78403. // Blob as response (XHR2)
  78404. blob = xhr.response;
  78405. var transaction = _this.db.transaction(["textures"], "readwrite");
  78406. // the transaction could abort because of a QuotaExceededError error
  78407. transaction.onabort = function (event) {
  78408. try {
  78409. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  78410. var srcElement = (event.srcElement || event.target);
  78411. var error = srcElement.error;
  78412. if (error && error.name === "QuotaExceededError") {
  78413. _this.hasReachedQuota = true;
  78414. }
  78415. }
  78416. catch (ex) { }
  78417. generateBlobUrl();
  78418. };
  78419. transaction.oncomplete = function (event) {
  78420. generateBlobUrl();
  78421. };
  78422. var newTexture = { textureUrl: url, data: blob };
  78423. try {
  78424. // Put the blob into the dabase
  78425. var addRequest = transaction.objectStore("textures").put(newTexture);
  78426. addRequest.onsuccess = function (event) {
  78427. };
  78428. addRequest.onerror = function (event) {
  78429. generateBlobUrl();
  78430. };
  78431. }
  78432. catch (ex) {
  78433. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  78434. if (ex.code === 25) {
  78435. Database.IsUASupportingBlobStorage = false;
  78436. }
  78437. image.src = url;
  78438. }
  78439. }
  78440. else {
  78441. image.src = url;
  78442. }
  78443. }, false);
  78444. xhr.addEventListener("error", function (event) {
  78445. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  78446. image.src = url;
  78447. }, false);
  78448. xhr.send();
  78449. }
  78450. else {
  78451. image.src = url;
  78452. }
  78453. }
  78454. else {
  78455. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  78456. image.src = url;
  78457. }
  78458. };
  78459. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  78460. var _this = this;
  78461. var updateVersion = function () {
  78462. // the version is not yet in the DB or we need to update it
  78463. _this._saveVersionIntoDBAsync(url, versionLoaded);
  78464. };
  78465. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  78466. };
  78467. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  78468. var _this = this;
  78469. if (this.isSupported && this.db) {
  78470. var version;
  78471. try {
  78472. var transaction = this.db.transaction(["versions"]);
  78473. transaction.oncomplete = function (event) {
  78474. if (version) {
  78475. // If the version in the JSON file is different from the version in DB
  78476. if (_this.manifestVersionFound !== version.data) {
  78477. _this.mustUpdateRessources = true;
  78478. updateInDBCallback();
  78479. }
  78480. else {
  78481. callback(version.data);
  78482. }
  78483. }
  78484. // version was not found in DB
  78485. else {
  78486. _this.mustUpdateRessources = true;
  78487. updateInDBCallback();
  78488. }
  78489. };
  78490. transaction.onabort = function (event) {
  78491. callback(-1);
  78492. };
  78493. var getRequest = transaction.objectStore("versions").get(url);
  78494. getRequest.onsuccess = function (event) {
  78495. version = (event.target).result;
  78496. };
  78497. getRequest.onerror = function (event) {
  78498. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  78499. callback(-1);
  78500. };
  78501. }
  78502. catch (ex) {
  78503. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  78504. callback(-1);
  78505. }
  78506. }
  78507. else {
  78508. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  78509. callback(-1);
  78510. }
  78511. };
  78512. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  78513. var _this = this;
  78514. if (this.isSupported && !this.hasReachedQuota && this.db) {
  78515. try {
  78516. // Open a transaction to the database
  78517. var transaction = this.db.transaction(["versions"], "readwrite");
  78518. // the transaction could abort because of a QuotaExceededError error
  78519. transaction.onabort = function (event) {
  78520. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  78521. var error = event.srcElement['error'];
  78522. if (error && error.name === "QuotaExceededError") {
  78523. _this.hasReachedQuota = true;
  78524. }
  78525. }
  78526. catch (ex) { }
  78527. callback(-1);
  78528. };
  78529. transaction.oncomplete = function (event) {
  78530. callback(_this.manifestVersionFound);
  78531. };
  78532. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  78533. // Put the scene into the database
  78534. var addRequest = transaction.objectStore("versions").put(newVersion);
  78535. addRequest.onsuccess = function (event) {
  78536. };
  78537. addRequest.onerror = function (event) {
  78538. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  78539. };
  78540. }
  78541. catch (ex) {
  78542. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  78543. callback(-1);
  78544. }
  78545. }
  78546. else {
  78547. callback(-1);
  78548. }
  78549. };
  78550. /**
  78551. * Loads a file from database
  78552. * @param url defines the URL to load from
  78553. * @param sceneLoaded defines a callback to call on success
  78554. * @param progressCallBack defines a callback to call when progress changed
  78555. * @param errorCallback defines a callback to call on error
  78556. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  78557. */
  78558. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  78559. var _this = this;
  78560. var completeUrl = Database._ReturnFullUrlLocation(url);
  78561. var saveAndLoadFile = function () {
  78562. // the scene is not yet in the DB, let's try to save it
  78563. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  78564. };
  78565. this._checkVersionFromDB(completeUrl, function (version) {
  78566. if (version !== -1) {
  78567. if (!_this.mustUpdateRessources) {
  78568. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  78569. }
  78570. else {
  78571. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  78572. }
  78573. }
  78574. else {
  78575. if (errorCallback) {
  78576. errorCallback();
  78577. }
  78578. }
  78579. });
  78580. };
  78581. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  78582. if (this.isSupported && this.db) {
  78583. var targetStore;
  78584. if (url.indexOf(".babylon") !== -1) {
  78585. targetStore = "scenes";
  78586. }
  78587. else {
  78588. targetStore = "textures";
  78589. }
  78590. var file;
  78591. var transaction = this.db.transaction([targetStore]);
  78592. transaction.oncomplete = function (event) {
  78593. if (file) {
  78594. callback(file.data);
  78595. }
  78596. // file was not found in DB
  78597. else {
  78598. notInDBCallback();
  78599. }
  78600. };
  78601. transaction.onabort = function (event) {
  78602. notInDBCallback();
  78603. };
  78604. var getRequest = transaction.objectStore(targetStore).get(url);
  78605. getRequest.onsuccess = function (event) {
  78606. file = (event.target).result;
  78607. };
  78608. getRequest.onerror = function (event) {
  78609. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  78610. notInDBCallback();
  78611. };
  78612. }
  78613. else {
  78614. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  78615. callback();
  78616. }
  78617. };
  78618. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  78619. var _this = this;
  78620. if (this.isSupported) {
  78621. var targetStore;
  78622. if (url.indexOf(".babylon") !== -1) {
  78623. targetStore = "scenes";
  78624. }
  78625. else {
  78626. targetStore = "textures";
  78627. }
  78628. // Create XHR
  78629. var xhr = new XMLHttpRequest();
  78630. var fileData;
  78631. xhr.open("GET", url + "?" + Date.now(), true);
  78632. if (useArrayBuffer) {
  78633. xhr.responseType = "arraybuffer";
  78634. }
  78635. if (progressCallback) {
  78636. xhr.onprogress = progressCallback;
  78637. }
  78638. xhr.addEventListener("load", function () {
  78639. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  78640. // Blob as response (XHR2)
  78641. //fileData = xhr.responseText;
  78642. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  78643. if (!_this.hasReachedQuota && _this.db) {
  78644. // Open a transaction to the database
  78645. var transaction = _this.db.transaction([targetStore], "readwrite");
  78646. // the transaction could abort because of a QuotaExceededError error
  78647. transaction.onabort = function (event) {
  78648. try {
  78649. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  78650. var error = event.srcElement['error'];
  78651. if (error && error.name === "QuotaExceededError") {
  78652. _this.hasReachedQuota = true;
  78653. }
  78654. }
  78655. catch (ex) { }
  78656. callback(fileData);
  78657. };
  78658. transaction.oncomplete = function (event) {
  78659. callback(fileData);
  78660. };
  78661. var newFile;
  78662. if (targetStore === "scenes") {
  78663. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  78664. }
  78665. else {
  78666. newFile = { textureUrl: url, data: fileData };
  78667. }
  78668. try {
  78669. // Put the scene into the database
  78670. var addRequest = transaction.objectStore(targetStore).put(newFile);
  78671. addRequest.onsuccess = function (event) {
  78672. };
  78673. addRequest.onerror = function (event) {
  78674. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  78675. };
  78676. }
  78677. catch (ex) {
  78678. callback(fileData);
  78679. }
  78680. }
  78681. else {
  78682. callback(fileData);
  78683. }
  78684. }
  78685. else {
  78686. if (xhr.status >= 400 && errorCallback) {
  78687. errorCallback(xhr);
  78688. }
  78689. else {
  78690. callback();
  78691. }
  78692. }
  78693. }, false);
  78694. xhr.addEventListener("error", function (event) {
  78695. BABYLON.Tools.Error("error on XHR request.");
  78696. callback();
  78697. }, false);
  78698. xhr.send();
  78699. }
  78700. else {
  78701. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  78702. callback();
  78703. }
  78704. };
  78705. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  78706. Database.IsUASupportingBlobStorage = true;
  78707. /** Gets a boolean indicating if Database storate is enabled */
  78708. Database.IDBStorageEnabled = true;
  78709. Database._ParseURL = function (url) {
  78710. var a = document.createElement('a');
  78711. a.href = url;
  78712. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  78713. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  78714. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  78715. return absLocation;
  78716. };
  78717. Database._ReturnFullUrlLocation = function (url) {
  78718. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  78719. return (Database._ParseURL(window.location.href) + url);
  78720. }
  78721. else {
  78722. return url;
  78723. }
  78724. };
  78725. return Database;
  78726. }());
  78727. BABYLON.Database = Database;
  78728. })(BABYLON || (BABYLON = {}));
  78729. //# sourceMappingURL=babylon.database.js.map
  78730. var BABYLON;
  78731. (function (BABYLON) {
  78732. /**
  78733. * This represents all the required information to add a fresnel effect on a material:
  78734. * @see http://doc.babylonjs.com/how_to/how_to_use_fresnelparameters
  78735. */
  78736. var FresnelParameters = /** @class */ (function () {
  78737. function FresnelParameters() {
  78738. this._isEnabled = true;
  78739. /**
  78740. * Define the color used on edges (grazing angle)
  78741. */
  78742. this.leftColor = BABYLON.Color3.White();
  78743. /**
  78744. * Define the color used on center
  78745. */
  78746. this.rightColor = BABYLON.Color3.Black();
  78747. /**
  78748. * Define bias applied to computed fresnel term
  78749. */
  78750. this.bias = 0;
  78751. /**
  78752. * Defined the power exponent applied to fresnel term
  78753. */
  78754. this.power = 1;
  78755. }
  78756. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  78757. /**
  78758. * Define if the fresnel effect is enable or not.
  78759. */
  78760. get: function () {
  78761. return this._isEnabled;
  78762. },
  78763. set: function (value) {
  78764. if (this._isEnabled === value) {
  78765. return;
  78766. }
  78767. this._isEnabled = value;
  78768. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  78769. },
  78770. enumerable: true,
  78771. configurable: true
  78772. });
  78773. /**
  78774. * Clones the current fresnel and its valuues
  78775. * @returns a clone fresnel configuration
  78776. */
  78777. FresnelParameters.prototype.clone = function () {
  78778. var newFresnelParameters = new FresnelParameters();
  78779. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  78780. return newFresnelParameters;
  78781. };
  78782. /**
  78783. * Serializes the current fresnel parameters to a JSON representation.
  78784. * @return the JSON serialization
  78785. */
  78786. FresnelParameters.prototype.serialize = function () {
  78787. var serializationObject = {};
  78788. serializationObject.isEnabled = this.isEnabled;
  78789. serializationObject.leftColor = this.leftColor.asArray();
  78790. serializationObject.rightColor = this.rightColor.asArray();
  78791. serializationObject.bias = this.bias;
  78792. serializationObject.power = this.power;
  78793. return serializationObject;
  78794. };
  78795. /**
  78796. * Parse a JSON object and deserialize it to a new Fresnel parameter object.
  78797. * @param parsedFresnelParameters Define the JSON representation
  78798. * @returns the parsed parameters
  78799. */
  78800. FresnelParameters.Parse = function (parsedFresnelParameters) {
  78801. var fresnelParameters = new FresnelParameters();
  78802. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  78803. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  78804. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  78805. fresnelParameters.bias = parsedFresnelParameters.bias;
  78806. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  78807. return fresnelParameters;
  78808. };
  78809. return FresnelParameters;
  78810. }());
  78811. BABYLON.FresnelParameters = FresnelParameters;
  78812. })(BABYLON || (BABYLON = {}));
  78813. //# sourceMappingURL=babylon.fresnelParameters.js.map
  78814. var BABYLON;
  78815. (function (BABYLON) {
  78816. /**
  78817. * A multi-material is used to apply different materials to different parts of the same object without the need of
  78818. * separate meshes. This can be use to improve performances.
  78819. * @see http://doc.babylonjs.com/how_to/multi_materials
  78820. */
  78821. var MultiMaterial = /** @class */ (function (_super) {
  78822. __extends(MultiMaterial, _super);
  78823. /**
  78824. * Instantiates a new Multi Material
  78825. * A multi-material is used to apply different materials to different parts of the same object without the need of
  78826. * separate meshes. This can be use to improve performances.
  78827. * @see http://doc.babylonjs.com/how_to/multi_materials
  78828. * @param name Define the name in the scene
  78829. * @param scene Define the scene the material belongs to
  78830. */
  78831. function MultiMaterial(name, scene) {
  78832. var _this = _super.call(this, name, scene, true) || this;
  78833. scene.multiMaterials.push(_this);
  78834. _this.subMaterials = new Array();
  78835. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  78836. return _this;
  78837. }
  78838. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  78839. /**
  78840. * Gets or Sets the list of Materials used within the multi material.
  78841. * They need to be ordered according to the submeshes order in the associated mesh
  78842. */
  78843. get: function () {
  78844. return this._subMaterials;
  78845. },
  78846. set: function (value) {
  78847. this._subMaterials = value;
  78848. this._hookArray(value);
  78849. },
  78850. enumerable: true,
  78851. configurable: true
  78852. });
  78853. MultiMaterial.prototype._hookArray = function (array) {
  78854. var _this = this;
  78855. var oldPush = array.push;
  78856. array.push = function () {
  78857. var items = [];
  78858. for (var _i = 0; _i < arguments.length; _i++) {
  78859. items[_i] = arguments[_i];
  78860. }
  78861. var result = oldPush.apply(array, items);
  78862. _this._markAllSubMeshesAsTexturesDirty();
  78863. return result;
  78864. };
  78865. var oldSplice = array.splice;
  78866. array.splice = function (index, deleteCount) {
  78867. var deleted = oldSplice.apply(array, [index, deleteCount]);
  78868. _this._markAllSubMeshesAsTexturesDirty();
  78869. return deleted;
  78870. };
  78871. };
  78872. /**
  78873. * Get one of the submaterial by its index in the submaterials array
  78874. * @param index The index to look the sub material at
  78875. * @returns The Material if the index has been defined
  78876. */
  78877. MultiMaterial.prototype.getSubMaterial = function (index) {
  78878. if (index < 0 || index >= this.subMaterials.length) {
  78879. return this.getScene().defaultMaterial;
  78880. }
  78881. return this.subMaterials[index];
  78882. };
  78883. /**
  78884. * Get the list of active textures for the whole sub materials list.
  78885. * @returns All the textures that will be used during the rendering
  78886. */
  78887. MultiMaterial.prototype.getActiveTextures = function () {
  78888. var _a;
  78889. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  78890. if (subMaterial) {
  78891. return subMaterial.getActiveTextures();
  78892. }
  78893. else {
  78894. return [];
  78895. }
  78896. }));
  78897. };
  78898. /**
  78899. * Gets the current class name of the material e.g. "MultiMaterial"
  78900. * Mainly use in serialization.
  78901. * @returns the class name
  78902. */
  78903. MultiMaterial.prototype.getClassName = function () {
  78904. return "MultiMaterial";
  78905. };
  78906. /**
  78907. * Checks if the material is ready to render the requested sub mesh
  78908. * @param mesh Define the mesh the submesh belongs to
  78909. * @param subMesh Define the sub mesh to look readyness for
  78910. * @param useInstances Define whether or not the material is used with instances
  78911. * @returns true if ready, otherwise false
  78912. */
  78913. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  78914. for (var index = 0; index < this.subMaterials.length; index++) {
  78915. var subMaterial = this.subMaterials[index];
  78916. if (subMaterial) {
  78917. if (subMaterial.storeEffectOnSubMeshes) {
  78918. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  78919. return false;
  78920. }
  78921. continue;
  78922. }
  78923. if (!subMaterial.isReady(mesh)) {
  78924. return false;
  78925. }
  78926. }
  78927. }
  78928. return true;
  78929. };
  78930. /**
  78931. * Clones the current material and its related sub materials
  78932. * @param name Define the name of the newly cloned material
  78933. * @param cloneChildren Define if submaterial will be cloned or shared with the parent instance
  78934. * @returns the cloned material
  78935. */
  78936. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  78937. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  78938. for (var index = 0; index < this.subMaterials.length; index++) {
  78939. var subMaterial = null;
  78940. var current = this.subMaterials[index];
  78941. if (cloneChildren && current) {
  78942. subMaterial = current.clone(name + "-" + current.name);
  78943. }
  78944. else {
  78945. subMaterial = this.subMaterials[index];
  78946. }
  78947. newMultiMaterial.subMaterials.push(subMaterial);
  78948. }
  78949. return newMultiMaterial;
  78950. };
  78951. /**
  78952. * Serializes the materials into a JSON representation.
  78953. * @returns the JSON representation
  78954. */
  78955. MultiMaterial.prototype.serialize = function () {
  78956. var serializationObject = {};
  78957. serializationObject.name = this.name;
  78958. serializationObject.id = this.id;
  78959. if (BABYLON.Tags) {
  78960. serializationObject.tags = BABYLON.Tags.GetTags(this);
  78961. }
  78962. serializationObject.materials = [];
  78963. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  78964. var subMat = this.subMaterials[matIndex];
  78965. if (subMat) {
  78966. serializationObject.materials.push(subMat.id);
  78967. }
  78968. else {
  78969. serializationObject.materials.push(null);
  78970. }
  78971. }
  78972. return serializationObject;
  78973. };
  78974. /**
  78975. * Dispose the material and release its associated resources
  78976. * @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)
  78977. * @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)
  78978. */
  78979. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  78980. var scene = this.getScene();
  78981. if (!scene) {
  78982. return;
  78983. }
  78984. var index = scene.multiMaterials.indexOf(this);
  78985. if (index >= 0) {
  78986. scene.multiMaterials.splice(index, 1);
  78987. }
  78988. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  78989. };
  78990. return MultiMaterial;
  78991. }(BABYLON.Material));
  78992. BABYLON.MultiMaterial = MultiMaterial;
  78993. })(BABYLON || (BABYLON = {}));
  78994. //# sourceMappingURL=babylon.multiMaterial.js.map
  78995. var BABYLON;
  78996. (function (BABYLON) {
  78997. /**
  78998. * Manage the touch inputs to control the movement of a free camera.
  78999. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  79000. */
  79001. var FreeCameraTouchInput = /** @class */ (function () {
  79002. function FreeCameraTouchInput() {
  79003. /**
  79004. * Defines the touch sensibility for rotation.
  79005. * The higher the faster.
  79006. */
  79007. this.touchAngularSensibility = 200000.0;
  79008. /**
  79009. * Defines the touch sensibility for move.
  79010. * The higher the faster.
  79011. */
  79012. this.touchMoveSensibility = 250.0;
  79013. this._offsetX = null;
  79014. this._offsetY = null;
  79015. this._pointerPressed = new Array();
  79016. }
  79017. /**
  79018. * Attach the input controls to a specific dom element to get the input from.
  79019. * @param element Defines the element the controls should be listened from
  79020. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  79021. */
  79022. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  79023. var _this = this;
  79024. var previousPosition = null;
  79025. if (this._pointerInput === undefined) {
  79026. this._onLostFocus = function (evt) {
  79027. _this._offsetX = null;
  79028. _this._offsetY = null;
  79029. };
  79030. this._pointerInput = function (p, s) {
  79031. var evt = p.event;
  79032. if (evt.pointerType === "mouse") {
  79033. return;
  79034. }
  79035. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  79036. if (!noPreventDefault) {
  79037. evt.preventDefault();
  79038. }
  79039. _this._pointerPressed.push(evt.pointerId);
  79040. if (_this._pointerPressed.length !== 1) {
  79041. return;
  79042. }
  79043. previousPosition = {
  79044. x: evt.clientX,
  79045. y: evt.clientY
  79046. };
  79047. }
  79048. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  79049. if (!noPreventDefault) {
  79050. evt.preventDefault();
  79051. }
  79052. var index = _this._pointerPressed.indexOf(evt.pointerId);
  79053. if (index === -1) {
  79054. return;
  79055. }
  79056. _this._pointerPressed.splice(index, 1);
  79057. if (index != 0) {
  79058. return;
  79059. }
  79060. previousPosition = null;
  79061. _this._offsetX = null;
  79062. _this._offsetY = null;
  79063. }
  79064. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  79065. if (!noPreventDefault) {
  79066. evt.preventDefault();
  79067. }
  79068. if (!previousPosition) {
  79069. return;
  79070. }
  79071. var index = _this._pointerPressed.indexOf(evt.pointerId);
  79072. if (index != 0) {
  79073. return;
  79074. }
  79075. _this._offsetX = evt.clientX - previousPosition.x;
  79076. _this._offsetY = -(evt.clientY - previousPosition.y);
  79077. }
  79078. };
  79079. }
  79080. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  79081. if (this._onLostFocus) {
  79082. element.addEventListener("blur", this._onLostFocus);
  79083. }
  79084. };
  79085. /**
  79086. * Detach the current controls from the specified dom element.
  79087. * @param element Defines the element to stop listening the inputs from
  79088. */
  79089. FreeCameraTouchInput.prototype.detachControl = function (element) {
  79090. if (this._pointerInput && element) {
  79091. if (this._observer) {
  79092. this.camera.getScene().onPointerObservable.remove(this._observer);
  79093. this._observer = null;
  79094. }
  79095. if (this._onLostFocus) {
  79096. element.removeEventListener("blur", this._onLostFocus);
  79097. this._onLostFocus = null;
  79098. }
  79099. this._pointerPressed = [];
  79100. this._offsetX = null;
  79101. this._offsetY = null;
  79102. }
  79103. };
  79104. /**
  79105. * Update the current camera state depending on the inputs that have been used this frame.
  79106. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  79107. */
  79108. FreeCameraTouchInput.prototype.checkInputs = function () {
  79109. if (this._offsetX && this._offsetY) {
  79110. var camera = this.camera;
  79111. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  79112. if (this._pointerPressed.length > 1) {
  79113. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  79114. }
  79115. else {
  79116. var speed = camera._computeLocalCameraSpeed();
  79117. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  79118. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  79119. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  79120. }
  79121. }
  79122. };
  79123. /**
  79124. * Gets the class name of the current intput.
  79125. * @returns the class name
  79126. */
  79127. FreeCameraTouchInput.prototype.getClassName = function () {
  79128. return "FreeCameraTouchInput";
  79129. };
  79130. /**
  79131. * Get the friendly name associated with the input class.
  79132. * @returns the input friendly name
  79133. */
  79134. FreeCameraTouchInput.prototype.getSimpleName = function () {
  79135. return "touch";
  79136. };
  79137. __decorate([
  79138. BABYLON.serialize()
  79139. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  79140. __decorate([
  79141. BABYLON.serialize()
  79142. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  79143. return FreeCameraTouchInput;
  79144. }());
  79145. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  79146. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  79147. })(BABYLON || (BABYLON = {}));
  79148. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  79149. var BABYLON;
  79150. (function (BABYLON) {
  79151. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  79152. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  79153. });
  79154. /**
  79155. * This represents a FPS type of camera controlled by touch.
  79156. * This is like a universal camera minus the Gamepad controls.
  79157. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  79158. */
  79159. var TouchCamera = /** @class */ (function (_super) {
  79160. __extends(TouchCamera, _super);
  79161. /**
  79162. * Instantiates a new touch camera.
  79163. * This represents a FPS type of camera controlled by touch.
  79164. * This is like a universal camera minus the Gamepad controls.
  79165. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  79166. * @param name Define the name of the camera in the scene
  79167. * @param position Define the start position of the camera in the scene
  79168. * @param scene Define the scene the camera belongs to
  79169. */
  79170. function TouchCamera(name, position, scene) {
  79171. var _this = _super.call(this, name, position, scene) || this;
  79172. _this.inputs.addTouch();
  79173. _this._setupInputs();
  79174. return _this;
  79175. }
  79176. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  79177. /**
  79178. * Defines the touch sensibility for rotation.
  79179. * The higher the faster.
  79180. */
  79181. get: function () {
  79182. var touch = this.inputs.attached["touch"];
  79183. if (touch) {
  79184. return touch.touchAngularSensibility;
  79185. }
  79186. return 0;
  79187. },
  79188. set: function (value) {
  79189. var touch = this.inputs.attached["touch"];
  79190. if (touch) {
  79191. touch.touchAngularSensibility = value;
  79192. }
  79193. },
  79194. enumerable: true,
  79195. configurable: true
  79196. });
  79197. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  79198. /**
  79199. * Defines the touch sensibility for move.
  79200. * The higher the faster.
  79201. */
  79202. get: function () {
  79203. var touch = this.inputs.attached["touch"];
  79204. if (touch) {
  79205. return touch.touchMoveSensibility;
  79206. }
  79207. return 0;
  79208. },
  79209. set: function (value) {
  79210. var touch = this.inputs.attached["touch"];
  79211. if (touch) {
  79212. touch.touchMoveSensibility = value;
  79213. }
  79214. },
  79215. enumerable: true,
  79216. configurable: true
  79217. });
  79218. /**
  79219. * Gets the current object class name.
  79220. * @return the class name
  79221. */
  79222. TouchCamera.prototype.getClassName = function () {
  79223. return "TouchCamera";
  79224. };
  79225. /** @hidden */
  79226. TouchCamera.prototype._setupInputs = function () {
  79227. var mouse = this.inputs.attached["mouse"];
  79228. if (mouse) {
  79229. mouse.touchEnabled = false;
  79230. }
  79231. };
  79232. return TouchCamera;
  79233. }(BABYLON.FreeCamera));
  79234. BABYLON.TouchCamera = TouchCamera;
  79235. })(BABYLON || (BABYLON = {}));
  79236. //# sourceMappingURL=babylon.touchCamera.js.map
  79237. var BABYLON;
  79238. (function (BABYLON) {
  79239. /**
  79240. * 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.
  79241. * This is the base class of any Procedural texture and contains most of the shareable code.
  79242. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  79243. */
  79244. var ProceduralTexture = /** @class */ (function (_super) {
  79245. __extends(ProceduralTexture, _super);
  79246. /**
  79247. * Instantiates a new procedural texture.
  79248. * 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.
  79249. * This is the base class of any Procedural texture and contains most of the shareable code.
  79250. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  79251. * @param name Define the name of the texture
  79252. * @param size Define the size of the texture to create
  79253. * @param fragment Define the fragment shader to use to generate the texture or null if it is defined later
  79254. * @param scene Define the scene the texture belongs to
  79255. * @param fallbackTexture Define a fallback texture in case there were issues to create the custom texture
  79256. * @param generateMipMaps Define if the texture should creates mip maps or not
  79257. * @param isCube Define if the texture is a cube texture or not (this will render each faces of the cube)
  79258. */
  79259. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  79260. if (fallbackTexture === void 0) { fallbackTexture = null; }
  79261. if (generateMipMaps === void 0) { generateMipMaps = true; }
  79262. if (isCube === void 0) { isCube = false; }
  79263. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  79264. _this.isCube = isCube;
  79265. /**
  79266. * Define if the texture is enabled or not (disabled texture will not render)
  79267. */
  79268. _this.isEnabled = true;
  79269. /**
  79270. * Define if the texture must be cleared before rendering (default is true)
  79271. */
  79272. _this.autoClear = true;
  79273. /**
  79274. * Event raised when the texture is generated
  79275. */
  79276. _this.onGeneratedObservable = new BABYLON.Observable();
  79277. /** @hidden */
  79278. _this._textures = {};
  79279. _this._currentRefreshId = -1;
  79280. _this._refreshRate = 1;
  79281. _this._vertexBuffers = {};
  79282. _this._uniforms = new Array();
  79283. _this._samplers = new Array();
  79284. _this._floats = {};
  79285. _this._ints = {};
  79286. _this._floatsArrays = {};
  79287. _this._colors3 = {};
  79288. _this._colors4 = {};
  79289. _this._vectors2 = {};
  79290. _this._vectors3 = {};
  79291. _this._matrices = {};
  79292. _this._fallbackTextureUsed = false;
  79293. _this._cachedDefines = "";
  79294. _this._contentUpdateId = -1;
  79295. scene = _this.getScene();
  79296. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE);
  79297. if (!component) {
  79298. component = new BABYLON.ProceduralTextureSceneComponent(scene);
  79299. scene._addComponent(component);
  79300. }
  79301. scene.proceduralTextures.push(_this);
  79302. _this._engine = scene.getEngine();
  79303. _this.name = name;
  79304. _this.isRenderTarget = true;
  79305. _this._size = size;
  79306. _this._generateMipMaps = generateMipMaps;
  79307. _this.setFragment(fragment);
  79308. _this._fallbackTexture = fallbackTexture;
  79309. if (isCube) {
  79310. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps, generateDepthBuffer: false, generateStencilBuffer: false });
  79311. _this.setFloat("face", 0);
  79312. }
  79313. else {
  79314. _this._texture = _this._engine.createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, generateDepthBuffer: false, generateStencilBuffer: false });
  79315. }
  79316. // VBO
  79317. var vertices = [];
  79318. vertices.push(1, 1);
  79319. vertices.push(-1, 1);
  79320. vertices.push(-1, -1);
  79321. vertices.push(1, -1);
  79322. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  79323. _this._createIndexBuffer();
  79324. return _this;
  79325. }
  79326. /**
  79327. * Gets texture content (Use this function wisely as reading from a texture can be slow)
  79328. * @returns an ArrayBufferView (Uint8Array or Float32Array)
  79329. */
  79330. ProceduralTexture.prototype.getContent = function () {
  79331. if (this._contentData && this._currentRefreshId == this._contentUpdateId) {
  79332. return this._contentData;
  79333. }
  79334. this._contentData = this.readPixels(0, 0, this._contentData);
  79335. this._contentUpdateId = this._currentRefreshId;
  79336. return this._contentData;
  79337. };
  79338. ProceduralTexture.prototype._createIndexBuffer = function () {
  79339. var engine = this._engine;
  79340. // Indices
  79341. var indices = [];
  79342. indices.push(0);
  79343. indices.push(1);
  79344. indices.push(2);
  79345. indices.push(0);
  79346. indices.push(2);
  79347. indices.push(3);
  79348. this._indexBuffer = engine.createIndexBuffer(indices);
  79349. };
  79350. /** @hidden */
  79351. ProceduralTexture.prototype._rebuild = function () {
  79352. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79353. if (vb) {
  79354. vb._rebuild();
  79355. }
  79356. this._createIndexBuffer();
  79357. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  79358. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  79359. }
  79360. };
  79361. /**
  79362. * Resets the texture in order to recreate its associated resources.
  79363. * This can be called in case of context loss
  79364. */
  79365. ProceduralTexture.prototype.reset = function () {
  79366. if (this._effect === undefined) {
  79367. return;
  79368. }
  79369. var engine = this._engine;
  79370. engine._releaseEffect(this._effect);
  79371. };
  79372. ProceduralTexture.prototype._getDefines = function () {
  79373. return "";
  79374. };
  79375. /**
  79376. * Is the texture ready to be used ? (rendered at least once)
  79377. * @returns true if ready, otherwise, false.
  79378. */
  79379. ProceduralTexture.prototype.isReady = function () {
  79380. var _this = this;
  79381. var engine = this._engine;
  79382. var shaders;
  79383. if (!this._fragment) {
  79384. return false;
  79385. }
  79386. if (this._fallbackTextureUsed) {
  79387. return true;
  79388. }
  79389. var defines = this._getDefines();
  79390. if (this._effect && defines === this._cachedDefines && this._effect.isReady()) {
  79391. return true;
  79392. }
  79393. if (this._fragment.fragmentElement !== undefined) {
  79394. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  79395. }
  79396. else {
  79397. shaders = { vertex: "procedural", fragment: this._fragment };
  79398. }
  79399. this._cachedDefines = defines;
  79400. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, defines, undefined, undefined, function () {
  79401. _this.releaseInternalTexture();
  79402. if (_this._fallbackTexture) {
  79403. _this._texture = _this._fallbackTexture._texture;
  79404. if (_this._texture) {
  79405. _this._texture.incrementReferences();
  79406. }
  79407. }
  79408. _this._fallbackTextureUsed = true;
  79409. });
  79410. return this._effect.isReady();
  79411. };
  79412. /**
  79413. * Resets the refresh counter of the texture and start bak from scratch.
  79414. * Could be usefull to regenerate the texture if it is setup to render only once.
  79415. */
  79416. ProceduralTexture.prototype.resetRefreshCounter = function () {
  79417. this._currentRefreshId = -1;
  79418. };
  79419. /**
  79420. * Set the fragment shader to use in order to render the texture.
  79421. * @param fragment This can be set to a path (into the shader store) or to a json object containing a fragmentElement property.
  79422. */
  79423. ProceduralTexture.prototype.setFragment = function (fragment) {
  79424. this._fragment = fragment;
  79425. };
  79426. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  79427. /**
  79428. * Define the refresh rate of the texture or the rendering frequency.
  79429. * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  79430. */
  79431. get: function () {
  79432. return this._refreshRate;
  79433. },
  79434. set: function (value) {
  79435. this._refreshRate = value;
  79436. this.resetRefreshCounter();
  79437. },
  79438. enumerable: true,
  79439. configurable: true
  79440. });
  79441. /** @hidden */
  79442. ProceduralTexture.prototype._shouldRender = function () {
  79443. if (!this.isEnabled || !this.isReady() || !this._texture) {
  79444. if (this._texture) {
  79445. this._texture.isReady = false;
  79446. }
  79447. return false;
  79448. }
  79449. if (this._fallbackTextureUsed) {
  79450. return false;
  79451. }
  79452. if (this._currentRefreshId === -1) { // At least render once
  79453. this._currentRefreshId = 1;
  79454. return true;
  79455. }
  79456. if (this.refreshRate === this._currentRefreshId) {
  79457. this._currentRefreshId = 1;
  79458. return true;
  79459. }
  79460. this._currentRefreshId++;
  79461. return false;
  79462. };
  79463. /**
  79464. * Get the size the texture is rendering at.
  79465. * @returns the size (texture is always squared)
  79466. */
  79467. ProceduralTexture.prototype.getRenderSize = function () {
  79468. return this._size;
  79469. };
  79470. /**
  79471. * Resize the texture to new value.
  79472. * @param size Define the new size the texture should have
  79473. * @param generateMipMaps Define whether the new texture should create mip maps
  79474. */
  79475. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  79476. if (this._fallbackTextureUsed) {
  79477. return;
  79478. }
  79479. this.releaseInternalTexture();
  79480. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  79481. // Update properties
  79482. this._size = size;
  79483. this._generateMipMaps = generateMipMaps;
  79484. };
  79485. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  79486. if (this._uniforms.indexOf(uniformName) === -1) {
  79487. this._uniforms.push(uniformName);
  79488. }
  79489. };
  79490. /**
  79491. * Set a texture in the shader program used to render.
  79492. * @param name Define the name of the uniform samplers as defined in the shader
  79493. * @param texture Define the texture to bind to this sampler
  79494. * @return the texture itself allowing "fluent" like uniform updates
  79495. */
  79496. ProceduralTexture.prototype.setTexture = function (name, texture) {
  79497. if (this._samplers.indexOf(name) === -1) {
  79498. this._samplers.push(name);
  79499. }
  79500. this._textures[name] = texture;
  79501. return this;
  79502. };
  79503. /**
  79504. * Set a float in the shader.
  79505. * @param name Define the name of the uniform as defined in the shader
  79506. * @param value Define the value to give to the uniform
  79507. * @return the texture itself allowing "fluent" like uniform updates
  79508. */
  79509. ProceduralTexture.prototype.setFloat = function (name, value) {
  79510. this._checkUniform(name);
  79511. this._floats[name] = value;
  79512. return this;
  79513. };
  79514. /**
  79515. * Set a int in the shader.
  79516. * @param name Define the name of the uniform as defined in the shader
  79517. * @param value Define the value to give to the uniform
  79518. * @return the texture itself allowing "fluent" like uniform updates
  79519. */
  79520. ProceduralTexture.prototype.setInt = function (name, value) {
  79521. this._checkUniform(name);
  79522. this._ints[name] = value;
  79523. return this;
  79524. };
  79525. /**
  79526. * Set an array of floats in the shader.
  79527. * @param name Define the name of the uniform as defined in the shader
  79528. * @param value Define the value to give to the uniform
  79529. * @return the texture itself allowing "fluent" like uniform updates
  79530. */
  79531. ProceduralTexture.prototype.setFloats = function (name, value) {
  79532. this._checkUniform(name);
  79533. this._floatsArrays[name] = value;
  79534. return this;
  79535. };
  79536. /**
  79537. * Set a vec3 in the shader from a Color3.
  79538. * @param name Define the name of the uniform as defined in the shader
  79539. * @param value Define the value to give to the uniform
  79540. * @return the texture itself allowing "fluent" like uniform updates
  79541. */
  79542. ProceduralTexture.prototype.setColor3 = function (name, value) {
  79543. this._checkUniform(name);
  79544. this._colors3[name] = value;
  79545. return this;
  79546. };
  79547. /**
  79548. * Set a vec4 in the shader from a Color4.
  79549. * @param name Define the name of the uniform as defined in the shader
  79550. * @param value Define the value to give to the uniform
  79551. * @return the texture itself allowing "fluent" like uniform updates
  79552. */
  79553. ProceduralTexture.prototype.setColor4 = function (name, value) {
  79554. this._checkUniform(name);
  79555. this._colors4[name] = value;
  79556. return this;
  79557. };
  79558. /**
  79559. * Set a vec2 in the shader from a Vector2.
  79560. * @param name Define the name of the uniform as defined in the shader
  79561. * @param value Define the value to give to the uniform
  79562. * @return the texture itself allowing "fluent" like uniform updates
  79563. */
  79564. ProceduralTexture.prototype.setVector2 = function (name, value) {
  79565. this._checkUniform(name);
  79566. this._vectors2[name] = value;
  79567. return this;
  79568. };
  79569. /**
  79570. * Set a vec3 in the shader from a Vector3.
  79571. * @param name Define the name of the uniform as defined in the shader
  79572. * @param value Define the value to give to the uniform
  79573. * @return the texture itself allowing "fluent" like uniform updates
  79574. */
  79575. ProceduralTexture.prototype.setVector3 = function (name, value) {
  79576. this._checkUniform(name);
  79577. this._vectors3[name] = value;
  79578. return this;
  79579. };
  79580. /**
  79581. * Set a mat4 in the shader from a MAtrix.
  79582. * @param name Define the name of the uniform as defined in the shader
  79583. * @param value Define the value to give to the uniform
  79584. * @return the texture itself allowing "fluent" like uniform updates
  79585. */
  79586. ProceduralTexture.prototype.setMatrix = function (name, value) {
  79587. this._checkUniform(name);
  79588. this._matrices[name] = value;
  79589. return this;
  79590. };
  79591. /**
  79592. * Render the texture to its associated render target.
  79593. * @param useCameraPostProcess Define if camera post process should be applied to the texture
  79594. */
  79595. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  79596. var scene = this.getScene();
  79597. if (!scene) {
  79598. return;
  79599. }
  79600. var engine = this._engine;
  79601. // Render
  79602. engine.enableEffect(this._effect);
  79603. engine.setState(false);
  79604. // Texture
  79605. for (var name in this._textures) {
  79606. this._effect.setTexture(name, this._textures[name]);
  79607. }
  79608. // Float
  79609. for (name in this._ints) {
  79610. this._effect.setInt(name, this._ints[name]);
  79611. }
  79612. // Float
  79613. for (name in this._floats) {
  79614. this._effect.setFloat(name, this._floats[name]);
  79615. }
  79616. // Floats
  79617. for (name in this._floatsArrays) {
  79618. this._effect.setArray(name, this._floatsArrays[name]);
  79619. }
  79620. // Color3
  79621. for (name in this._colors3) {
  79622. this._effect.setColor3(name, this._colors3[name]);
  79623. }
  79624. // Color4
  79625. for (name in this._colors4) {
  79626. var color = this._colors4[name];
  79627. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  79628. }
  79629. // Vector2
  79630. for (name in this._vectors2) {
  79631. this._effect.setVector2(name, this._vectors2[name]);
  79632. }
  79633. // Vector3
  79634. for (name in this._vectors3) {
  79635. this._effect.setVector3(name, this._vectors3[name]);
  79636. }
  79637. // Matrix
  79638. for (name in this._matrices) {
  79639. this._effect.setMatrix(name, this._matrices[name]);
  79640. }
  79641. if (!this._texture) {
  79642. return;
  79643. }
  79644. if (this.isCube) {
  79645. for (var face = 0; face < 6; face++) {
  79646. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  79647. // VBOs
  79648. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  79649. this._effect.setFloat("face", face);
  79650. // Clear
  79651. if (this.autoClear) {
  79652. engine.clear(scene.clearColor, true, false, false);
  79653. }
  79654. // Draw order
  79655. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  79656. // Mipmaps
  79657. if (face === 5) {
  79658. engine.generateMipMapsForCubemap(this._texture);
  79659. }
  79660. }
  79661. }
  79662. else {
  79663. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  79664. // VBOs
  79665. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  79666. // Clear
  79667. if (this.autoClear) {
  79668. engine.clear(scene.clearColor, true, false, false);
  79669. }
  79670. // Draw order
  79671. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  79672. }
  79673. // Unbind
  79674. engine.unBindFramebuffer(this._texture, this.isCube);
  79675. if (this.onGenerated) {
  79676. this.onGenerated();
  79677. }
  79678. this.onGeneratedObservable.notifyObservers(this);
  79679. };
  79680. /**
  79681. * Clone the texture.
  79682. * @returns the cloned texture
  79683. */
  79684. ProceduralTexture.prototype.clone = function () {
  79685. var textureSize = this.getSize();
  79686. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  79687. // Base texture
  79688. newTexture.hasAlpha = this.hasAlpha;
  79689. newTexture.level = this.level;
  79690. // RenderTarget Texture
  79691. newTexture.coordinatesMode = this.coordinatesMode;
  79692. return newTexture;
  79693. };
  79694. /**
  79695. * Dispose the texture and release its asoociated resources.
  79696. */
  79697. ProceduralTexture.prototype.dispose = function () {
  79698. var scene = this.getScene();
  79699. if (!scene) {
  79700. return;
  79701. }
  79702. var index = scene.proceduralTextures.indexOf(this);
  79703. if (index >= 0) {
  79704. scene.proceduralTextures.splice(index, 1);
  79705. }
  79706. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79707. if (vertexBuffer) {
  79708. vertexBuffer.dispose();
  79709. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  79710. }
  79711. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  79712. this._indexBuffer = null;
  79713. }
  79714. _super.prototype.dispose.call(this);
  79715. };
  79716. __decorate([
  79717. BABYLON.serialize()
  79718. ], ProceduralTexture.prototype, "isEnabled", void 0);
  79719. __decorate([
  79720. BABYLON.serialize()
  79721. ], ProceduralTexture.prototype, "autoClear", void 0);
  79722. __decorate([
  79723. BABYLON.serialize()
  79724. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  79725. __decorate([
  79726. BABYLON.serialize()
  79727. ], ProceduralTexture.prototype, "_size", void 0);
  79728. __decorate([
  79729. BABYLON.serialize()
  79730. ], ProceduralTexture.prototype, "refreshRate", null);
  79731. return ProceduralTexture;
  79732. }(BABYLON.Texture));
  79733. BABYLON.ProceduralTexture = ProceduralTexture;
  79734. })(BABYLON || (BABYLON = {}));
  79735. //# sourceMappingURL=babylon.proceduralTexture.js.map
  79736. var BABYLON;
  79737. (function (BABYLON) {
  79738. /**
  79739. * Defines the Procedural Texture scene component responsible to manage any Procedural Texture
  79740. * in a given scene.
  79741. */
  79742. var ProceduralTextureSceneComponent = /** @class */ (function () {
  79743. /**
  79744. * Creates a new instance of the component for the given scene
  79745. * @param scene Defines the scene to register the component in
  79746. */
  79747. function ProceduralTextureSceneComponent(scene) {
  79748. /**
  79749. * The component name helpfull to identify the component in the list of scene components.
  79750. */
  79751. this.name = BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE;
  79752. this.scene = scene;
  79753. this.scene.proceduralTextures = new Array();
  79754. scene.layers = new Array();
  79755. }
  79756. /**
  79757. * Registers the component in a given scene
  79758. */
  79759. ProceduralTextureSceneComponent.prototype.register = function () {
  79760. this.scene._beforeClearStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear);
  79761. };
  79762. /**
  79763. * Rebuilds the elements related to this component in case of
  79764. * context lost for instance.
  79765. */
  79766. ProceduralTextureSceneComponent.prototype.rebuild = function () {
  79767. // Nothing to do here.
  79768. };
  79769. /**
  79770. * Disposes the component and the associated ressources.
  79771. */
  79772. ProceduralTextureSceneComponent.prototype.dispose = function () {
  79773. // Nothing to do here.
  79774. };
  79775. ProceduralTextureSceneComponent.prototype._beforeClear = function () {
  79776. if (this.scene.proceduralTexturesEnabled) {
  79777. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  79778. for (var proceduralIndex = 0; proceduralIndex < this.scene.proceduralTextures.length; proceduralIndex++) {
  79779. var proceduralTexture = this.scene.proceduralTextures[proceduralIndex];
  79780. if (proceduralTexture._shouldRender()) {
  79781. proceduralTexture.render();
  79782. }
  79783. }
  79784. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  79785. }
  79786. };
  79787. return ProceduralTextureSceneComponent;
  79788. }());
  79789. BABYLON.ProceduralTextureSceneComponent = ProceduralTextureSceneComponent;
  79790. })(BABYLON || (BABYLON = {}));
  79791. //# sourceMappingURL=babylon.proceduralTextureSceneComponent.js.map
  79792. var BABYLON;
  79793. (function (BABYLON) {
  79794. /**
  79795. * 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.
  79796. * Custom Procedural textures are the easiest way to create your own procedural in your application.
  79797. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures#creating-custom-procedural-textures
  79798. */
  79799. var CustomProceduralTexture = /** @class */ (function (_super) {
  79800. __extends(CustomProceduralTexture, _super);
  79801. /**
  79802. * Instantiates a new Custom Procedural Texture.
  79803. * 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.
  79804. * Custom Procedural textures are the easiest way to create your own procedural in your application.
  79805. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures#creating-custom-procedural-textures
  79806. * @param name Define the name of the texture
  79807. * @param texturePath Define the folder path containing all the cutom texture related files (config, shaders...)
  79808. * @param size Define the size of the texture to create
  79809. * @param scene Define the scene the texture belongs to
  79810. * @param fallbackTexture Define a fallback texture in case there were issues to create the custom texture
  79811. * @param generateMipMaps Define if the texture should creates mip maps or not
  79812. */
  79813. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  79814. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  79815. _this._animate = true;
  79816. _this._time = 0;
  79817. _this._texturePath = texturePath;
  79818. //Try to load json
  79819. _this._loadJson(texturePath);
  79820. _this.refreshRate = 1;
  79821. return _this;
  79822. }
  79823. CustomProceduralTexture.prototype._loadJson = function (jsonUrl) {
  79824. var _this = this;
  79825. var noConfigFile = function () {
  79826. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  79827. try {
  79828. _this.setFragment(_this._texturePath);
  79829. }
  79830. catch (ex) {
  79831. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  79832. }
  79833. };
  79834. var configFileUrl = jsonUrl + "/config.json";
  79835. var xhr = new XMLHttpRequest();
  79836. xhr.open("GET", configFileUrl, true);
  79837. xhr.addEventListener("load", function () {
  79838. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  79839. try {
  79840. _this._config = JSON.parse(xhr.response);
  79841. _this.updateShaderUniforms();
  79842. _this.updateTextures();
  79843. _this.setFragment(_this._texturePath + "/custom");
  79844. _this._animate = _this._config.animate;
  79845. _this.refreshRate = _this._config.refreshrate;
  79846. }
  79847. catch (ex) {
  79848. noConfigFile();
  79849. }
  79850. }
  79851. else {
  79852. noConfigFile();
  79853. }
  79854. }, false);
  79855. xhr.addEventListener("error", function () {
  79856. noConfigFile();
  79857. }, false);
  79858. try {
  79859. xhr.send();
  79860. }
  79861. catch (ex) {
  79862. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  79863. }
  79864. };
  79865. /**
  79866. * Is the texture ready to be used ? (rendered at least once)
  79867. * @returns true if ready, otherwise, false.
  79868. */
  79869. CustomProceduralTexture.prototype.isReady = function () {
  79870. if (!_super.prototype.isReady.call(this)) {
  79871. return false;
  79872. }
  79873. for (var name in this._textures) {
  79874. var texture = this._textures[name];
  79875. if (!texture.isReady()) {
  79876. return false;
  79877. }
  79878. }
  79879. return true;
  79880. };
  79881. /**
  79882. * Render the texture to its associated render target.
  79883. * @param useCameraPostProcess Define if camera post process should be applied to the texture
  79884. */
  79885. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  79886. var scene = this.getScene();
  79887. if (this._animate && scene) {
  79888. this._time += scene.getAnimationRatio() * 0.03;
  79889. this.updateShaderUniforms();
  79890. }
  79891. _super.prototype.render.call(this, useCameraPostProcess);
  79892. };
  79893. /**
  79894. * Update the list of dependant textures samplers in the shader.
  79895. */
  79896. CustomProceduralTexture.prototype.updateTextures = function () {
  79897. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  79898. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  79899. }
  79900. };
  79901. /**
  79902. * Update the uniform values of the procedural texture in the shader.
  79903. */
  79904. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  79905. if (this._config) {
  79906. for (var j = 0; j < this._config.uniforms.length; j++) {
  79907. var uniform = this._config.uniforms[j];
  79908. switch (uniform.type) {
  79909. case "float":
  79910. this.setFloat(uniform.name, uniform.value);
  79911. break;
  79912. case "color3":
  79913. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  79914. break;
  79915. case "color4":
  79916. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  79917. break;
  79918. case "vector2":
  79919. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  79920. break;
  79921. case "vector3":
  79922. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  79923. break;
  79924. }
  79925. }
  79926. }
  79927. this.setFloat("time", this._time);
  79928. };
  79929. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  79930. /**
  79931. * Define if the texture animates or not.
  79932. */
  79933. get: function () {
  79934. return this._animate;
  79935. },
  79936. set: function (value) {
  79937. this._animate = value;
  79938. },
  79939. enumerable: true,
  79940. configurable: true
  79941. });
  79942. return CustomProceduralTexture;
  79943. }(BABYLON.ProceduralTexture));
  79944. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  79945. })(BABYLON || (BABYLON = {}));
  79946. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  79947. var BABYLON;
  79948. (function (BABYLON) {
  79949. /**
  79950. * Manage the gamepad inputs to control a free camera.
  79951. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  79952. */
  79953. var FreeCameraGamepadInput = /** @class */ (function () {
  79954. function FreeCameraGamepadInput() {
  79955. /**
  79956. * Defines the gamepad rotation sensiblity.
  79957. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  79958. */
  79959. this.gamepadAngularSensibility = 200;
  79960. /**
  79961. * Defines the gamepad move sensiblity.
  79962. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  79963. */
  79964. this.gamepadMoveSensibility = 40;
  79965. this._cameraTransform = BABYLON.Matrix.Identity();
  79966. this._deltaTransform = BABYLON.Vector3.Zero();
  79967. this._vector3 = BABYLON.Vector3.Zero();
  79968. this._vector2 = BABYLON.Vector2.Zero();
  79969. }
  79970. /**
  79971. * Attach the input controls to a specific dom element to get the input from.
  79972. * @param element Defines the element the controls should be listened from
  79973. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  79974. */
  79975. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  79976. var _this = this;
  79977. var manager = this.camera.getScene().gamepadManager;
  79978. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  79979. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  79980. // prioritize XBOX gamepads.
  79981. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  79982. _this.gamepad = gamepad;
  79983. }
  79984. }
  79985. });
  79986. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  79987. if (_this.gamepad === gamepad) {
  79988. _this.gamepad = null;
  79989. }
  79990. });
  79991. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  79992. };
  79993. /**
  79994. * Detach the current controls from the specified dom element.
  79995. * @param element Defines the element to stop listening the inputs from
  79996. */
  79997. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  79998. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  79999. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  80000. this.gamepad = null;
  80001. };
  80002. /**
  80003. * Update the current camera state depending on the inputs that have been used this frame.
  80004. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  80005. */
  80006. FreeCameraGamepadInput.prototype.checkInputs = function () {
  80007. if (this.gamepad && this.gamepad.leftStick) {
  80008. var camera = this.camera;
  80009. var LSValues = this.gamepad.leftStick;
  80010. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  80011. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  80012. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  80013. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  80014. var RSValues = this.gamepad.rightStick;
  80015. if (RSValues) {
  80016. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  80017. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  80018. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  80019. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  80020. }
  80021. else {
  80022. RSValues = { x: 0, y: 0 };
  80023. }
  80024. if (!camera.rotationQuaternion) {
  80025. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  80026. }
  80027. else {
  80028. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  80029. }
  80030. var speed = camera._computeLocalCameraSpeed() * 50.0;
  80031. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  80032. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  80033. camera.cameraDirection.addInPlace(this._deltaTransform);
  80034. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  80035. camera.cameraRotation.addInPlace(this._vector2);
  80036. }
  80037. };
  80038. /**
  80039. * Gets the class name of the current intput.
  80040. * @returns the class name
  80041. */
  80042. FreeCameraGamepadInput.prototype.getClassName = function () {
  80043. return "FreeCameraGamepadInput";
  80044. };
  80045. /**
  80046. * Get the friendly name associated with the input class.
  80047. * @returns the input friendly name
  80048. */
  80049. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  80050. return "gamepad";
  80051. };
  80052. __decorate([
  80053. BABYLON.serialize()
  80054. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  80055. __decorate([
  80056. BABYLON.serialize()
  80057. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  80058. return FreeCameraGamepadInput;
  80059. }());
  80060. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  80061. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  80062. })(BABYLON || (BABYLON = {}));
  80063. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  80064. var BABYLON;
  80065. (function (BABYLON) {
  80066. /**
  80067. * Manage the gamepad inputs to control an arc rotate camera.
  80068. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  80069. */
  80070. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  80071. function ArcRotateCameraGamepadInput() {
  80072. /**
  80073. * Defines the gamepad rotation sensiblity.
  80074. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  80075. */
  80076. this.gamepadRotationSensibility = 80;
  80077. /**
  80078. * Defines the gamepad move sensiblity.
  80079. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  80080. */
  80081. this.gamepadMoveSensibility = 40;
  80082. }
  80083. /**
  80084. * Attach the input controls to a specific dom element to get the input from.
  80085. * @param element Defines the element the controls should be listened from
  80086. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  80087. */
  80088. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  80089. var _this = this;
  80090. var manager = this.camera.getScene().gamepadManager;
  80091. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  80092. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  80093. // prioritize XBOX gamepads.
  80094. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  80095. _this.gamepad = gamepad;
  80096. }
  80097. }
  80098. });
  80099. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  80100. if (_this.gamepad === gamepad) {
  80101. _this.gamepad = null;
  80102. }
  80103. });
  80104. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  80105. };
  80106. /**
  80107. * Detach the current controls from the specified dom element.
  80108. * @param element Defines the element to stop listening the inputs from
  80109. */
  80110. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  80111. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  80112. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  80113. this.gamepad = null;
  80114. };
  80115. /**
  80116. * Update the current camera state depending on the inputs that have been used this frame.
  80117. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  80118. */
  80119. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  80120. if (this.gamepad) {
  80121. var camera = this.camera;
  80122. var RSValues = this.gamepad.rightStick;
  80123. if (RSValues) {
  80124. if (RSValues.x != 0) {
  80125. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  80126. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  80127. camera.inertialAlphaOffset += normalizedRX;
  80128. }
  80129. }
  80130. if (RSValues.y != 0) {
  80131. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  80132. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  80133. camera.inertialBetaOffset += normalizedRY;
  80134. }
  80135. }
  80136. }
  80137. var LSValues = this.gamepad.leftStick;
  80138. if (LSValues && LSValues.y != 0) {
  80139. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  80140. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  80141. this.camera.inertialRadiusOffset -= normalizedLY;
  80142. }
  80143. }
  80144. }
  80145. };
  80146. /**
  80147. * Gets the class name of the current intput.
  80148. * @returns the class name
  80149. */
  80150. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  80151. return "ArcRotateCameraGamepadInput";
  80152. };
  80153. /**
  80154. * Get the friendly name associated with the input class.
  80155. * @returns the input friendly name
  80156. */
  80157. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  80158. return "gamepad";
  80159. };
  80160. __decorate([
  80161. BABYLON.serialize()
  80162. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  80163. __decorate([
  80164. BABYLON.serialize()
  80165. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  80166. return ArcRotateCameraGamepadInput;
  80167. }());
  80168. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  80169. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  80170. })(BABYLON || (BABYLON = {}));
  80171. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  80172. var BABYLON;
  80173. (function (BABYLON) {
  80174. /**
  80175. * Manager for handling gamepads
  80176. */
  80177. var GamepadManager = /** @class */ (function () {
  80178. /**
  80179. * Initializes the gamepad manager
  80180. * @param _scene BabylonJS scene
  80181. */
  80182. function GamepadManager(_scene) {
  80183. var _this = this;
  80184. this._scene = _scene;
  80185. this._babylonGamepads = [];
  80186. this._oneGamepadConnected = false;
  80187. /** @hidden */
  80188. this._isMonitoring = false;
  80189. /**
  80190. * observable to be triggered when the gamepad controller has been disconnected
  80191. */
  80192. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  80193. if (!BABYLON.Tools.IsWindowObjectExist()) {
  80194. this._gamepadEventSupported = false;
  80195. }
  80196. else {
  80197. this._gamepadEventSupported = 'GamepadEvent' in window;
  80198. this._gamepadSupport = (navigator.getGamepads ||
  80199. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  80200. }
  80201. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  80202. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  80203. for (var i in _this._babylonGamepads) {
  80204. var gamepad = _this._babylonGamepads[i];
  80205. if (gamepad && gamepad._isConnected) {
  80206. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  80207. }
  80208. }
  80209. });
  80210. this._onGamepadConnectedEvent = function (evt) {
  80211. var gamepad = evt.gamepad;
  80212. if (gamepad.index in _this._babylonGamepads) {
  80213. if (_this._babylonGamepads[gamepad.index].isConnected) {
  80214. return;
  80215. }
  80216. }
  80217. var newGamepad;
  80218. if (_this._babylonGamepads[gamepad.index]) {
  80219. newGamepad = _this._babylonGamepads[gamepad.index];
  80220. newGamepad.browserGamepad = gamepad;
  80221. newGamepad._isConnected = true;
  80222. }
  80223. else {
  80224. newGamepad = _this._addNewGamepad(gamepad);
  80225. }
  80226. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  80227. _this._startMonitoringGamepads();
  80228. };
  80229. this._onGamepadDisconnectedEvent = function (evt) {
  80230. var gamepad = evt.gamepad;
  80231. // Remove the gamepad from the list of gamepads to monitor.
  80232. for (var i in _this._babylonGamepads) {
  80233. if (_this._babylonGamepads[i].index === gamepad.index) {
  80234. var disconnectedGamepad = _this._babylonGamepads[i];
  80235. disconnectedGamepad._isConnected = false;
  80236. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  80237. break;
  80238. }
  80239. }
  80240. };
  80241. if (this._gamepadSupport) {
  80242. //first add already-connected gamepads
  80243. this._updateGamepadObjects();
  80244. if (this._babylonGamepads.length) {
  80245. this._startMonitoringGamepads();
  80246. }
  80247. // Checking if the gamepad connected event is supported (like in Firefox)
  80248. if (this._gamepadEventSupported) {
  80249. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  80250. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  80251. }
  80252. else {
  80253. this._startMonitoringGamepads();
  80254. }
  80255. }
  80256. }
  80257. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  80258. /**
  80259. * The gamepads in the game pad manager
  80260. */
  80261. get: function () {
  80262. return this._babylonGamepads;
  80263. },
  80264. enumerable: true,
  80265. configurable: true
  80266. });
  80267. /**
  80268. * Get the gamepad controllers based on type
  80269. * @param type The type of gamepad controller
  80270. * @returns Nullable gamepad
  80271. */
  80272. GamepadManager.prototype.getGamepadByType = function (type) {
  80273. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  80274. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  80275. var gamepad = _a[_i];
  80276. if (gamepad && gamepad.type === type) {
  80277. return gamepad;
  80278. }
  80279. }
  80280. return null;
  80281. };
  80282. /**
  80283. * Disposes the gamepad manager
  80284. */
  80285. GamepadManager.prototype.dispose = function () {
  80286. if (this._gamepadEventSupported) {
  80287. if (this._onGamepadConnectedEvent) {
  80288. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  80289. }
  80290. if (this._onGamepadDisconnectedEvent) {
  80291. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  80292. }
  80293. this._onGamepadConnectedEvent = null;
  80294. this._onGamepadDisconnectedEvent = null;
  80295. }
  80296. this._babylonGamepads.forEach(function (gamepad) {
  80297. gamepad.dispose();
  80298. });
  80299. this.onGamepadConnectedObservable.clear();
  80300. this.onGamepadDisconnectedObservable.clear();
  80301. this._oneGamepadConnected = false;
  80302. this._stopMonitoringGamepads();
  80303. this._babylonGamepads = [];
  80304. };
  80305. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  80306. if (!this._oneGamepadConnected) {
  80307. this._oneGamepadConnected = true;
  80308. }
  80309. var newGamepad;
  80310. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  80311. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  80312. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  80313. }
  80314. // if pose is supported, use the (WebVR) pose enabled controller
  80315. else if (gamepad.pose) {
  80316. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  80317. }
  80318. else {
  80319. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  80320. }
  80321. this._babylonGamepads[newGamepad.index] = newGamepad;
  80322. return newGamepad;
  80323. };
  80324. GamepadManager.prototype._startMonitoringGamepads = function () {
  80325. if (!this._isMonitoring) {
  80326. this._isMonitoring = true;
  80327. //back-comp
  80328. if (!this._scene) {
  80329. this._checkGamepadsStatus();
  80330. }
  80331. }
  80332. };
  80333. GamepadManager.prototype._stopMonitoringGamepads = function () {
  80334. this._isMonitoring = false;
  80335. };
  80336. /** @hidden */
  80337. GamepadManager.prototype._checkGamepadsStatus = function () {
  80338. var _this = this;
  80339. // Hack to be compatible Chrome
  80340. this._updateGamepadObjects();
  80341. for (var i in this._babylonGamepads) {
  80342. var gamepad = this._babylonGamepads[i];
  80343. if (!gamepad || !gamepad.isConnected) {
  80344. continue;
  80345. }
  80346. gamepad.update();
  80347. }
  80348. if (this._isMonitoring && !this._scene) {
  80349. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  80350. }
  80351. };
  80352. // This function is called only on Chrome, which does not properly support
  80353. // connection/disconnection events and forces you to recopy again the gamepad object
  80354. GamepadManager.prototype._updateGamepadObjects = function () {
  80355. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  80356. for (var i = 0; i < gamepads.length; i++) {
  80357. var gamepad = gamepads[i];
  80358. if (gamepad) {
  80359. if (!this._babylonGamepads[gamepad.index]) {
  80360. var newGamepad = this._addNewGamepad(gamepad);
  80361. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  80362. }
  80363. else {
  80364. // Forced to copy again this object for Chrome for unknown reason
  80365. this._babylonGamepads[i].browserGamepad = gamepad;
  80366. if (!this._babylonGamepads[i].isConnected) {
  80367. this._babylonGamepads[i]._isConnected = true;
  80368. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  80369. }
  80370. }
  80371. }
  80372. }
  80373. };
  80374. return GamepadManager;
  80375. }());
  80376. BABYLON.GamepadManager = GamepadManager;
  80377. })(BABYLON || (BABYLON = {}));
  80378. //# sourceMappingURL=babylon.gamepadManager.js.map
  80379. var BABYLON;
  80380. (function (BABYLON) {
  80381. /**
  80382. * Represents a gamepad control stick position
  80383. */
  80384. var StickValues = /** @class */ (function () {
  80385. /**
  80386. * Initializes the gamepad x and y control stick values
  80387. * @param x The x component of the gamepad control stick value
  80388. * @param y The y component of the gamepad control stick value
  80389. */
  80390. function StickValues(
  80391. /**
  80392. * The x component of the control stick
  80393. */
  80394. x,
  80395. /**
  80396. * The y component of the control stick
  80397. */
  80398. y) {
  80399. this.x = x;
  80400. this.y = y;
  80401. }
  80402. return StickValues;
  80403. }());
  80404. BABYLON.StickValues = StickValues;
  80405. /**
  80406. * Represents a gamepad
  80407. */
  80408. var Gamepad = /** @class */ (function () {
  80409. /**
  80410. * Initializes the gamepad
  80411. * @param id The id of the gamepad
  80412. * @param index The index of the gamepad
  80413. * @param browserGamepad The browser gamepad
  80414. * @param leftStickX The x component of the left joystick
  80415. * @param leftStickY The y component of the left joystick
  80416. * @param rightStickX The x component of the right joystick
  80417. * @param rightStickY The y component of the right joystick
  80418. */
  80419. function Gamepad(
  80420. /**
  80421. * The id of the gamepad
  80422. */
  80423. id,
  80424. /**
  80425. * The index of the gamepad
  80426. */
  80427. index,
  80428. /**
  80429. * The browser gamepad
  80430. */
  80431. browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  80432. if (leftStickX === void 0) { leftStickX = 0; }
  80433. if (leftStickY === void 0) { leftStickY = 1; }
  80434. if (rightStickX === void 0) { rightStickX = 2; }
  80435. if (rightStickY === void 0) { rightStickY = 3; }
  80436. this.id = id;
  80437. this.index = index;
  80438. this.browserGamepad = browserGamepad;
  80439. this._leftStick = { x: 0, y: 0 };
  80440. this._rightStick = { x: 0, y: 0 };
  80441. /** @hidden */
  80442. this._isConnected = true;
  80443. /**
  80444. * Specifies whether the left control stick should be Y-inverted
  80445. */
  80446. this._invertLeftStickY = false;
  80447. this.type = Gamepad.GAMEPAD;
  80448. this._leftStickAxisX = leftStickX;
  80449. this._leftStickAxisY = leftStickY;
  80450. this._rightStickAxisX = rightStickX;
  80451. this._rightStickAxisY = rightStickY;
  80452. if (this.browserGamepad.axes.length >= 2) {
  80453. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  80454. }
  80455. if (this.browserGamepad.axes.length >= 4) {
  80456. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  80457. }
  80458. }
  80459. Object.defineProperty(Gamepad.prototype, "isConnected", {
  80460. /**
  80461. * Specifies if the gamepad has been connected
  80462. */
  80463. get: function () {
  80464. return this._isConnected;
  80465. },
  80466. enumerable: true,
  80467. configurable: true
  80468. });
  80469. /**
  80470. * Callback triggered when the left joystick has changed
  80471. * @param callback
  80472. */
  80473. Gamepad.prototype.onleftstickchanged = function (callback) {
  80474. this._onleftstickchanged = callback;
  80475. };
  80476. /**
  80477. * Callback triggered when the right joystick has changed
  80478. * @param callback
  80479. */
  80480. Gamepad.prototype.onrightstickchanged = function (callback) {
  80481. this._onrightstickchanged = callback;
  80482. };
  80483. Object.defineProperty(Gamepad.prototype, "leftStick", {
  80484. /**
  80485. * Gets the left joystick
  80486. */
  80487. get: function () {
  80488. return this._leftStick;
  80489. },
  80490. /**
  80491. * Sets the left joystick values
  80492. */
  80493. set: function (newValues) {
  80494. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  80495. this._onleftstickchanged(newValues);
  80496. }
  80497. this._leftStick = newValues;
  80498. },
  80499. enumerable: true,
  80500. configurable: true
  80501. });
  80502. Object.defineProperty(Gamepad.prototype, "rightStick", {
  80503. /**
  80504. * Gets the right joystick
  80505. */
  80506. get: function () {
  80507. return this._rightStick;
  80508. },
  80509. /**
  80510. * Sets the right joystick value
  80511. */
  80512. set: function (newValues) {
  80513. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  80514. this._onrightstickchanged(newValues);
  80515. }
  80516. this._rightStick = newValues;
  80517. },
  80518. enumerable: true,
  80519. configurable: true
  80520. });
  80521. /**
  80522. * Updates the gamepad joystick positions
  80523. */
  80524. Gamepad.prototype.update = function () {
  80525. if (this._leftStick) {
  80526. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  80527. if (this._invertLeftStickY) {
  80528. this.leftStick.y *= -1;
  80529. }
  80530. }
  80531. if (this._rightStick) {
  80532. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  80533. }
  80534. };
  80535. /**
  80536. * Disposes the gamepad
  80537. */
  80538. Gamepad.prototype.dispose = function () {
  80539. };
  80540. /**
  80541. * Represents a gamepad controller
  80542. */
  80543. Gamepad.GAMEPAD = 0;
  80544. /**
  80545. * Represents a generic controller
  80546. */
  80547. Gamepad.GENERIC = 1;
  80548. /**
  80549. * Represents an XBox controller
  80550. */
  80551. Gamepad.XBOX = 2;
  80552. /**
  80553. * Represents a pose-enabled controller
  80554. */
  80555. Gamepad.POSE_ENABLED = 3;
  80556. return Gamepad;
  80557. }());
  80558. BABYLON.Gamepad = Gamepad;
  80559. /**
  80560. * Represents a generic gamepad
  80561. */
  80562. var GenericPad = /** @class */ (function (_super) {
  80563. __extends(GenericPad, _super);
  80564. /**
  80565. * Initializes the generic gamepad
  80566. * @param id The id of the generic gamepad
  80567. * @param index The index of the generic gamepad
  80568. * @param browserGamepad The browser gamepad
  80569. */
  80570. function GenericPad(id, index, browserGamepad) {
  80571. var _this = _super.call(this, id, index, browserGamepad) || this;
  80572. /**
  80573. * Observable triggered when a button has been pressed
  80574. */
  80575. _this.onButtonDownObservable = new BABYLON.Observable();
  80576. /**
  80577. * Observable triggered when a button has been released
  80578. */
  80579. _this.onButtonUpObservable = new BABYLON.Observable();
  80580. _this.type = Gamepad.GENERIC;
  80581. _this._buttons = new Array(browserGamepad.buttons.length);
  80582. return _this;
  80583. }
  80584. /**
  80585. * Callback triggered when a button has been pressed
  80586. * @param callback Called when a button has been pressed
  80587. */
  80588. GenericPad.prototype.onbuttondown = function (callback) {
  80589. this._onbuttondown = callback;
  80590. };
  80591. /**
  80592. * Callback triggered when a button has been released
  80593. * @param callback Called when a button has been released
  80594. */
  80595. GenericPad.prototype.onbuttonup = function (callback) {
  80596. this._onbuttonup = callback;
  80597. };
  80598. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  80599. if (newValue !== currentValue) {
  80600. if (newValue === 1) {
  80601. if (this._onbuttondown) {
  80602. this._onbuttondown(buttonIndex);
  80603. }
  80604. this.onButtonDownObservable.notifyObservers(buttonIndex);
  80605. }
  80606. if (newValue === 0) {
  80607. if (this._onbuttonup) {
  80608. this._onbuttonup(buttonIndex);
  80609. }
  80610. this.onButtonUpObservable.notifyObservers(buttonIndex);
  80611. }
  80612. }
  80613. return newValue;
  80614. };
  80615. /**
  80616. * Updates the generic gamepad
  80617. */
  80618. GenericPad.prototype.update = function () {
  80619. _super.prototype.update.call(this);
  80620. for (var index = 0; index < this._buttons.length; index++) {
  80621. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  80622. }
  80623. };
  80624. /**
  80625. * Disposes the generic gamepad
  80626. */
  80627. GenericPad.prototype.dispose = function () {
  80628. _super.prototype.dispose.call(this);
  80629. this.onButtonDownObservable.clear();
  80630. this.onButtonUpObservable.clear();
  80631. };
  80632. return GenericPad;
  80633. }(Gamepad));
  80634. BABYLON.GenericPad = GenericPad;
  80635. })(BABYLON || (BABYLON = {}));
  80636. //# sourceMappingURL=babylon.gamepad.js.map
  80637. var BABYLON;
  80638. (function (BABYLON) {
  80639. /**
  80640. * Defines supported buttons for XBox360 compatible gamepads
  80641. */
  80642. var Xbox360Button;
  80643. (function (Xbox360Button) {
  80644. /** A */
  80645. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  80646. /** B */
  80647. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  80648. /** X */
  80649. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  80650. /** Y */
  80651. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  80652. /** Start */
  80653. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  80654. /** Back */
  80655. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  80656. /** Left button */
  80657. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  80658. /** Right button */
  80659. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  80660. /** Left stick */
  80661. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  80662. /** Right stick */
  80663. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  80664. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  80665. /** Defines values for XBox360 DPad */
  80666. var Xbox360Dpad;
  80667. (function (Xbox360Dpad) {
  80668. /** Up */
  80669. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  80670. /** Down */
  80671. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  80672. /** Left */
  80673. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  80674. /** Right */
  80675. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  80676. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  80677. /**
  80678. * Defines a XBox360 gamepad
  80679. */
  80680. var Xbox360Pad = /** @class */ (function (_super) {
  80681. __extends(Xbox360Pad, _super);
  80682. /**
  80683. * Creates a new XBox360 gamepad object
  80684. * @param id defines the id of this gamepad
  80685. * @param index defines its index
  80686. * @param gamepad defines the internal HTML gamepad object
  80687. * @param xboxOne defines if it is a XBox One gamepad
  80688. */
  80689. function Xbox360Pad(id, index, gamepad, xboxOne) {
  80690. if (xboxOne === void 0) { xboxOne = false; }
  80691. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  80692. _this._leftTrigger = 0;
  80693. _this._rightTrigger = 0;
  80694. /** Observable raised when a button is pressed */
  80695. _this.onButtonDownObservable = new BABYLON.Observable();
  80696. /** Observable raised when a button is released */
  80697. _this.onButtonUpObservable = new BABYLON.Observable();
  80698. /** Observable raised when a pad is pressed */
  80699. _this.onPadDownObservable = new BABYLON.Observable();
  80700. /** Observable raised when a pad is released */
  80701. _this.onPadUpObservable = new BABYLON.Observable();
  80702. _this._buttonA = 0;
  80703. _this._buttonB = 0;
  80704. _this._buttonX = 0;
  80705. _this._buttonY = 0;
  80706. _this._buttonBack = 0;
  80707. _this._buttonStart = 0;
  80708. _this._buttonLB = 0;
  80709. _this._buttonRB = 0;
  80710. _this._buttonLeftStick = 0;
  80711. _this._buttonRightStick = 0;
  80712. _this._dPadUp = 0;
  80713. _this._dPadDown = 0;
  80714. _this._dPadLeft = 0;
  80715. _this._dPadRight = 0;
  80716. _this._isXboxOnePad = false;
  80717. _this.type = BABYLON.Gamepad.XBOX;
  80718. _this._isXboxOnePad = xboxOne;
  80719. return _this;
  80720. }
  80721. /**
  80722. * Defines the callback to call when left trigger is pressed
  80723. * @param callback defines the callback to use
  80724. */
  80725. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  80726. this._onlefttriggerchanged = callback;
  80727. };
  80728. /**
  80729. * Defines the callback to call when right trigger is pressed
  80730. * @param callback defines the callback to use
  80731. */
  80732. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  80733. this._onrighttriggerchanged = callback;
  80734. };
  80735. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  80736. /**
  80737. * Gets the left trigger value
  80738. */
  80739. get: function () {
  80740. return this._leftTrigger;
  80741. },
  80742. /**
  80743. * Sets the left trigger value
  80744. */
  80745. set: function (newValue) {
  80746. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  80747. this._onlefttriggerchanged(newValue);
  80748. }
  80749. this._leftTrigger = newValue;
  80750. },
  80751. enumerable: true,
  80752. configurable: true
  80753. });
  80754. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  80755. /**
  80756. * Gets the right trigger value
  80757. */
  80758. get: function () {
  80759. return this._rightTrigger;
  80760. },
  80761. /**
  80762. * Sets the right trigger value
  80763. */
  80764. set: function (newValue) {
  80765. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  80766. this._onrighttriggerchanged(newValue);
  80767. }
  80768. this._rightTrigger = newValue;
  80769. },
  80770. enumerable: true,
  80771. configurable: true
  80772. });
  80773. /**
  80774. * Defines the callback to call when a button is pressed
  80775. * @param callback defines the callback to use
  80776. */
  80777. Xbox360Pad.prototype.onbuttondown = function (callback) {
  80778. this._onbuttondown = callback;
  80779. };
  80780. /**
  80781. * Defines the callback to call when a button is released
  80782. * @param callback defines the callback to use
  80783. */
  80784. Xbox360Pad.prototype.onbuttonup = function (callback) {
  80785. this._onbuttonup = callback;
  80786. };
  80787. /**
  80788. * Defines the callback to call when a pad is pressed
  80789. * @param callback defines the callback to use
  80790. */
  80791. Xbox360Pad.prototype.ondpaddown = function (callback) {
  80792. this._ondpaddown = callback;
  80793. };
  80794. /**
  80795. * Defines the callback to call when a pad is released
  80796. * @param callback defines the callback to use
  80797. */
  80798. Xbox360Pad.prototype.ondpadup = function (callback) {
  80799. this._ondpadup = callback;
  80800. };
  80801. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  80802. if (newValue !== currentValue) {
  80803. if (newValue === 1) {
  80804. if (this._onbuttondown) {
  80805. this._onbuttondown(buttonType);
  80806. }
  80807. this.onButtonDownObservable.notifyObservers(buttonType);
  80808. }
  80809. if (newValue === 0) {
  80810. if (this._onbuttonup) {
  80811. this._onbuttonup(buttonType);
  80812. }
  80813. this.onButtonUpObservable.notifyObservers(buttonType);
  80814. }
  80815. }
  80816. return newValue;
  80817. };
  80818. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  80819. if (newValue !== currentValue) {
  80820. if (newValue === 1) {
  80821. if (this._ondpaddown) {
  80822. this._ondpaddown(buttonType);
  80823. }
  80824. this.onPadDownObservable.notifyObservers(buttonType);
  80825. }
  80826. if (newValue === 0) {
  80827. if (this._ondpadup) {
  80828. this._ondpadup(buttonType);
  80829. }
  80830. this.onPadUpObservable.notifyObservers(buttonType);
  80831. }
  80832. }
  80833. return newValue;
  80834. };
  80835. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  80836. /**
  80837. * Gets the value of the `A` button
  80838. */
  80839. get: function () {
  80840. return this._buttonA;
  80841. },
  80842. /**
  80843. * Sets the value of the `A` button
  80844. */
  80845. set: function (value) {
  80846. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  80847. },
  80848. enumerable: true,
  80849. configurable: true
  80850. });
  80851. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  80852. /**
  80853. * Gets the value of the `B` button
  80854. */
  80855. get: function () {
  80856. return this._buttonB;
  80857. },
  80858. /**
  80859. * Sets the value of the `B` button
  80860. */
  80861. set: function (value) {
  80862. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  80863. },
  80864. enumerable: true,
  80865. configurable: true
  80866. });
  80867. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  80868. /**
  80869. * Gets the value of the `X` button
  80870. */
  80871. get: function () {
  80872. return this._buttonX;
  80873. },
  80874. /**
  80875. * Sets the value of the `X` button
  80876. */
  80877. set: function (value) {
  80878. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  80879. },
  80880. enumerable: true,
  80881. configurable: true
  80882. });
  80883. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  80884. /**
  80885. * Gets the value of the `Y` button
  80886. */
  80887. get: function () {
  80888. return this._buttonY;
  80889. },
  80890. /**
  80891. * Sets the value of the `Y` button
  80892. */
  80893. set: function (value) {
  80894. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  80895. },
  80896. enumerable: true,
  80897. configurable: true
  80898. });
  80899. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  80900. /**
  80901. * Gets the value of the `Start` button
  80902. */
  80903. get: function () {
  80904. return this._buttonStart;
  80905. },
  80906. /**
  80907. * Sets the value of the `Start` button
  80908. */
  80909. set: function (value) {
  80910. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  80911. },
  80912. enumerable: true,
  80913. configurable: true
  80914. });
  80915. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  80916. /**
  80917. * Gets the value of the `Back` button
  80918. */
  80919. get: function () {
  80920. return this._buttonBack;
  80921. },
  80922. /**
  80923. * Sets the value of the `Back` button
  80924. */
  80925. set: function (value) {
  80926. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  80927. },
  80928. enumerable: true,
  80929. configurable: true
  80930. });
  80931. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  80932. /**
  80933. * Gets the value of the `Left` button
  80934. */
  80935. get: function () {
  80936. return this._buttonLB;
  80937. },
  80938. /**
  80939. * Sets the value of the `Left` button
  80940. */
  80941. set: function (value) {
  80942. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  80943. },
  80944. enumerable: true,
  80945. configurable: true
  80946. });
  80947. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  80948. /**
  80949. * Gets the value of the `Right` button
  80950. */
  80951. get: function () {
  80952. return this._buttonRB;
  80953. },
  80954. /**
  80955. * Sets the value of the `Right` button
  80956. */
  80957. set: function (value) {
  80958. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  80959. },
  80960. enumerable: true,
  80961. configurable: true
  80962. });
  80963. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  80964. /**
  80965. * Gets the value of the Left joystick
  80966. */
  80967. get: function () {
  80968. return this._buttonLeftStick;
  80969. },
  80970. /**
  80971. * Sets the value of the Left joystick
  80972. */
  80973. set: function (value) {
  80974. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  80975. },
  80976. enumerable: true,
  80977. configurable: true
  80978. });
  80979. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  80980. /**
  80981. * Gets the value of the Right joystick
  80982. */
  80983. get: function () {
  80984. return this._buttonRightStick;
  80985. },
  80986. /**
  80987. * Sets the value of the Right joystick
  80988. */
  80989. set: function (value) {
  80990. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  80991. },
  80992. enumerable: true,
  80993. configurable: true
  80994. });
  80995. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  80996. /**
  80997. * Gets the value of D-pad up
  80998. */
  80999. get: function () {
  81000. return this._dPadUp;
  81001. },
  81002. /**
  81003. * Sets the value of D-pad up
  81004. */
  81005. set: function (value) {
  81006. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  81007. },
  81008. enumerable: true,
  81009. configurable: true
  81010. });
  81011. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  81012. /**
  81013. * Gets the value of D-pad down
  81014. */
  81015. get: function () {
  81016. return this._dPadDown;
  81017. },
  81018. /**
  81019. * Sets the value of D-pad down
  81020. */
  81021. set: function (value) {
  81022. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  81023. },
  81024. enumerable: true,
  81025. configurable: true
  81026. });
  81027. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  81028. /**
  81029. * Gets the value of D-pad left
  81030. */
  81031. get: function () {
  81032. return this._dPadLeft;
  81033. },
  81034. /**
  81035. * Sets the value of D-pad left
  81036. */
  81037. set: function (value) {
  81038. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  81039. },
  81040. enumerable: true,
  81041. configurable: true
  81042. });
  81043. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  81044. /**
  81045. * Gets the value of D-pad right
  81046. */
  81047. get: function () {
  81048. return this._dPadRight;
  81049. },
  81050. /**
  81051. * Sets the value of D-pad right
  81052. */
  81053. set: function (value) {
  81054. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  81055. },
  81056. enumerable: true,
  81057. configurable: true
  81058. });
  81059. /**
  81060. * Force the gamepad to synchronize with device values
  81061. */
  81062. Xbox360Pad.prototype.update = function () {
  81063. _super.prototype.update.call(this);
  81064. if (this._isXboxOnePad) {
  81065. this.buttonA = this.browserGamepad.buttons[0].value;
  81066. this.buttonB = this.browserGamepad.buttons[1].value;
  81067. this.buttonX = this.browserGamepad.buttons[2].value;
  81068. this.buttonY = this.browserGamepad.buttons[3].value;
  81069. this.buttonLB = this.browserGamepad.buttons[4].value;
  81070. this.buttonRB = this.browserGamepad.buttons[5].value;
  81071. this.leftTrigger = this.browserGamepad.axes[2];
  81072. this.rightTrigger = this.browserGamepad.axes[5];
  81073. this.buttonBack = this.browserGamepad.buttons[9].value;
  81074. this.buttonStart = this.browserGamepad.buttons[8].value;
  81075. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  81076. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  81077. this.dPadUp = this.browserGamepad.buttons[11].value;
  81078. this.dPadDown = this.browserGamepad.buttons[12].value;
  81079. this.dPadLeft = this.browserGamepad.buttons[13].value;
  81080. this.dPadRight = this.browserGamepad.buttons[14].value;
  81081. }
  81082. else {
  81083. this.buttonA = this.browserGamepad.buttons[0].value;
  81084. this.buttonB = this.browserGamepad.buttons[1].value;
  81085. this.buttonX = this.browserGamepad.buttons[2].value;
  81086. this.buttonY = this.browserGamepad.buttons[3].value;
  81087. this.buttonLB = this.browserGamepad.buttons[4].value;
  81088. this.buttonRB = this.browserGamepad.buttons[5].value;
  81089. this.leftTrigger = this.browserGamepad.buttons[6].value;
  81090. this.rightTrigger = this.browserGamepad.buttons[7].value;
  81091. this.buttonBack = this.browserGamepad.buttons[8].value;
  81092. this.buttonStart = this.browserGamepad.buttons[9].value;
  81093. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  81094. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  81095. this.dPadUp = this.browserGamepad.buttons[12].value;
  81096. this.dPadDown = this.browserGamepad.buttons[13].value;
  81097. this.dPadLeft = this.browserGamepad.buttons[14].value;
  81098. this.dPadRight = this.browserGamepad.buttons[15].value;
  81099. }
  81100. };
  81101. /**
  81102. * Disposes the gamepad
  81103. */
  81104. Xbox360Pad.prototype.dispose = function () {
  81105. _super.prototype.dispose.call(this);
  81106. this.onButtonDownObservable.clear();
  81107. this.onButtonUpObservable.clear();
  81108. this.onPadDownObservable.clear();
  81109. this.onPadUpObservable.clear();
  81110. };
  81111. return Xbox360Pad;
  81112. }(BABYLON.Gamepad));
  81113. BABYLON.Xbox360Pad = Xbox360Pad;
  81114. })(BABYLON || (BABYLON = {}));
  81115. //# sourceMappingURL=babylon.xboxGamepad.js.map
  81116. var BABYLON;
  81117. (function (BABYLON) {
  81118. /**
  81119. * Defines the types of pose enabled controllers that are supported
  81120. */
  81121. var PoseEnabledControllerType;
  81122. (function (PoseEnabledControllerType) {
  81123. /**
  81124. * HTC Vive
  81125. */
  81126. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  81127. /**
  81128. * Oculus Rift
  81129. */
  81130. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  81131. /**
  81132. * Windows mixed reality
  81133. */
  81134. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  81135. /**
  81136. * Samsung gear VR
  81137. */
  81138. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  81139. /**
  81140. * Google Daydream
  81141. */
  81142. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  81143. /**
  81144. * Generic
  81145. */
  81146. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  81147. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  81148. /**
  81149. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  81150. */
  81151. var PoseEnabledControllerHelper = /** @class */ (function () {
  81152. function PoseEnabledControllerHelper() {
  81153. }
  81154. /**
  81155. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  81156. * @param vrGamepad the gamepad to initialized
  81157. * @returns a vr controller of the type the gamepad identified as
  81158. */
  81159. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  81160. // Oculus Touch
  81161. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  81162. return new BABYLON.OculusTouchController(vrGamepad);
  81163. }
  81164. // Windows Mixed Reality controllers
  81165. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  81166. return new BABYLON.WindowsMotionController(vrGamepad);
  81167. }
  81168. // HTC Vive
  81169. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  81170. return new BABYLON.ViveController(vrGamepad);
  81171. }
  81172. // Samsung/Oculus Gear VR or Oculus Go
  81173. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  81174. return new BABYLON.GearVRController(vrGamepad);
  81175. }
  81176. // Google Daydream
  81177. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  81178. return new BABYLON.DaydreamController(vrGamepad);
  81179. }
  81180. // Generic
  81181. else {
  81182. return new BABYLON.GenericController(vrGamepad);
  81183. }
  81184. };
  81185. return PoseEnabledControllerHelper;
  81186. }());
  81187. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  81188. /**
  81189. * Defines the PoseEnabledController object that contains state of a vr capable controller
  81190. */
  81191. var PoseEnabledController = /** @class */ (function (_super) {
  81192. __extends(PoseEnabledController, _super);
  81193. /**
  81194. * Creates a new PoseEnabledController from a gamepad
  81195. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  81196. */
  81197. function PoseEnabledController(browserGamepad) {
  81198. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  81199. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  81200. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  81201. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  81202. /**
  81203. * The device position in babylon space
  81204. */
  81205. _this.devicePosition = BABYLON.Vector3.Zero();
  81206. /**
  81207. * The device rotation in babylon space
  81208. */
  81209. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  81210. /**
  81211. * The scale factor of the device in babylon space
  81212. */
  81213. _this.deviceScaleFactor = 1;
  81214. // Used to convert 6dof controllers to 3dof
  81215. _this._trackPosition = true;
  81216. _this._maxRotationDistFromHeadset = Math.PI / 5;
  81217. _this._draggedRoomRotation = 0;
  81218. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  81219. /**
  81220. * Internal, matrix used to convert room space to babylon space
  81221. * @hidden
  81222. */
  81223. _this._deviceToWorld = BABYLON.Matrix.Identity();
  81224. /**
  81225. * Node to be used when casting a ray from the controller
  81226. * @hidden
  81227. */
  81228. _this._pointingPoseNode = null;
  81229. _this._workingMatrix = BABYLON.Matrix.Identity();
  81230. /**
  81231. * @hidden
  81232. */
  81233. _this._meshAttachedObservable = new BABYLON.Observable();
  81234. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  81235. _this.controllerType = PoseEnabledControllerType.GENERIC;
  81236. _this.position = BABYLON.Vector3.Zero();
  81237. _this.rotationQuaternion = new BABYLON.Quaternion();
  81238. _this._calculatedPosition = BABYLON.Vector3.Zero();
  81239. _this._calculatedRotation = new BABYLON.Quaternion();
  81240. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  81241. return _this;
  81242. }
  81243. /**
  81244. * @hidden
  81245. */
  81246. PoseEnabledController.prototype._disableTrackPosition = function (fixedPosition) {
  81247. if (this._trackPosition) {
  81248. this._calculatedPosition.copyFrom(fixedPosition);
  81249. this._trackPosition = false;
  81250. }
  81251. };
  81252. /**
  81253. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  81254. */
  81255. PoseEnabledController.prototype.update = function () {
  81256. _super.prototype.update.call(this);
  81257. this._updatePoseAndMesh();
  81258. };
  81259. /**
  81260. * Updates only the pose device and mesh without doing any button event checking
  81261. */
  81262. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  81263. var pose = this.browserGamepad.pose;
  81264. this.updateFromDevice(pose);
  81265. if (!this._trackPosition && BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera && BABYLON.Engine.LastCreatedScene.activeCamera.devicePosition) {
  81266. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  81267. camera._computeDevicePosition();
  81268. this._deviceToWorld.setTranslation(camera.devicePosition);
  81269. if (camera.deviceRotationQuaternion) {
  81270. var camera = camera;
  81271. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(BABYLON.Tmp.Vector3[0]);
  81272. // Find the radian distance away that the headset is from the controllers rotation
  81273. var distanceAway = Math.atan2(Math.sin(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation), Math.cos(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation));
  81274. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  81275. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  81276. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  81277. this._draggedRoomRotation += rotationAmount;
  81278. // Rotate controller around headset
  81279. var sin = Math.sin(-rotationAmount);
  81280. var cos = Math.cos(-rotationAmount);
  81281. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  81282. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  81283. }
  81284. }
  81285. }
  81286. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  81287. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  81288. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  81289. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  81290. if (this._mesh) {
  81291. this._mesh.position.copyFrom(this.devicePosition);
  81292. if (this._mesh.rotationQuaternion) {
  81293. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  81294. }
  81295. }
  81296. };
  81297. /**
  81298. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  81299. * @param poseData raw pose fromthe device
  81300. */
  81301. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  81302. if (poseData) {
  81303. this.rawPose = poseData;
  81304. if (poseData.position) {
  81305. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  81306. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  81307. this._deviceRoomPosition.z *= -1;
  81308. }
  81309. if (this._trackPosition) {
  81310. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  81311. }
  81312. this._calculatedPosition.addInPlace(this.position);
  81313. }
  81314. var pose = this.rawPose;
  81315. if (poseData.orientation && pose.orientation) {
  81316. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  81317. if (this._mesh) {
  81318. if (this._mesh.getScene().useRightHandedSystem) {
  81319. this._deviceRoomRotationQuaternion.z *= -1;
  81320. this._deviceRoomRotationQuaternion.w *= -1;
  81321. }
  81322. else {
  81323. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  81324. }
  81325. }
  81326. // if the camera is set, rotate to the camera's rotation
  81327. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  81328. }
  81329. }
  81330. };
  81331. /**
  81332. * Attaches a mesh to the controller
  81333. * @param mesh the mesh to be attached
  81334. */
  81335. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  81336. if (this._mesh) {
  81337. this._mesh.parent = null;
  81338. }
  81339. this._mesh = mesh;
  81340. if (this._poseControlledCamera) {
  81341. this._mesh.parent = this._poseControlledCamera;
  81342. }
  81343. if (!this._mesh.rotationQuaternion) {
  81344. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  81345. }
  81346. // 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
  81347. this._updatePoseAndMesh();
  81348. if (this._pointingPoseNode) {
  81349. var parents = [];
  81350. var obj = this._pointingPoseNode;
  81351. while (obj.parent) {
  81352. parents.push(obj.parent);
  81353. obj = obj.parent;
  81354. }
  81355. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  81356. }
  81357. this._meshAttachedObservable.notifyObservers(mesh);
  81358. };
  81359. /**
  81360. * Attaches the controllers mesh to a camera
  81361. * @param camera the camera the mesh should be attached to
  81362. */
  81363. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  81364. this._poseControlledCamera = camera;
  81365. if (this._mesh) {
  81366. this._mesh.parent = this._poseControlledCamera;
  81367. }
  81368. };
  81369. /**
  81370. * Disposes of the controller
  81371. */
  81372. PoseEnabledController.prototype.dispose = function () {
  81373. if (this._mesh) {
  81374. this._mesh.dispose();
  81375. }
  81376. this._mesh = null;
  81377. _super.prototype.dispose.call(this);
  81378. };
  81379. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  81380. /**
  81381. * The mesh that is attached to the controller
  81382. */
  81383. get: function () {
  81384. return this._mesh;
  81385. },
  81386. enumerable: true,
  81387. configurable: true
  81388. });
  81389. /**
  81390. * Gets the ray of the controller in the direction the controller is pointing
  81391. * @param length the length the resulting ray should be
  81392. * @returns a ray in the direction the controller is pointing
  81393. */
  81394. PoseEnabledController.prototype.getForwardRay = function (length) {
  81395. if (length === void 0) { length = 100; }
  81396. if (!this.mesh) {
  81397. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  81398. }
  81399. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  81400. var origin = m.getTranslation();
  81401. var forward = new BABYLON.Vector3(0, 0, -1);
  81402. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  81403. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  81404. return new BABYLON.Ray(origin, direction, length);
  81405. };
  81406. /**
  81407. * Name of the child mesh that can be used to cast a ray from the controller
  81408. */
  81409. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  81410. return PoseEnabledController;
  81411. }(BABYLON.Gamepad));
  81412. BABYLON.PoseEnabledController = PoseEnabledController;
  81413. })(BABYLON || (BABYLON = {}));
  81414. //# sourceMappingURL=babylon.poseEnabledController.js.map
  81415. var BABYLON;
  81416. (function (BABYLON) {
  81417. /**
  81418. * Defines the WebVRController object that represents controllers tracked in 3D space
  81419. */
  81420. var WebVRController = /** @class */ (function (_super) {
  81421. __extends(WebVRController, _super);
  81422. /**
  81423. * Creates a new WebVRController from a gamepad
  81424. * @param vrGamepad the gamepad that the WebVRController should be created from
  81425. */
  81426. function WebVRController(vrGamepad) {
  81427. var _this = _super.call(this, vrGamepad) || this;
  81428. // Observables
  81429. /**
  81430. * Fired when the trigger state has changed
  81431. */
  81432. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  81433. /**
  81434. * Fired when the main button state has changed
  81435. */
  81436. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  81437. /**
  81438. * Fired when the secondary button state has changed
  81439. */
  81440. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  81441. /**
  81442. * Fired when the pad state has changed
  81443. */
  81444. _this.onPadStateChangedObservable = new BABYLON.Observable();
  81445. /**
  81446. * Fired when controllers stick values have changed
  81447. */
  81448. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  81449. /**
  81450. * X and Y axis corrisponding to the controllers joystick
  81451. */
  81452. _this.pad = { x: 0, y: 0 };
  81453. // avoid GC, store state in a tmp object
  81454. _this._changes = {
  81455. pressChanged: false,
  81456. touchChanged: false,
  81457. valueChanged: false,
  81458. changed: false
  81459. };
  81460. _this._buttons = new Array(vrGamepad.buttons.length);
  81461. _this.hand = vrGamepad.hand;
  81462. return _this;
  81463. }
  81464. /**
  81465. * Fired when a controller button's state has changed
  81466. * @param callback the callback containing the button that was modified
  81467. */
  81468. WebVRController.prototype.onButtonStateChange = function (callback) {
  81469. this._onButtonStateChange = callback;
  81470. };
  81471. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  81472. /**
  81473. * The default controller model for the controller
  81474. */
  81475. get: function () {
  81476. return this._defaultModel;
  81477. },
  81478. enumerable: true,
  81479. configurable: true
  81480. });
  81481. /**
  81482. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  81483. */
  81484. WebVRController.prototype.update = function () {
  81485. _super.prototype.update.call(this);
  81486. for (var index = 0; index < this._buttons.length; index++) {
  81487. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  81488. }
  81489. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  81490. this.pad.x = this.leftStick.x;
  81491. this.pad.y = this.leftStick.y;
  81492. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  81493. }
  81494. };
  81495. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  81496. if (!newState) {
  81497. newState = {
  81498. pressed: false,
  81499. touched: false,
  81500. value: 0
  81501. };
  81502. }
  81503. if (!currentState) {
  81504. this._buttons[buttonIndex] = {
  81505. pressed: newState.pressed,
  81506. touched: newState.touched,
  81507. value: newState.value
  81508. };
  81509. return;
  81510. }
  81511. this._checkChanges(newState, currentState);
  81512. if (this._changes.changed) {
  81513. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  81514. this._handleButtonChange(buttonIndex, newState, this._changes);
  81515. }
  81516. this._buttons[buttonIndex].pressed = newState.pressed;
  81517. this._buttons[buttonIndex].touched = newState.touched;
  81518. // oculus triggers are never 0, thou not touched.
  81519. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  81520. };
  81521. WebVRController.prototype._checkChanges = function (newState, currentState) {
  81522. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  81523. this._changes.touchChanged = newState.touched !== currentState.touched;
  81524. this._changes.valueChanged = newState.value !== currentState.value;
  81525. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  81526. return this._changes;
  81527. };
  81528. /**
  81529. * Disposes of th webVRCOntroller
  81530. */
  81531. WebVRController.prototype.dispose = function () {
  81532. _super.prototype.dispose.call(this);
  81533. this.onTriggerStateChangedObservable.clear();
  81534. this.onMainButtonStateChangedObservable.clear();
  81535. this.onSecondaryButtonStateChangedObservable.clear();
  81536. this.onPadStateChangedObservable.clear();
  81537. this.onPadValuesChangedObservable.clear();
  81538. };
  81539. return WebVRController;
  81540. }(BABYLON.PoseEnabledController));
  81541. BABYLON.WebVRController = WebVRController;
  81542. })(BABYLON || (BABYLON = {}));
  81543. //# sourceMappingURL=babylon.webVRController.js.map
  81544. var BABYLON;
  81545. (function (BABYLON) {
  81546. /**
  81547. * Oculus Touch Controller
  81548. */
  81549. var OculusTouchController = /** @class */ (function (_super) {
  81550. __extends(OculusTouchController, _super);
  81551. /**
  81552. * Creates a new OculusTouchController from a gamepad
  81553. * @param vrGamepad the gamepad that the controller should be created from
  81554. */
  81555. function OculusTouchController(vrGamepad) {
  81556. var _this = _super.call(this, vrGamepad) || this;
  81557. /**
  81558. * Fired when the secondary trigger on this controller is modified
  81559. */
  81560. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  81561. /**
  81562. * Fired when the thumb rest on this controller is modified
  81563. */
  81564. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  81565. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  81566. return _this;
  81567. }
  81568. /**
  81569. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  81570. * @param scene scene in which to add meshes
  81571. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  81572. */
  81573. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  81574. var _this = this;
  81575. var meshName;
  81576. // Hand
  81577. if (this.hand === 'left') {
  81578. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  81579. }
  81580. else { // Right is the default if no hand is specified
  81581. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  81582. }
  81583. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  81584. /*
  81585. Parent Mesh name: oculus_touch_left
  81586. - body
  81587. - trigger
  81588. - thumbstick
  81589. - grip
  81590. - button_y
  81591. - button_x
  81592. - button_enter
  81593. */
  81594. _this._defaultModel = newMeshes[1];
  81595. _this.attachToMesh(_this._defaultModel);
  81596. if (meshLoaded) {
  81597. meshLoaded(_this._defaultModel);
  81598. }
  81599. });
  81600. };
  81601. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  81602. /**
  81603. * Fired when the A button on this controller is modified
  81604. */
  81605. get: function () {
  81606. if (this.hand === 'right') {
  81607. return this.onMainButtonStateChangedObservable;
  81608. }
  81609. else {
  81610. throw new Error('No A button on left hand');
  81611. }
  81612. },
  81613. enumerable: true,
  81614. configurable: true
  81615. });
  81616. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  81617. /**
  81618. * Fired when the B button on this controller is modified
  81619. */
  81620. get: function () {
  81621. if (this.hand === 'right') {
  81622. return this.onSecondaryButtonStateChangedObservable;
  81623. }
  81624. else {
  81625. throw new Error('No B button on left hand');
  81626. }
  81627. },
  81628. enumerable: true,
  81629. configurable: true
  81630. });
  81631. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  81632. /**
  81633. * Fired when the X button on this controller is modified
  81634. */
  81635. get: function () {
  81636. if (this.hand === 'left') {
  81637. return this.onMainButtonStateChangedObservable;
  81638. }
  81639. else {
  81640. throw new Error('No X button on right hand');
  81641. }
  81642. },
  81643. enumerable: true,
  81644. configurable: true
  81645. });
  81646. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  81647. /**
  81648. * Fired when the Y button on this controller is modified
  81649. */
  81650. get: function () {
  81651. if (this.hand === 'left') {
  81652. return this.onSecondaryButtonStateChangedObservable;
  81653. }
  81654. else {
  81655. throw new Error('No Y button on right hand');
  81656. }
  81657. },
  81658. enumerable: true,
  81659. configurable: true
  81660. });
  81661. /**
  81662. * Called once for each button that changed state since the last frame
  81663. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  81664. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  81665. * 2) secondary trigger (same)
  81666. * 3) A (right) X (left), touch, pressed = value
  81667. * 4) B / Y
  81668. * 5) thumb rest
  81669. * @param buttonIdx Which button index changed
  81670. * @param state New state of the button
  81671. * @param changes Which properties on the state changed since last frame
  81672. */
  81673. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  81674. var notifyObject = state; //{ state: state, changes: changes };
  81675. var triggerDirection = this.hand === 'right' ? -1 : 1;
  81676. switch (buttonIdx) {
  81677. case 0:
  81678. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  81679. return;
  81680. case 1: // index trigger
  81681. if (this._defaultModel) {
  81682. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  81683. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  81684. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  81685. }
  81686. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  81687. return;
  81688. case 2: // secondary trigger
  81689. if (this._defaultModel) {
  81690. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  81691. }
  81692. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  81693. return;
  81694. case 3:
  81695. if (this._defaultModel) {
  81696. if (notifyObject.pressed) {
  81697. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  81698. }
  81699. else {
  81700. (this._defaultModel.getChildren()[1]).position.y = 0;
  81701. }
  81702. }
  81703. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  81704. return;
  81705. case 4:
  81706. if (this._defaultModel) {
  81707. if (notifyObject.pressed) {
  81708. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  81709. }
  81710. else {
  81711. (this._defaultModel.getChildren()[2]).position.y = 0;
  81712. }
  81713. }
  81714. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  81715. return;
  81716. case 5:
  81717. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  81718. return;
  81719. }
  81720. };
  81721. /**
  81722. * Base Url for the controller model.
  81723. */
  81724. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  81725. /**
  81726. * File name for the left controller model.
  81727. */
  81728. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  81729. /**
  81730. * File name for the right controller model.
  81731. */
  81732. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  81733. return OculusTouchController;
  81734. }(BABYLON.WebVRController));
  81735. BABYLON.OculusTouchController = OculusTouchController;
  81736. })(BABYLON || (BABYLON = {}));
  81737. //# sourceMappingURL=babylon.oculusTouchController.js.map
  81738. var BABYLON;
  81739. (function (BABYLON) {
  81740. /**
  81741. * Vive Controller
  81742. */
  81743. var ViveController = /** @class */ (function (_super) {
  81744. __extends(ViveController, _super);
  81745. /**
  81746. * Creates a new ViveController from a gamepad
  81747. * @param vrGamepad the gamepad that the controller should be created from
  81748. */
  81749. function ViveController(vrGamepad) {
  81750. var _this = _super.call(this, vrGamepad) || this;
  81751. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  81752. _this._invertLeftStickY = true;
  81753. return _this;
  81754. }
  81755. /**
  81756. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  81757. * @param scene scene in which to add meshes
  81758. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  81759. */
  81760. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  81761. var _this = this;
  81762. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  81763. /*
  81764. Parent Mesh name: ViveWand
  81765. - body
  81766. - r_gripper
  81767. - l_gripper
  81768. - menu_button
  81769. - system_button
  81770. - trackpad
  81771. - trigger
  81772. - LED
  81773. */
  81774. _this._defaultModel = newMeshes[1];
  81775. _this.attachToMesh(_this._defaultModel);
  81776. if (meshLoaded) {
  81777. meshLoaded(_this._defaultModel);
  81778. }
  81779. });
  81780. };
  81781. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  81782. /**
  81783. * Fired when the left button on this controller is modified
  81784. */
  81785. get: function () {
  81786. return this.onMainButtonStateChangedObservable;
  81787. },
  81788. enumerable: true,
  81789. configurable: true
  81790. });
  81791. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  81792. /**
  81793. * Fired when the right button on this controller is modified
  81794. */
  81795. get: function () {
  81796. return this.onMainButtonStateChangedObservable;
  81797. },
  81798. enumerable: true,
  81799. configurable: true
  81800. });
  81801. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  81802. /**
  81803. * Fired when the menu button on this controller is modified
  81804. */
  81805. get: function () {
  81806. return this.onSecondaryButtonStateChangedObservable;
  81807. },
  81808. enumerable: true,
  81809. configurable: true
  81810. });
  81811. /**
  81812. * Called once for each button that changed state since the last frame
  81813. * Vive mapping:
  81814. * 0: touchpad
  81815. * 1: trigger
  81816. * 2: left AND right buttons
  81817. * 3: menu button
  81818. * @param buttonIdx Which button index changed
  81819. * @param state New state of the button
  81820. * @param changes Which properties on the state changed since last frame
  81821. */
  81822. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  81823. var notifyObject = state; //{ state: state, changes: changes };
  81824. switch (buttonIdx) {
  81825. case 0:
  81826. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  81827. return;
  81828. case 1: // index trigger
  81829. if (this._defaultModel) {
  81830. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  81831. }
  81832. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  81833. return;
  81834. case 2: // left AND right button
  81835. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  81836. return;
  81837. case 3:
  81838. if (this._defaultModel) {
  81839. if (notifyObject.pressed) {
  81840. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  81841. }
  81842. else {
  81843. (this._defaultModel.getChildren()[2]).position.y = 0;
  81844. }
  81845. }
  81846. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  81847. return;
  81848. }
  81849. };
  81850. /**
  81851. * Base Url for the controller model.
  81852. */
  81853. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  81854. /**
  81855. * File name for the controller model.
  81856. */
  81857. ViveController.MODEL_FILENAME = 'wand.babylon';
  81858. return ViveController;
  81859. }(BABYLON.WebVRController));
  81860. BABYLON.ViveController = ViveController;
  81861. })(BABYLON || (BABYLON = {}));
  81862. //# sourceMappingURL=babylon.viveController.js.map
  81863. var BABYLON;
  81864. (function (BABYLON) {
  81865. /**
  81866. * Generic Controller
  81867. */
  81868. var GenericController = /** @class */ (function (_super) {
  81869. __extends(GenericController, _super);
  81870. /**
  81871. * Creates a new GenericController from a gamepad
  81872. * @param vrGamepad the gamepad that the controller should be created from
  81873. */
  81874. function GenericController(vrGamepad) {
  81875. return _super.call(this, vrGamepad) || this;
  81876. }
  81877. /**
  81878. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  81879. * @param scene scene in which to add meshes
  81880. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  81881. */
  81882. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  81883. var _this = this;
  81884. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  81885. _this._defaultModel = newMeshes[1];
  81886. _this.attachToMesh(_this._defaultModel);
  81887. if (meshLoaded) {
  81888. meshLoaded(_this._defaultModel);
  81889. }
  81890. });
  81891. };
  81892. /**
  81893. * Called once for each button that changed state since the last frame
  81894. * @param buttonIdx Which button index changed
  81895. * @param state New state of the button
  81896. * @param changes Which properties on the state changed since last frame
  81897. */
  81898. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  81899. console.log("Button id: " + buttonIdx + "state: ");
  81900. console.dir(state);
  81901. };
  81902. /**
  81903. * Base Url for the controller model.
  81904. */
  81905. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  81906. /**
  81907. * File name for the controller model.
  81908. */
  81909. GenericController.MODEL_FILENAME = 'generic.babylon';
  81910. return GenericController;
  81911. }(BABYLON.WebVRController));
  81912. BABYLON.GenericController = GenericController;
  81913. })(BABYLON || (BABYLON = {}));
  81914. //# sourceMappingURL=babylon.genericController.js.map
  81915. var BABYLON;
  81916. (function (BABYLON) {
  81917. /**
  81918. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  81919. */
  81920. var LoadedMeshInfo = /** @class */ (function () {
  81921. function LoadedMeshInfo() {
  81922. /**
  81923. * Map of the button meshes contained in the controller
  81924. */
  81925. this.buttonMeshes = {};
  81926. /**
  81927. * Map of the axis meshes contained in the controller
  81928. */
  81929. this.axisMeshes = {};
  81930. }
  81931. return LoadedMeshInfo;
  81932. }());
  81933. /**
  81934. * Defines the WindowsMotionController object that the state of the windows motion controller
  81935. */
  81936. var WindowsMotionController = /** @class */ (function (_super) {
  81937. __extends(WindowsMotionController, _super);
  81938. /**
  81939. * Creates a new WindowsMotionController from a gamepad
  81940. * @param vrGamepad the gamepad that the controller should be created from
  81941. */
  81942. function WindowsMotionController(vrGamepad) {
  81943. var _this = _super.call(this, vrGamepad) || this;
  81944. _this._mapping = {
  81945. // Semantic button names
  81946. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  81947. // A mapping of the button name to glTF model node name
  81948. // that should be transformed by button value.
  81949. buttonMeshNames: {
  81950. 'trigger': 'SELECT',
  81951. 'menu': 'MENU',
  81952. 'grip': 'GRASP',
  81953. 'thumbstick': 'THUMBSTICK_PRESS',
  81954. 'trackpad': 'TOUCHPAD_PRESS'
  81955. },
  81956. // This mapping is used to translate from the Motion Controller to Babylon semantics
  81957. buttonObservableNames: {
  81958. 'trigger': 'onTriggerStateChangedObservable',
  81959. 'menu': 'onSecondaryButtonStateChangedObservable',
  81960. 'grip': 'onMainButtonStateChangedObservable',
  81961. 'thumbstick': 'onPadStateChangedObservable',
  81962. 'trackpad': 'onTrackpadChangedObservable'
  81963. },
  81964. // A mapping of the axis name to glTF model node name
  81965. // that should be transformed by axis value.
  81966. // This array mirrors the browserGamepad.axes array, such that
  81967. // the mesh corresponding to axis 0 is in this array index 0.
  81968. axisMeshNames: [
  81969. 'THUMBSTICK_X',
  81970. 'THUMBSTICK_Y',
  81971. 'TOUCHPAD_TOUCH_X',
  81972. 'TOUCHPAD_TOUCH_Y'
  81973. ],
  81974. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  81975. };
  81976. /**
  81977. * Fired when the trackpad on this controller is clicked
  81978. */
  81979. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  81980. /**
  81981. * Fired when the trackpad on this controller is modified
  81982. */
  81983. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  81984. /**
  81985. * The current x and y values of this controller's trackpad
  81986. */
  81987. _this.trackpad = { x: 0, y: 0 };
  81988. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  81989. _this._loadedMeshInfo = null;
  81990. return _this;
  81991. }
  81992. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  81993. /**
  81994. * Fired when the trigger on this controller is modified
  81995. */
  81996. get: function () {
  81997. return this.onTriggerStateChangedObservable;
  81998. },
  81999. enumerable: true,
  82000. configurable: true
  82001. });
  82002. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  82003. /**
  82004. * Fired when the menu button on this controller is modified
  82005. */
  82006. get: function () {
  82007. return this.onSecondaryButtonStateChangedObservable;
  82008. },
  82009. enumerable: true,
  82010. configurable: true
  82011. });
  82012. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  82013. /**
  82014. * Fired when the grip button on this controller is modified
  82015. */
  82016. get: function () {
  82017. return this.onMainButtonStateChangedObservable;
  82018. },
  82019. enumerable: true,
  82020. configurable: true
  82021. });
  82022. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  82023. /**
  82024. * Fired when the thumbstick button on this controller is modified
  82025. */
  82026. get: function () {
  82027. return this.onPadStateChangedObservable;
  82028. },
  82029. enumerable: true,
  82030. configurable: true
  82031. });
  82032. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  82033. /**
  82034. * Fired when the touchpad button on this controller is modified
  82035. */
  82036. get: function () {
  82037. return this.onTrackpadChangedObservable;
  82038. },
  82039. enumerable: true,
  82040. configurable: true
  82041. });
  82042. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  82043. /**
  82044. * Fired when the touchpad values on this controller are modified
  82045. */
  82046. get: function () {
  82047. return this.onTrackpadValuesChangedObservable;
  82048. },
  82049. enumerable: true,
  82050. configurable: true
  82051. });
  82052. WindowsMotionController.prototype._updateTrackpad = function () {
  82053. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  82054. this.trackpad.x = this.browserGamepad["axes"][2];
  82055. this.trackpad.y = this.browserGamepad["axes"][3];
  82056. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  82057. }
  82058. };
  82059. /**
  82060. * Called once per frame by the engine.
  82061. */
  82062. WindowsMotionController.prototype.update = function () {
  82063. _super.prototype.update.call(this);
  82064. if (this.browserGamepad.axes) {
  82065. this._updateTrackpad();
  82066. // Only need to animate axes if there is a loaded mesh
  82067. if (this._loadedMeshInfo) {
  82068. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  82069. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  82070. }
  82071. }
  82072. }
  82073. };
  82074. /**
  82075. * Called once for each button that changed state since the last frame
  82076. * @param buttonIdx Which button index changed
  82077. * @param state New state of the button
  82078. * @param changes Which properties on the state changed since last frame
  82079. */
  82080. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  82081. var buttonName = this._mapping.buttons[buttonIdx];
  82082. if (!buttonName) {
  82083. return;
  82084. }
  82085. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  82086. this._updateTrackpad();
  82087. // Only emit events for buttons that we know how to map from index to name
  82088. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  82089. if (observable) {
  82090. observable.notifyObservers(state);
  82091. }
  82092. this._lerpButtonTransform(buttonName, state.value);
  82093. };
  82094. /**
  82095. * Moves the buttons on the controller mesh based on their current state
  82096. * @param buttonName the name of the button to move
  82097. * @param buttonValue the value of the button which determines the buttons new position
  82098. */
  82099. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  82100. // If there is no loaded mesh, there is nothing to transform.
  82101. if (!this._loadedMeshInfo) {
  82102. return;
  82103. }
  82104. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  82105. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  82106. return;
  82107. }
  82108. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  82109. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  82110. };
  82111. /**
  82112. * Moves the axis on the controller mesh based on its current state
  82113. * @param axis the index of the axis
  82114. * @param axisValue the value of the axis which determines the meshes new position
  82115. * @hidden
  82116. */
  82117. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  82118. if (!this._loadedMeshInfo) {
  82119. return;
  82120. }
  82121. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  82122. if (!meshInfo) {
  82123. return;
  82124. }
  82125. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  82126. return;
  82127. }
  82128. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  82129. var lerpValue = axisValue * 0.5 + 0.5;
  82130. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  82131. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  82132. };
  82133. /**
  82134. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  82135. * @param scene scene in which to add meshes
  82136. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  82137. */
  82138. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  82139. var _this = this;
  82140. if (forceDefault === void 0) { forceDefault = false; }
  82141. var path;
  82142. var filename;
  82143. // Checking if GLB loader is present
  82144. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  82145. // Determine the device specific folder based on the ID suffix
  82146. var device = 'default';
  82147. if (this.id && !forceDefault) {
  82148. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  82149. device = ((match && match[0]) || device);
  82150. }
  82151. // Hand
  82152. if (this.hand === 'left') {
  82153. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  82154. }
  82155. else { // Right is the default if no hand is specified
  82156. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  82157. }
  82158. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  82159. }
  82160. else {
  82161. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  82162. path = BABYLON.GenericController.MODEL_BASE_URL;
  82163. filename = BABYLON.GenericController.MODEL_FILENAME;
  82164. }
  82165. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  82166. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  82167. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  82168. if (!_this._loadedMeshInfo) {
  82169. return;
  82170. }
  82171. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  82172. _this.attachToMesh(_this._defaultModel);
  82173. if (meshLoaded) {
  82174. meshLoaded(_this._defaultModel);
  82175. }
  82176. }, null, function (scene, message) {
  82177. BABYLON.Tools.Log(message);
  82178. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  82179. if (!forceDefault) {
  82180. _this.initControllerMesh(scene, meshLoaded, true);
  82181. }
  82182. });
  82183. };
  82184. /**
  82185. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  82186. * can be transformed by button presses and axes values, based on this._mapping.
  82187. *
  82188. * @param scene scene in which the meshes exist
  82189. * @param meshes list of meshes that make up the controller model to process
  82190. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  82191. */
  82192. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  82193. var loadedMeshInfo = null;
  82194. // Create a new mesh to contain the glTF hierarchy
  82195. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  82196. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  82197. var childMesh = null;
  82198. for (var i = 0; i < meshes.length; i++) {
  82199. var mesh = meshes[i];
  82200. if (!mesh.parent) {
  82201. // Exclude controller meshes from picking results
  82202. mesh.isPickable = false;
  82203. // Handle root node, attach to the new parentMesh
  82204. childMesh = mesh;
  82205. break;
  82206. }
  82207. }
  82208. if (childMesh) {
  82209. childMesh.setParent(parentMesh);
  82210. // Create our mesh info. Note that this method will always return non-null.
  82211. loadedMeshInfo = this.createMeshInfo(parentMesh);
  82212. }
  82213. else {
  82214. BABYLON.Tools.Warn('Could not find root node in model file.');
  82215. }
  82216. return loadedMeshInfo;
  82217. };
  82218. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  82219. var loadedMeshInfo = new LoadedMeshInfo();
  82220. var i;
  82221. loadedMeshInfo.rootNode = rootNode;
  82222. // Reset the caches
  82223. loadedMeshInfo.buttonMeshes = {};
  82224. loadedMeshInfo.axisMeshes = {};
  82225. // Button Meshes
  82226. for (i = 0; i < this._mapping.buttons.length; i++) {
  82227. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  82228. if (!buttonMeshName) {
  82229. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  82230. continue;
  82231. }
  82232. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  82233. if (!buttonMesh) {
  82234. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  82235. continue;
  82236. }
  82237. var buttonMeshInfo = {
  82238. index: i,
  82239. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  82240. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  82241. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  82242. };
  82243. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  82244. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  82245. }
  82246. else {
  82247. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  82248. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  82249. '(VALUE: ' + !!buttonMeshInfo.value +
  82250. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  82251. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  82252. ')');
  82253. }
  82254. }
  82255. // Axis Meshes
  82256. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  82257. var axisMeshName = this._mapping.axisMeshNames[i];
  82258. if (!axisMeshName) {
  82259. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  82260. continue;
  82261. }
  82262. var axisMesh = getChildByName(rootNode, axisMeshName);
  82263. if (!axisMesh) {
  82264. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  82265. continue;
  82266. }
  82267. var axisMeshInfo = {
  82268. index: i,
  82269. value: getImmediateChildByName(axisMesh, 'VALUE'),
  82270. min: getImmediateChildByName(axisMesh, 'MIN'),
  82271. max: getImmediateChildByName(axisMesh, 'MAX')
  82272. };
  82273. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  82274. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  82275. }
  82276. else {
  82277. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  82278. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  82279. '(VALUE: ' + !!axisMeshInfo.value +
  82280. ', MIN: ' + !!axisMeshInfo.min +
  82281. ', MAX:' + !!axisMeshInfo.max +
  82282. ')');
  82283. }
  82284. }
  82285. // Pointing Ray
  82286. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  82287. if (!loadedMeshInfo.pointingPoseNode) {
  82288. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  82289. }
  82290. else {
  82291. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  82292. }
  82293. return loadedMeshInfo;
  82294. // Look through all children recursively. This will return null if no mesh exists with the given name.
  82295. function getChildByName(node, name) {
  82296. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  82297. }
  82298. // Look through only immediate children. This will return null if no mesh exists with the given name.
  82299. function getImmediateChildByName(node, name) {
  82300. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  82301. }
  82302. };
  82303. /**
  82304. * Gets the ray of the controller in the direction the controller is pointing
  82305. * @param length the length the resulting ray should be
  82306. * @returns a ray in the direction the controller is pointing
  82307. */
  82308. WindowsMotionController.prototype.getForwardRay = function (length) {
  82309. if (length === void 0) { length = 100; }
  82310. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  82311. return _super.prototype.getForwardRay.call(this, length);
  82312. }
  82313. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  82314. var origin = m.getTranslation();
  82315. var forward = new BABYLON.Vector3(0, 0, -1);
  82316. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  82317. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  82318. return new BABYLON.Ray(origin, direction, length);
  82319. };
  82320. /**
  82321. * Disposes of the controller
  82322. */
  82323. WindowsMotionController.prototype.dispose = function () {
  82324. _super.prototype.dispose.call(this);
  82325. this.onTrackpadChangedObservable.clear();
  82326. };
  82327. /**
  82328. * The base url used to load the left and right controller models
  82329. */
  82330. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  82331. /**
  82332. * The name of the left controller model file
  82333. */
  82334. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  82335. /**
  82336. * The name of the right controller model file
  82337. */
  82338. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  82339. /**
  82340. * The controller name prefix for this controller type
  82341. */
  82342. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  82343. /**
  82344. * The controller id pattern for this controller type
  82345. */
  82346. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  82347. return WindowsMotionController;
  82348. }(BABYLON.WebVRController));
  82349. BABYLON.WindowsMotionController = WindowsMotionController;
  82350. })(BABYLON || (BABYLON = {}));
  82351. //# sourceMappingURL=babylon.windowsMotionController.js.map
  82352. var BABYLON;
  82353. (function (BABYLON) {
  82354. /**
  82355. * Gear VR Controller
  82356. */
  82357. var GearVRController = /** @class */ (function (_super) {
  82358. __extends(GearVRController, _super);
  82359. /**
  82360. * Creates a new GearVRController from a gamepad
  82361. * @param vrGamepad the gamepad that the controller should be created from
  82362. */
  82363. function GearVRController(vrGamepad) {
  82364. var _this = _super.call(this, vrGamepad) || this;
  82365. _this._buttonIndexToObservableNameMap = [
  82366. 'onTrackpadChangedObservable',
  82367. 'onTriggerStateChangedObservable' // Trigger
  82368. ];
  82369. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  82370. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  82371. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  82372. _this._disableTrackPosition(_this._calculatedPosition);
  82373. return _this;
  82374. }
  82375. /**
  82376. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  82377. * @param scene scene in which to add meshes
  82378. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  82379. */
  82380. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  82381. var _this = this;
  82382. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  82383. // Offset the controller so it will rotate around the users wrist
  82384. var mesh = new BABYLON.Mesh("", scene);
  82385. newMeshes[1].parent = mesh;
  82386. newMeshes[1].position.z = -0.15;
  82387. _this._defaultModel = mesh;
  82388. _this.attachToMesh(_this._defaultModel);
  82389. if (meshLoaded) {
  82390. meshLoaded(_this._defaultModel);
  82391. }
  82392. });
  82393. };
  82394. /**
  82395. * Called once for each button that changed state since the last frame
  82396. * @param buttonIdx Which button index changed
  82397. * @param state New state of the button
  82398. * @param changes Which properties on the state changed since last frame
  82399. */
  82400. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  82401. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  82402. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  82403. // Only emit events for buttons that we know how to map from index to observable
  82404. var observable = this[observableName];
  82405. if (observable) {
  82406. observable.notifyObservers(state);
  82407. }
  82408. }
  82409. };
  82410. /**
  82411. * Base Url for the controller model.
  82412. */
  82413. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  82414. /**
  82415. * File name for the controller model.
  82416. */
  82417. GearVRController.MODEL_FILENAME = 'generic.babylon';
  82418. /**
  82419. * Gamepad Id prefix used to identify this controller.
  82420. */
  82421. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  82422. return GearVRController;
  82423. }(BABYLON.WebVRController));
  82424. BABYLON.GearVRController = GearVRController;
  82425. })(BABYLON || (BABYLON = {}));
  82426. //# sourceMappingURL=babylon.gearVRController.js.map
  82427. var BABYLON;
  82428. (function (BABYLON) {
  82429. /**
  82430. * Google Daydream controller
  82431. */
  82432. var DaydreamController = /** @class */ (function (_super) {
  82433. __extends(DaydreamController, _super);
  82434. /**
  82435. * Creates a new DaydreamController from a gamepad
  82436. * @param vrGamepad the gamepad that the controller should be created from
  82437. */
  82438. function DaydreamController(vrGamepad) {
  82439. var _this = _super.call(this, vrGamepad) || this;
  82440. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  82441. return _this;
  82442. }
  82443. /**
  82444. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  82445. * @param scene scene in which to add meshes
  82446. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  82447. */
  82448. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  82449. var _this = this;
  82450. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  82451. _this._defaultModel = newMeshes[1];
  82452. _this.attachToMesh(_this._defaultModel);
  82453. if (meshLoaded) {
  82454. meshLoaded(_this._defaultModel);
  82455. }
  82456. });
  82457. };
  82458. /**
  82459. * Called once for each button that changed state since the last frame
  82460. * @param buttonIdx Which button index changed
  82461. * @param state New state of the button
  82462. * @param changes Which properties on the state changed since last frame
  82463. */
  82464. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  82465. // Daydream controller only has 1 GamepadButton (on the trackpad).
  82466. if (buttonIdx === 0) {
  82467. var observable = this.onTriggerStateChangedObservable;
  82468. if (observable) {
  82469. observable.notifyObservers(state);
  82470. }
  82471. }
  82472. else {
  82473. // If the app or home buttons are ever made available
  82474. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  82475. }
  82476. };
  82477. /**
  82478. * Base Url for the controller model.
  82479. */
  82480. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  82481. /**
  82482. * File name for the controller model.
  82483. */
  82484. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  82485. /**
  82486. * Gamepad Id prefix used to identify Daydream Controller.
  82487. */
  82488. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  82489. return DaydreamController;
  82490. }(BABYLON.WebVRController));
  82491. BABYLON.DaydreamController = DaydreamController;
  82492. })(BABYLON || (BABYLON = {}));
  82493. //# sourceMappingURL=babylon.daydreamController.js.map
  82494. var BABYLON;
  82495. (function (BABYLON) {
  82496. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  82497. get: function () {
  82498. if (!this._gamepadManager) {
  82499. this._gamepadManager = new BABYLON.GamepadManager(this);
  82500. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  82501. if (!component) {
  82502. component = new GamepadSystemSceneComponent(this);
  82503. this._addComponent(component);
  82504. }
  82505. }
  82506. return this._gamepadManager;
  82507. },
  82508. enumerable: true,
  82509. configurable: true
  82510. });
  82511. /**
  82512. * Adds a gamepad to the free camera inputs manager
  82513. */
  82514. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  82515. this.add(new BABYLON.FreeCameraGamepadInput());
  82516. return this;
  82517. };
  82518. /**
  82519. * Adds a gamepad to the arc rotate camera inputs manager
  82520. */
  82521. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  82522. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  82523. return this;
  82524. };
  82525. /**
  82526. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  82527. */
  82528. var GamepadSystemSceneComponent = /** @class */ (function () {
  82529. /**
  82530. * Creates a new instance of the component for the given scene
  82531. * @param scene Defines the scene to register the component in
  82532. */
  82533. function GamepadSystemSceneComponent(scene) {
  82534. /**
  82535. * The component name helpfull to identify the component in the list of scene components.
  82536. */
  82537. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  82538. this.scene = scene;
  82539. }
  82540. /**
  82541. * Registers the component in a given scene
  82542. */
  82543. GamepadSystemSceneComponent.prototype.register = function () {
  82544. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  82545. };
  82546. /**
  82547. * Rebuilds the elements related to this component in case of
  82548. * context lost for instance.
  82549. */
  82550. GamepadSystemSceneComponent.prototype.rebuild = function () {
  82551. // Nothing to do for gamepads
  82552. };
  82553. /**
  82554. * Disposes the component and the associated ressources
  82555. */
  82556. GamepadSystemSceneComponent.prototype.dispose = function () {
  82557. var gamepadManager = this.scene._gamepadManager;
  82558. if (gamepadManager) {
  82559. gamepadManager.dispose();
  82560. this.scene._gamepadManager = null;
  82561. }
  82562. };
  82563. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  82564. var gamepadManager = this.scene._gamepadManager;
  82565. if (gamepadManager && gamepadManager._isMonitoring) {
  82566. gamepadManager._checkGamepadsStatus();
  82567. }
  82568. };
  82569. return GamepadSystemSceneComponent;
  82570. }());
  82571. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  82572. })(BABYLON || (BABYLON = {}));
  82573. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  82574. var BABYLON;
  82575. (function (BABYLON) {
  82576. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  82577. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  82578. });
  82579. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  82580. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  82581. });
  82582. /**
  82583. * A follow camera takes a mesh as a target and follows it as it moves. Both a free camera version followCamera and
  82584. * an arc rotate version arcFollowCamera are available.
  82585. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  82586. */
  82587. var FollowCamera = /** @class */ (function (_super) {
  82588. __extends(FollowCamera, _super);
  82589. /**
  82590. * Instantiates the follow camera.
  82591. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  82592. * @param name Define the name of the camera in the scene
  82593. * @param position Define the position of the camera
  82594. * @param scene Define the scene the camera belong to
  82595. * @param lockedTarget Define the target of the camera
  82596. */
  82597. function FollowCamera(name, position, scene, lockedTarget) {
  82598. if (lockedTarget === void 0) { lockedTarget = null; }
  82599. var _this = _super.call(this, name, position, scene) || this;
  82600. /**
  82601. * Distance the follow camera should follow an object at
  82602. */
  82603. _this.radius = 12;
  82604. /**
  82605. * Define a rotation offset between the camera and the object it follows
  82606. */
  82607. _this.rotationOffset = 0;
  82608. /**
  82609. * Define a height offset between the camera and the object it follows.
  82610. * It can help following an object from the top (like a car chaing a plane)
  82611. */
  82612. _this.heightOffset = 4;
  82613. /**
  82614. * Define how fast the camera can accelerate to follow it s target.
  82615. */
  82616. _this.cameraAcceleration = 0.05;
  82617. /**
  82618. * Define the speed limit of the camera following an object.
  82619. */
  82620. _this.maxCameraSpeed = 20;
  82621. _this.lockedTarget = lockedTarget;
  82622. return _this;
  82623. }
  82624. FollowCamera.prototype._follow = function (cameraTarget) {
  82625. if (!cameraTarget) {
  82626. return;
  82627. }
  82628. var yRotation;
  82629. if (cameraTarget.rotationQuaternion) {
  82630. var rotMatrix = new BABYLON.Matrix();
  82631. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  82632. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  82633. }
  82634. else {
  82635. yRotation = cameraTarget.rotation.y;
  82636. }
  82637. var radians = BABYLON.Tools.ToRadians(this.rotationOffset) + yRotation;
  82638. var targetPosition = cameraTarget.getAbsolutePosition();
  82639. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  82640. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  82641. var dx = targetX - this.position.x;
  82642. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  82643. var dz = (targetZ) - this.position.z;
  82644. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  82645. var vy = dy * this.cameraAcceleration;
  82646. var vz = dz * this.cameraAcceleration * 2;
  82647. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  82648. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  82649. }
  82650. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  82651. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  82652. }
  82653. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  82654. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  82655. }
  82656. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  82657. this.setTarget(targetPosition);
  82658. };
  82659. /** @hidden */
  82660. FollowCamera.prototype._checkInputs = function () {
  82661. _super.prototype._checkInputs.call(this);
  82662. if (this.lockedTarget) {
  82663. this._follow(this.lockedTarget);
  82664. }
  82665. };
  82666. /**
  82667. * Gets the camera class name.
  82668. * @returns the class name
  82669. */
  82670. FollowCamera.prototype.getClassName = function () {
  82671. return "FollowCamera";
  82672. };
  82673. __decorate([
  82674. BABYLON.serialize()
  82675. ], FollowCamera.prototype, "radius", void 0);
  82676. __decorate([
  82677. BABYLON.serialize()
  82678. ], FollowCamera.prototype, "rotationOffset", void 0);
  82679. __decorate([
  82680. BABYLON.serialize()
  82681. ], FollowCamera.prototype, "heightOffset", void 0);
  82682. __decorate([
  82683. BABYLON.serialize()
  82684. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  82685. __decorate([
  82686. BABYLON.serialize()
  82687. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  82688. __decorate([
  82689. BABYLON.serializeAsMeshReference("lockedTargetId")
  82690. ], FollowCamera.prototype, "lockedTarget", void 0);
  82691. return FollowCamera;
  82692. }(BABYLON.TargetCamera));
  82693. BABYLON.FollowCamera = FollowCamera;
  82694. /**
  82695. * Arc Rotate version of the follow camera.
  82696. * It still follows a Defined mesh but in an Arc Rotate Camera fashion.
  82697. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  82698. */
  82699. var ArcFollowCamera = /** @class */ (function (_super) {
  82700. __extends(ArcFollowCamera, _super);
  82701. /**
  82702. * Instantiates a new ArcFollowCamera
  82703. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  82704. * @param name Define the name of the camera
  82705. * @param alpha Define the rotation angle of the camera around the logitudinal axis
  82706. * @param beta Define the rotation angle of the camera around the elevation axis
  82707. * @param radius Define the radius of the camera from its target point
  82708. * @param target Define the target of the camera
  82709. * @param scene Define the scene the camera belongs to
  82710. */
  82711. function ArcFollowCamera(name,
  82712. /** The longitudinal angle of the camera */
  82713. alpha,
  82714. /** The latitudinal angle of the camera */
  82715. beta,
  82716. /** The radius of the camera from its target */
  82717. radius,
  82718. /** Define the camera target (the messh it should follow) */
  82719. target, scene) {
  82720. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  82721. _this.alpha = alpha;
  82722. _this.beta = beta;
  82723. _this.radius = radius;
  82724. _this.target = target;
  82725. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  82726. _this._follow();
  82727. return _this;
  82728. }
  82729. ArcFollowCamera.prototype._follow = function () {
  82730. if (!this.target) {
  82731. return;
  82732. }
  82733. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  82734. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  82735. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  82736. var targetPosition = this.target.getAbsolutePosition();
  82737. this.position = targetPosition.add(this._cartesianCoordinates);
  82738. this.setTarget(targetPosition);
  82739. };
  82740. /** @hidden */
  82741. ArcFollowCamera.prototype._checkInputs = function () {
  82742. _super.prototype._checkInputs.call(this);
  82743. this._follow();
  82744. };
  82745. /**
  82746. * Returns the class name of the object.
  82747. * It is mostly used internally for serialization purposes.
  82748. */
  82749. ArcFollowCamera.prototype.getClassName = function () {
  82750. return "ArcFollowCamera";
  82751. };
  82752. return ArcFollowCamera;
  82753. }(BABYLON.TargetCamera));
  82754. BABYLON.ArcFollowCamera = ArcFollowCamera;
  82755. })(BABYLON || (BABYLON = {}));
  82756. //# sourceMappingURL=babylon.followCamera.js.map
  82757. var BABYLON;
  82758. (function (BABYLON) {
  82759. /**
  82760. * 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,
  82761. * which still works and will still be found in many Playgrounds.
  82762. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  82763. */
  82764. var UniversalCamera = /** @class */ (function (_super) {
  82765. __extends(UniversalCamera, _super);
  82766. /**
  82767. * 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,
  82768. * which still works and will still be found in many Playgrounds.
  82769. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  82770. * @param name Define the name of the camera in the scene
  82771. * @param position Define the start position of the camera in the scene
  82772. * @param scene Define the scene the camera belongs to
  82773. */
  82774. function UniversalCamera(name, position, scene) {
  82775. var _this = _super.call(this, name, position, scene) || this;
  82776. _this.inputs.addGamepad();
  82777. return _this;
  82778. }
  82779. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  82780. /**
  82781. * Defines the gamepad rotation sensiblity.
  82782. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  82783. */
  82784. get: function () {
  82785. var gamepad = this.inputs.attached["gamepad"];
  82786. if (gamepad) {
  82787. return gamepad.gamepadAngularSensibility;
  82788. }
  82789. return 0;
  82790. },
  82791. set: function (value) {
  82792. var gamepad = this.inputs.attached["gamepad"];
  82793. if (gamepad) {
  82794. gamepad.gamepadAngularSensibility = value;
  82795. }
  82796. },
  82797. enumerable: true,
  82798. configurable: true
  82799. });
  82800. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  82801. /**
  82802. * Defines the gamepad move sensiblity.
  82803. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  82804. */
  82805. get: function () {
  82806. var gamepad = this.inputs.attached["gamepad"];
  82807. if (gamepad) {
  82808. return gamepad.gamepadMoveSensibility;
  82809. }
  82810. return 0;
  82811. },
  82812. set: function (value) {
  82813. var gamepad = this.inputs.attached["gamepad"];
  82814. if (gamepad) {
  82815. gamepad.gamepadMoveSensibility = value;
  82816. }
  82817. },
  82818. enumerable: true,
  82819. configurable: true
  82820. });
  82821. /**
  82822. * Gets the current object class name.
  82823. * @return the class name
  82824. */
  82825. UniversalCamera.prototype.getClassName = function () {
  82826. return "UniversalCamera";
  82827. };
  82828. return UniversalCamera;
  82829. }(BABYLON.TouchCamera));
  82830. BABYLON.UniversalCamera = UniversalCamera;
  82831. })(BABYLON || (BABYLON = {}));
  82832. //# sourceMappingURL=babylon.universalCamera.js.map
  82833. var BABYLON;
  82834. (function (BABYLON) {
  82835. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  82836. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  82837. });
  82838. /**
  82839. * This represents a FPS type of camera. This is only here for back compat purpose.
  82840. * Please use the UniversalCamera instead as both are identical.
  82841. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  82842. */
  82843. var GamepadCamera = /** @class */ (function (_super) {
  82844. __extends(GamepadCamera, _super);
  82845. /**
  82846. * Instantiates a new Gamepad Camera
  82847. * This represents a FPS type of camera. This is only here for back compat purpose.
  82848. * Please use the UniversalCamera instead as both are identical.
  82849. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  82850. * @param name Define the name of the camera in the scene
  82851. * @param position Define the start position of the camera in the scene
  82852. * @param scene Define the scene the camera belongs to
  82853. */
  82854. function GamepadCamera(name, position, scene) {
  82855. return _super.call(this, name, position, scene) || this;
  82856. }
  82857. /**
  82858. * Gets the current object class name.
  82859. * @return the class name
  82860. */
  82861. GamepadCamera.prototype.getClassName = function () {
  82862. return "GamepadCamera";
  82863. };
  82864. return GamepadCamera;
  82865. }(BABYLON.UniversalCamera));
  82866. BABYLON.GamepadCamera = GamepadCamera;
  82867. })(BABYLON || (BABYLON = {}));
  82868. //# sourceMappingURL=babylon.gamepadCamera.js.map
  82869. var BABYLON;
  82870. (function (BABYLON) {
  82871. /**
  82872. * PostProcessRenderPipelineManager class
  82873. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  82874. */
  82875. var PostProcessRenderPipelineManager = /** @class */ (function () {
  82876. /**
  82877. * Initializes a PostProcessRenderPipelineManager
  82878. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  82879. */
  82880. function PostProcessRenderPipelineManager() {
  82881. this._renderPipelines = {};
  82882. }
  82883. /**
  82884. * Adds a pipeline to the manager
  82885. * @param renderPipeline The pipeline to add
  82886. */
  82887. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  82888. this._renderPipelines[renderPipeline._name] = renderPipeline;
  82889. };
  82890. /**
  82891. * Attaches a camera to the pipeline
  82892. * @param renderPipelineName The name of the pipeline to attach to
  82893. * @param cameras the camera to attach
  82894. * @param unique if the camera can be attached multiple times to the pipeline
  82895. */
  82896. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  82897. if (unique === void 0) { unique = false; }
  82898. var renderPipeline = this._renderPipelines[renderPipelineName];
  82899. if (!renderPipeline) {
  82900. return;
  82901. }
  82902. renderPipeline._attachCameras(cameras, unique);
  82903. };
  82904. /**
  82905. * Detaches a camera from the pipeline
  82906. * @param renderPipelineName The name of the pipeline to detach from
  82907. * @param cameras the camera to detach
  82908. */
  82909. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  82910. var renderPipeline = this._renderPipelines[renderPipelineName];
  82911. if (!renderPipeline) {
  82912. return;
  82913. }
  82914. renderPipeline._detachCameras(cameras);
  82915. };
  82916. /**
  82917. * Enables an effect by name on a pipeline
  82918. * @param renderPipelineName the name of the pipeline to enable the effect in
  82919. * @param renderEffectName the name of the effect to enable
  82920. * @param cameras the cameras that the effect should be enabled on
  82921. */
  82922. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  82923. var renderPipeline = this._renderPipelines[renderPipelineName];
  82924. if (!renderPipeline) {
  82925. return;
  82926. }
  82927. renderPipeline._enableEffect(renderEffectName, cameras);
  82928. };
  82929. /**
  82930. * Disables an effect by name on a pipeline
  82931. * @param renderPipelineName the name of the pipeline to disable the effect in
  82932. * @param renderEffectName the name of the effect to disable
  82933. * @param cameras the cameras that the effect should be disabled on
  82934. */
  82935. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  82936. var renderPipeline = this._renderPipelines[renderPipelineName];
  82937. if (!renderPipeline) {
  82938. return;
  82939. }
  82940. renderPipeline._disableEffect(renderEffectName, cameras);
  82941. };
  82942. /**
  82943. * Updates the state of all contained render pipelines and disposes of any non supported pipelines
  82944. */
  82945. PostProcessRenderPipelineManager.prototype.update = function () {
  82946. for (var renderPipelineName in this._renderPipelines) {
  82947. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  82948. var pipeline = this._renderPipelines[renderPipelineName];
  82949. if (!pipeline.isSupported) {
  82950. pipeline.dispose();
  82951. delete this._renderPipelines[renderPipelineName];
  82952. }
  82953. else {
  82954. pipeline._update();
  82955. }
  82956. }
  82957. }
  82958. };
  82959. /** @hidden */
  82960. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  82961. for (var renderPipelineName in this._renderPipelines) {
  82962. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  82963. var pipeline = this._renderPipelines[renderPipelineName];
  82964. pipeline._rebuild();
  82965. }
  82966. }
  82967. };
  82968. /**
  82969. * Disposes of the manager and pipelines
  82970. */
  82971. PostProcessRenderPipelineManager.prototype.dispose = function () {
  82972. for (var renderPipelineName in this._renderPipelines) {
  82973. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  82974. var pipeline = this._renderPipelines[renderPipelineName];
  82975. pipeline.dispose();
  82976. }
  82977. }
  82978. };
  82979. return PostProcessRenderPipelineManager;
  82980. }());
  82981. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  82982. })(BABYLON || (BABYLON = {}));
  82983. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  82984. var BABYLON;
  82985. (function (BABYLON) {
  82986. Object.defineProperty(BABYLON.Scene.prototype, "postProcessRenderPipelineManager", {
  82987. get: function () {
  82988. if (!this._postProcessRenderPipelineManager) {
  82989. // Register the G Buffer component to the scene.
  82990. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
  82991. if (!component) {
  82992. component = new PostProcessRenderPipelineManagerSceneComponent(this);
  82993. this._addComponent(component);
  82994. }
  82995. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  82996. }
  82997. return this._postProcessRenderPipelineManager;
  82998. },
  82999. enumerable: true,
  83000. configurable: true
  83001. });
  83002. /**
  83003. * Defines the Render Pipeline scene component responsible to rendering pipelines
  83004. */
  83005. var PostProcessRenderPipelineManagerSceneComponent = /** @class */ (function () {
  83006. /**
  83007. * Creates a new instance of the component for the given scene
  83008. * @param scene Defines the scene to register the component in
  83009. */
  83010. function PostProcessRenderPipelineManagerSceneComponent(scene) {
  83011. /**
  83012. * The component name helpfull to identify the component in the list of scene components.
  83013. */
  83014. this.name = BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER;
  83015. this.scene = scene;
  83016. }
  83017. /**
  83018. * Registers the component in a given scene
  83019. */
  83020. PostProcessRenderPipelineManagerSceneComponent.prototype.register = function () {
  83021. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets);
  83022. };
  83023. /**
  83024. * Rebuilds the elements related to this component in case of
  83025. * context lost for instance.
  83026. */
  83027. PostProcessRenderPipelineManagerSceneComponent.prototype.rebuild = function () {
  83028. if (this.scene._postProcessRenderPipelineManager) {
  83029. this.scene._postProcessRenderPipelineManager._rebuild();
  83030. }
  83031. };
  83032. /**
  83033. * Disposes the component and the associated ressources
  83034. */
  83035. PostProcessRenderPipelineManagerSceneComponent.prototype.dispose = function () {
  83036. if (this.scene._postProcessRenderPipelineManager) {
  83037. this.scene._postProcessRenderPipelineManager.dispose();
  83038. }
  83039. };
  83040. PostProcessRenderPipelineManagerSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  83041. if (this.scene._postProcessRenderPipelineManager) {
  83042. this.scene._postProcessRenderPipelineManager.update();
  83043. }
  83044. };
  83045. return PostProcessRenderPipelineManagerSceneComponent;
  83046. }());
  83047. BABYLON.PostProcessRenderPipelineManagerSceneComponent = PostProcessRenderPipelineManagerSceneComponent;
  83048. })(BABYLON || (BABYLON = {}));
  83049. //# sourceMappingURL=babylon.postProcessRenderPipelineManagerSceneComponent.js.map
  83050. var BABYLON;
  83051. (function (BABYLON) {
  83052. /**
  83053. * This represents a set of one or more post processes in Babylon.
  83054. * A post process can be used to apply a shader to a texture after it is rendered.
  83055. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  83056. */
  83057. var PostProcessRenderEffect = /** @class */ (function () {
  83058. /**
  83059. * Instantiates a post process render effect.
  83060. * A post process can be used to apply a shader to a texture after it is rendered.
  83061. * @param engine The engine the effect is tied to
  83062. * @param name The name of the effect
  83063. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  83064. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  83065. */
  83066. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  83067. this._name = name;
  83068. this._singleInstance = singleInstance || true;
  83069. this._getPostProcesses = getPostProcesses;
  83070. this._cameras = {};
  83071. this._indicesForCamera = {};
  83072. this._postProcesses = {};
  83073. }
  83074. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  83075. /**
  83076. * Checks if all the post processes in the effect are supported.
  83077. */
  83078. get: function () {
  83079. for (var index in this._postProcesses) {
  83080. if (this._postProcesses.hasOwnProperty(index)) {
  83081. var pps = this._postProcesses[index];
  83082. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  83083. if (!pps[ppIndex].isSupported) {
  83084. return false;
  83085. }
  83086. }
  83087. }
  83088. }
  83089. return true;
  83090. },
  83091. enumerable: true,
  83092. configurable: true
  83093. });
  83094. /**
  83095. * Updates the current state of the effect
  83096. * @hidden
  83097. */
  83098. PostProcessRenderEffect.prototype._update = function () {
  83099. };
  83100. /**
  83101. * Attaches the effect on cameras
  83102. * @param cameras The camera to attach to.
  83103. * @hidden
  83104. */
  83105. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  83106. var _this = this;
  83107. var cameraKey;
  83108. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  83109. if (!cams) {
  83110. return;
  83111. }
  83112. for (var i = 0; i < cams.length; i++) {
  83113. var camera = cams[i];
  83114. var cameraName = camera.name;
  83115. if (this._singleInstance) {
  83116. cameraKey = 0;
  83117. }
  83118. else {
  83119. cameraKey = cameraName;
  83120. }
  83121. if (!this._postProcesses[cameraKey]) {
  83122. var postProcess = this._getPostProcesses();
  83123. if (postProcess) {
  83124. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  83125. }
  83126. }
  83127. if (!this._indicesForCamera[cameraName]) {
  83128. this._indicesForCamera[cameraName] = [];
  83129. }
  83130. this._postProcesses[cameraKey].forEach(function (postProcess) {
  83131. var index = camera.attachPostProcess(postProcess);
  83132. _this._indicesForCamera[cameraName].push(index);
  83133. });
  83134. if (!this._cameras[cameraName]) {
  83135. this._cameras[cameraName] = camera;
  83136. }
  83137. }
  83138. };
  83139. /**
  83140. * Detatches the effect on cameras
  83141. * @param cameras The camera to detatch from.
  83142. * @hidden
  83143. */
  83144. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  83145. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  83146. if (!cams) {
  83147. return;
  83148. }
  83149. for (var i = 0; i < cams.length; i++) {
  83150. var camera = cams[i];
  83151. var cameraName = camera.name;
  83152. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  83153. camera.detachPostProcess(postProcess);
  83154. });
  83155. if (this._cameras[cameraName]) {
  83156. //this._indicesForCamera.splice(index, 1);
  83157. this._cameras[cameraName] = null;
  83158. }
  83159. }
  83160. };
  83161. /**
  83162. * Enables the effect on given cameras
  83163. * @param cameras The camera to enable.
  83164. * @hidden
  83165. */
  83166. PostProcessRenderEffect.prototype._enable = function (cameras) {
  83167. var _this = this;
  83168. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  83169. if (!cams) {
  83170. return;
  83171. }
  83172. for (var i = 0; i < cams.length; i++) {
  83173. var camera = cams[i];
  83174. var cameraName = camera.name;
  83175. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  83176. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  83177. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  83178. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  83179. });
  83180. }
  83181. }
  83182. }
  83183. };
  83184. /**
  83185. * Disables the effect on the given cameras
  83186. * @param cameras The camera to disable.
  83187. * @hidden
  83188. */
  83189. PostProcessRenderEffect.prototype._disable = function (cameras) {
  83190. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  83191. if (!cams) {
  83192. return;
  83193. }
  83194. for (var i = 0; i < cams.length; i++) {
  83195. var camera = cams[i];
  83196. var cameraName = camera.name;
  83197. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  83198. camera.detachPostProcess(postProcess);
  83199. });
  83200. }
  83201. };
  83202. /**
  83203. * Gets a list of the post processes contained in the effect.
  83204. * @param camera The camera to get the post processes on.
  83205. * @returns The list of the post processes in the effect.
  83206. */
  83207. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  83208. if (this._singleInstance) {
  83209. return this._postProcesses[0];
  83210. }
  83211. else {
  83212. if (!camera) {
  83213. return null;
  83214. }
  83215. return this._postProcesses[camera.name];
  83216. }
  83217. };
  83218. return PostProcessRenderEffect;
  83219. }());
  83220. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  83221. })(BABYLON || (BABYLON = {}));
  83222. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  83223. var BABYLON;
  83224. (function (BABYLON) {
  83225. /**
  83226. * PostProcessRenderPipeline
  83227. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  83228. */
  83229. var PostProcessRenderPipeline = /** @class */ (function () {
  83230. /**
  83231. * Initializes a PostProcessRenderPipeline
  83232. * @param engine engine to add the pipeline to
  83233. * @param name name of the pipeline
  83234. */
  83235. function PostProcessRenderPipeline(engine, name) {
  83236. this.engine = engine;
  83237. this._name = name;
  83238. this._renderEffects = {};
  83239. this._renderEffectsForIsolatedPass = new Array();
  83240. this._cameras = [];
  83241. }
  83242. /**
  83243. * "PostProcessRenderPipeline"
  83244. * @returns "PostProcessRenderPipeline"
  83245. */
  83246. PostProcessRenderPipeline.prototype.getClassName = function () {
  83247. return "PostProcessRenderPipeline";
  83248. };
  83249. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  83250. /**
  83251. * If all the render effects in the pipeline are support
  83252. */
  83253. get: function () {
  83254. for (var renderEffectName in this._renderEffects) {
  83255. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  83256. if (!this._renderEffects[renderEffectName].isSupported) {
  83257. return false;
  83258. }
  83259. }
  83260. }
  83261. return true;
  83262. },
  83263. enumerable: true,
  83264. configurable: true
  83265. });
  83266. /**
  83267. * Adds an effect to the pipeline
  83268. * @param renderEffect the effect to add
  83269. */
  83270. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  83271. this._renderEffects[renderEffect._name] = renderEffect;
  83272. };
  83273. // private
  83274. /** @hidden */
  83275. PostProcessRenderPipeline.prototype._rebuild = function () {
  83276. };
  83277. /** @hidden */
  83278. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  83279. var renderEffects = this._renderEffects[renderEffectName];
  83280. if (!renderEffects) {
  83281. return;
  83282. }
  83283. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  83284. };
  83285. /** @hidden */
  83286. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  83287. var renderEffects = this._renderEffects[renderEffectName];
  83288. if (!renderEffects) {
  83289. return;
  83290. }
  83291. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  83292. };
  83293. /** @hidden */
  83294. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  83295. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  83296. if (!cams) {
  83297. return;
  83298. }
  83299. var indicesToDelete = [];
  83300. var i;
  83301. for (i = 0; i < cams.length; i++) {
  83302. var camera = cams[i];
  83303. var cameraName = camera.name;
  83304. if (this._cameras.indexOf(camera) === -1) {
  83305. this._cameras[cameraName] = camera;
  83306. }
  83307. else if (unique) {
  83308. indicesToDelete.push(i);
  83309. }
  83310. }
  83311. for (i = 0; i < indicesToDelete.length; i++) {
  83312. cameras.splice(indicesToDelete[i], 1);
  83313. }
  83314. for (var renderEffectName in this._renderEffects) {
  83315. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  83316. this._renderEffects[renderEffectName]._attachCameras(cams);
  83317. }
  83318. }
  83319. };
  83320. /** @hidden */
  83321. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  83322. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  83323. if (!cams) {
  83324. return;
  83325. }
  83326. for (var renderEffectName in this._renderEffects) {
  83327. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  83328. this._renderEffects[renderEffectName]._detachCameras(cams);
  83329. }
  83330. }
  83331. for (var i = 0; i < cams.length; i++) {
  83332. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  83333. }
  83334. };
  83335. /** @hidden */
  83336. PostProcessRenderPipeline.prototype._update = function () {
  83337. for (var renderEffectName in this._renderEffects) {
  83338. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  83339. this._renderEffects[renderEffectName]._update();
  83340. }
  83341. }
  83342. for (var i = 0; i < this._cameras.length; i++) {
  83343. var cameraName = this._cameras[i].name;
  83344. if (this._renderEffectsForIsolatedPass[cameraName]) {
  83345. this._renderEffectsForIsolatedPass[cameraName]._update();
  83346. }
  83347. }
  83348. };
  83349. /** @hidden */
  83350. PostProcessRenderPipeline.prototype._reset = function () {
  83351. this._renderEffects = {};
  83352. this._renderEffectsForIsolatedPass = new Array();
  83353. };
  83354. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  83355. // 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)
  83356. var effectKeys = Object.keys(this._renderEffects);
  83357. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  83358. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  83359. if (postProcesses) {
  83360. postProcesses[0].samples = sampleCount;
  83361. return true;
  83362. }
  83363. }
  83364. return false;
  83365. };
  83366. /**
  83367. * Disposes of the pipeline
  83368. */
  83369. PostProcessRenderPipeline.prototype.dispose = function () {
  83370. // Must be implemented by children
  83371. };
  83372. __decorate([
  83373. BABYLON.serialize()
  83374. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  83375. return PostProcessRenderPipeline;
  83376. }());
  83377. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  83378. })(BABYLON || (BABYLON = {}));
  83379. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  83380. var BABYLON;
  83381. (function (BABYLON) {
  83382. /**
  83383. * This represents a depth renderer in Babylon.
  83384. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  83385. */
  83386. var DepthRenderer = /** @class */ (function () {
  83387. /**
  83388. * Instantiates a depth renderer
  83389. * @param scene The scene the renderer belongs to
  83390. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  83391. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  83392. */
  83393. function DepthRenderer(scene, type, camera) {
  83394. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  83395. if (camera === void 0) { camera = null; }
  83396. var _this = this;
  83397. /**
  83398. * Specifiess that the depth renderer will only be used within
  83399. * the camera it is created for.
  83400. * This can help forcing its rendering during the camera processing.
  83401. */
  83402. this.useOnlyInActiveCamera = false;
  83403. this._scene = scene;
  83404. // Register the G Buffer component to the scene.
  83405. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER);
  83406. if (!component) {
  83407. component = new BABYLON.DepthRendererSceneComponent(scene);
  83408. scene._addComponent(component);
  83409. }
  83410. this._camera = camera;
  83411. var engine = scene.getEngine();
  83412. // Render target
  83413. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  83414. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83415. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83416. this._depthMap.refreshRate = 1;
  83417. this._depthMap.renderParticles = false;
  83418. this._depthMap.renderList = null;
  83419. // Camera to get depth map from to support multiple concurrent cameras
  83420. this._depthMap.activeCamera = this._camera;
  83421. this._depthMap.ignoreCameraViewport = true;
  83422. this._depthMap.useCameraPostProcesses = false;
  83423. // set default depth value to 1.0 (far away)
  83424. this._depthMap.onClearObservable.add(function (engine) {
  83425. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  83426. });
  83427. // Custom render function
  83428. var renderSubMesh = function (subMesh) {
  83429. var mesh = subMesh.getRenderingMesh();
  83430. var scene = _this._scene;
  83431. var engine = scene.getEngine();
  83432. var material = subMesh.getMaterial();
  83433. if (!material) {
  83434. return;
  83435. }
  83436. // Culling and reverse (right handed system)
  83437. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  83438. // Managing instances
  83439. var batch = mesh._getInstancesRenderList(subMesh._id);
  83440. if (batch.mustReturn) {
  83441. return;
  83442. }
  83443. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  83444. var camera = _this._camera || scene.activeCamera;
  83445. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  83446. engine.enableEffect(_this._effect);
  83447. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  83448. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  83449. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  83450. // Alpha test
  83451. if (material && material.needAlphaTesting()) {
  83452. var alphaTexture = material.getAlphaTestTexture();
  83453. if (alphaTexture) {
  83454. _this._effect.setTexture("diffuseSampler", alphaTexture);
  83455. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  83456. }
  83457. }
  83458. // Bones
  83459. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  83460. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  83461. }
  83462. // Draw
  83463. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  83464. }
  83465. };
  83466. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  83467. var index;
  83468. if (depthOnlySubMeshes.length) {
  83469. engine.setColorWrite(false);
  83470. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  83471. renderSubMesh(depthOnlySubMeshes.data[index]);
  83472. }
  83473. engine.setColorWrite(true);
  83474. }
  83475. for (index = 0; index < opaqueSubMeshes.length; index++) {
  83476. renderSubMesh(opaqueSubMeshes.data[index]);
  83477. }
  83478. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  83479. renderSubMesh(alphaTestSubMeshes.data[index]);
  83480. }
  83481. };
  83482. }
  83483. /**
  83484. * Creates the depth rendering effect and checks if the effect is ready.
  83485. * @param subMesh The submesh to be used to render the depth map of
  83486. * @param useInstances If multiple world instances should be used
  83487. * @returns if the depth renderer is ready to render the depth map
  83488. */
  83489. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  83490. var material = subMesh.getMaterial();
  83491. if (material.disableDepthWrite) {
  83492. return false;
  83493. }
  83494. var defines = [];
  83495. var attribs = [BABYLON.VertexBuffer.PositionKind];
  83496. var mesh = subMesh.getMesh();
  83497. // Alpha test
  83498. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  83499. defines.push("#define ALPHATEST");
  83500. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  83501. attribs.push(BABYLON.VertexBuffer.UVKind);
  83502. defines.push("#define UV1");
  83503. }
  83504. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  83505. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  83506. defines.push("#define UV2");
  83507. }
  83508. }
  83509. // Bones
  83510. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  83511. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  83512. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  83513. if (mesh.numBoneInfluencers > 4) {
  83514. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  83515. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  83516. }
  83517. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  83518. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  83519. }
  83520. else {
  83521. defines.push("#define NUM_BONE_INFLUENCERS 0");
  83522. }
  83523. // Instances
  83524. if (useInstances) {
  83525. defines.push("#define INSTANCES");
  83526. attribs.push("world0");
  83527. attribs.push("world1");
  83528. attribs.push("world2");
  83529. attribs.push("world3");
  83530. }
  83531. // Get correct effect
  83532. var join = defines.join("\n");
  83533. if (this._cachedDefines !== join) {
  83534. this._cachedDefines = join;
  83535. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  83536. }
  83537. return this._effect.isReady();
  83538. };
  83539. /**
  83540. * Gets the texture which the depth map will be written to.
  83541. * @returns The depth map texture
  83542. */
  83543. DepthRenderer.prototype.getDepthMap = function () {
  83544. return this._depthMap;
  83545. };
  83546. /**
  83547. * Disposes of the depth renderer.
  83548. */
  83549. DepthRenderer.prototype.dispose = function () {
  83550. this._depthMap.dispose();
  83551. };
  83552. return DepthRenderer;
  83553. }());
  83554. BABYLON.DepthRenderer = DepthRenderer;
  83555. })(BABYLON || (BABYLON = {}));
  83556. //# sourceMappingURL=babylon.depthRenderer.js.map
  83557. var BABYLON;
  83558. (function (BABYLON) {
  83559. BABYLON.Scene.prototype.enableDepthRenderer = function (camera) {
  83560. camera = camera || this.activeCamera;
  83561. if (!camera) {
  83562. throw "No camera available to enable depth renderer";
  83563. }
  83564. if (!this._depthRenderer) {
  83565. this._depthRenderer = {};
  83566. }
  83567. if (!this._depthRenderer[camera.id]) {
  83568. var textureType = 0;
  83569. if (this.getEngine().getCaps().textureHalfFloatRender) {
  83570. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  83571. }
  83572. else if (this.getEngine().getCaps().textureFloatRender) {
  83573. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  83574. }
  83575. else {
  83576. throw "Depth renderer does not support int texture type";
  83577. }
  83578. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  83579. }
  83580. return this._depthRenderer[camera.id];
  83581. };
  83582. BABYLON.Scene.prototype.disableDepthRenderer = function (camera) {
  83583. camera = camera || this.activeCamera;
  83584. if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) {
  83585. return;
  83586. }
  83587. this._depthRenderer[camera.id].dispose();
  83588. delete this._depthRenderer[camera.id];
  83589. };
  83590. /**
  83591. * Defines the Depth Renderer scene component responsible to manage a depth buffer usefull
  83592. * in several rendering techniques.
  83593. */
  83594. var DepthRendererSceneComponent = /** @class */ (function () {
  83595. /**
  83596. * Creates a new instance of the component for the given scene
  83597. * @param scene Defines the scene to register the component in
  83598. */
  83599. function DepthRendererSceneComponent(scene) {
  83600. /**
  83601. * The component name helpfull to identify the component in the list of scene components.
  83602. */
  83603. this.name = BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER;
  83604. this.scene = scene;
  83605. }
  83606. /**
  83607. * Registers the component in a given scene
  83608. */
  83609. DepthRendererSceneComponent.prototype.register = function () {
  83610. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);
  83611. this.scene._gatherActiveCameraRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER, this, this._gatherActiveCameraRenderTargets);
  83612. };
  83613. /**
  83614. * Rebuilds the elements related to this component in case of
  83615. * context lost for instance.
  83616. */
  83617. DepthRendererSceneComponent.prototype.rebuild = function () {
  83618. // Nothing to do for this component
  83619. };
  83620. /**
  83621. * Disposes the component and the associated ressources
  83622. */
  83623. DepthRendererSceneComponent.prototype.dispose = function () {
  83624. for (var key in this.scene._depthRenderer) {
  83625. this.scene._depthRenderer[key].dispose();
  83626. }
  83627. };
  83628. DepthRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  83629. if (this.scene._depthRenderer) {
  83630. for (var key in this.scene._depthRenderer) {
  83631. var depthRenderer = this.scene._depthRenderer[key];
  83632. if (!depthRenderer.useOnlyInActiveCamera) {
  83633. renderTargets.push(depthRenderer.getDepthMap());
  83634. }
  83635. }
  83636. }
  83637. };
  83638. DepthRendererSceneComponent.prototype._gatherActiveCameraRenderTargets = function (renderTargets) {
  83639. if (this.scene._depthRenderer) {
  83640. for (var key in this.scene._depthRenderer) {
  83641. var depthRenderer = this.scene._depthRenderer[key];
  83642. if (depthRenderer.useOnlyInActiveCamera && this.scene.activeCamera.id === key) {
  83643. renderTargets.push(depthRenderer.getDepthMap());
  83644. }
  83645. }
  83646. }
  83647. };
  83648. return DepthRendererSceneComponent;
  83649. }());
  83650. BABYLON.DepthRendererSceneComponent = DepthRendererSceneComponent;
  83651. })(BABYLON || (BABYLON = {}));
  83652. //# sourceMappingURL=babylon.depthRendererSceneComponent.js.map
  83653. var BABYLON;
  83654. (function (BABYLON) {
  83655. /**
  83656. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  83657. */
  83658. var GeometryBufferRenderer = /** @class */ (function () {
  83659. /**
  83660. * Creates a new G Buffer for the scene
  83661. * @param scene The scene the buffer belongs to
  83662. * @param ratio How big is the buffer related to the main canvas.
  83663. */
  83664. function GeometryBufferRenderer(scene, ratio) {
  83665. if (ratio === void 0) { ratio = 1; }
  83666. this._enablePosition = false;
  83667. this._scene = scene;
  83668. this._ratio = ratio;
  83669. // Register the G Buffer component to the scene.
  83670. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);
  83671. if (!component) {
  83672. component = new BABYLON.GeometryBufferRendererSceneComponent(scene);
  83673. scene._addComponent(component);
  83674. }
  83675. // Render target
  83676. this._createRenderTargets();
  83677. }
  83678. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  83679. /**
  83680. * Set the render list (meshes to be rendered) used in the G buffer.
  83681. */
  83682. set: function (meshes) {
  83683. this._multiRenderTarget.renderList = meshes;
  83684. },
  83685. enumerable: true,
  83686. configurable: true
  83687. });
  83688. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  83689. /**
  83690. * Gets wether or not G buffer are supported by the running hardware.
  83691. * This requires draw buffer supports
  83692. */
  83693. get: function () {
  83694. return this._multiRenderTarget.isSupported;
  83695. },
  83696. enumerable: true,
  83697. configurable: true
  83698. });
  83699. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  83700. /**
  83701. * Gets wether or not position are enabled for the G buffer.
  83702. */
  83703. get: function () {
  83704. return this._enablePosition;
  83705. },
  83706. /**
  83707. * Sets wether or not position are enabled for the G buffer.
  83708. */
  83709. set: function (enable) {
  83710. this._enablePosition = enable;
  83711. this.dispose();
  83712. this._createRenderTargets();
  83713. },
  83714. enumerable: true,
  83715. configurable: true
  83716. });
  83717. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  83718. /**
  83719. * Gets the scene associated with the buffer.
  83720. */
  83721. get: function () {
  83722. return this._scene;
  83723. },
  83724. enumerable: true,
  83725. configurable: true
  83726. });
  83727. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  83728. /**
  83729. * Gets the ratio used by the buffer during its creation.
  83730. * How big is the buffer related to the main canvas.
  83731. */
  83732. get: function () {
  83733. return this._ratio;
  83734. },
  83735. enumerable: true,
  83736. configurable: true
  83737. });
  83738. /**
  83739. * Checks wether everything is ready to render a submesh to the G buffer.
  83740. * @param subMesh the submesh to check readiness for
  83741. * @param useInstances is the mesh drawn using instance or not
  83742. * @returns true if ready otherwise false
  83743. */
  83744. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  83745. var material = subMesh.getMaterial();
  83746. if (material && material.disableDepthWrite) {
  83747. return false;
  83748. }
  83749. var defines = [];
  83750. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  83751. var mesh = subMesh.getMesh();
  83752. // Alpha test
  83753. if (material && material.needAlphaTesting()) {
  83754. defines.push("#define ALPHATEST");
  83755. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  83756. attribs.push(BABYLON.VertexBuffer.UVKind);
  83757. defines.push("#define UV1");
  83758. }
  83759. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  83760. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  83761. defines.push("#define UV2");
  83762. }
  83763. }
  83764. // Buffers
  83765. if (this._enablePosition) {
  83766. defines.push("#define POSITION");
  83767. }
  83768. // Bones
  83769. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  83770. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  83771. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  83772. if (mesh.numBoneInfluencers > 4) {
  83773. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  83774. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  83775. }
  83776. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  83777. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  83778. }
  83779. else {
  83780. defines.push("#define NUM_BONE_INFLUENCERS 0");
  83781. }
  83782. // Instances
  83783. if (useInstances) {
  83784. defines.push("#define INSTANCES");
  83785. attribs.push("world0");
  83786. attribs.push("world1");
  83787. attribs.push("world2");
  83788. attribs.push("world3");
  83789. }
  83790. // Get correct effect
  83791. var join = defines.join("\n");
  83792. if (this._cachedDefines !== join) {
  83793. this._cachedDefines = join;
  83794. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  83795. }
  83796. return this._effect.isReady();
  83797. };
  83798. /**
  83799. * Gets the current underlying G Buffer.
  83800. * @returns the buffer
  83801. */
  83802. GeometryBufferRenderer.prototype.getGBuffer = function () {
  83803. return this._multiRenderTarget;
  83804. };
  83805. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  83806. /**
  83807. * Gets the number of samples used to render the buffer (anti aliasing).
  83808. */
  83809. get: function () {
  83810. return this._multiRenderTarget.samples;
  83811. },
  83812. /**
  83813. * Sets the number of samples used to render the buffer (anti aliasing).
  83814. */
  83815. set: function (value) {
  83816. this._multiRenderTarget.samples = value;
  83817. },
  83818. enumerable: true,
  83819. configurable: true
  83820. });
  83821. /**
  83822. * Disposes the renderer and frees up associated resources.
  83823. */
  83824. GeometryBufferRenderer.prototype.dispose = function () {
  83825. this.getGBuffer().dispose();
  83826. };
  83827. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  83828. var _this = this;
  83829. var engine = this._scene.getEngine();
  83830. var count = this._enablePosition ? 3 : 2;
  83831. 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 });
  83832. if (!this.isSupported) {
  83833. return;
  83834. }
  83835. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83836. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83837. this._multiRenderTarget.refreshRate = 1;
  83838. this._multiRenderTarget.renderParticles = false;
  83839. this._multiRenderTarget.renderList = null;
  83840. // set default depth value to 1.0 (far away)
  83841. this._multiRenderTarget.onClearObservable.add(function (engine) {
  83842. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  83843. });
  83844. // Custom render function
  83845. var renderSubMesh = function (subMesh) {
  83846. var mesh = subMesh.getRenderingMesh();
  83847. var scene = _this._scene;
  83848. var engine = scene.getEngine();
  83849. var material = subMesh.getMaterial();
  83850. if (!material) {
  83851. return;
  83852. }
  83853. // Culling
  83854. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  83855. // Managing instances
  83856. var batch = mesh._getInstancesRenderList(subMesh._id);
  83857. if (batch.mustReturn) {
  83858. return;
  83859. }
  83860. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  83861. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  83862. engine.enableEffect(_this._effect);
  83863. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  83864. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  83865. _this._effect.setMatrix("view", scene.getViewMatrix());
  83866. // Alpha test
  83867. if (material && material.needAlphaTesting()) {
  83868. var alphaTexture = material.getAlphaTestTexture();
  83869. if (alphaTexture) {
  83870. _this._effect.setTexture("diffuseSampler", alphaTexture);
  83871. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  83872. }
  83873. }
  83874. // Bones
  83875. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  83876. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  83877. }
  83878. // Draw
  83879. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  83880. }
  83881. };
  83882. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  83883. var index;
  83884. if (depthOnlySubMeshes.length) {
  83885. engine.setColorWrite(false);
  83886. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  83887. renderSubMesh(depthOnlySubMeshes.data[index]);
  83888. }
  83889. engine.setColorWrite(true);
  83890. }
  83891. for (index = 0; index < opaqueSubMeshes.length; index++) {
  83892. renderSubMesh(opaqueSubMeshes.data[index]);
  83893. }
  83894. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  83895. renderSubMesh(alphaTestSubMeshes.data[index]);
  83896. }
  83897. };
  83898. };
  83899. return GeometryBufferRenderer;
  83900. }());
  83901. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  83902. })(BABYLON || (BABYLON = {}));
  83903. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  83904. var BABYLON;
  83905. (function (BABYLON) {
  83906. Object.defineProperty(BABYLON.Scene.prototype, "geometryBufferRenderer", {
  83907. get: function () {
  83908. this._geometryBufferRenderer;
  83909. },
  83910. set: function (value) {
  83911. if (value && value.isSupported) {
  83912. this._geometryBufferRenderer = value;
  83913. }
  83914. },
  83915. enumerable: true,
  83916. configurable: true
  83917. });
  83918. BABYLON.Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  83919. if (ratio === void 0) { ratio = 1; }
  83920. if (this._geometryBufferRenderer) {
  83921. return this._geometryBufferRenderer;
  83922. }
  83923. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  83924. if (!this._geometryBufferRenderer.isSupported) {
  83925. this._geometryBufferRenderer = null;
  83926. }
  83927. return this._geometryBufferRenderer;
  83928. };
  83929. BABYLON.Scene.prototype.disableGeometryBufferRenderer = function () {
  83930. if (!this._geometryBufferRenderer) {
  83931. return;
  83932. }
  83933. this._geometryBufferRenderer.dispose();
  83934. this._geometryBufferRenderer = null;
  83935. };
  83936. /**
  83937. * Defines the Geometry Buffer scene component responsible to manage a G-Buffer useful
  83938. * in several rendering techniques.
  83939. */
  83940. var GeometryBufferRendererSceneComponent = /** @class */ (function () {
  83941. /**
  83942. * Creates a new instance of the component for the given scene
  83943. * @param scene Defines the scene to register the component in
  83944. */
  83945. function GeometryBufferRendererSceneComponent(scene) {
  83946. /**
  83947. * The component name helpful to identify the component in the list of scene components.
  83948. */
  83949. this.name = BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER;
  83950. this.scene = scene;
  83951. }
  83952. /**
  83953. * Registers the component in a given scene
  83954. */
  83955. GeometryBufferRendererSceneComponent.prototype.register = function () {
  83956. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets);
  83957. };
  83958. /**
  83959. * Rebuilds the elements related to this component in case of
  83960. * context lost for instance.
  83961. */
  83962. GeometryBufferRendererSceneComponent.prototype.rebuild = function () {
  83963. // Nothing to do for this component
  83964. };
  83965. /**
  83966. * Disposes the component and the associated ressources
  83967. */
  83968. GeometryBufferRendererSceneComponent.prototype.dispose = function () {
  83969. // Nothing to do for this component
  83970. };
  83971. GeometryBufferRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  83972. if (this.scene._geometryBufferRenderer) {
  83973. renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer());
  83974. }
  83975. };
  83976. return GeometryBufferRendererSceneComponent;
  83977. }());
  83978. BABYLON.GeometryBufferRendererSceneComponent = GeometryBufferRendererSceneComponent;
  83979. })(BABYLON || (BABYLON = {}));
  83980. //# sourceMappingURL=babylon.geometryBufferRendererSceneComponent.js.map
  83981. var BABYLON;
  83982. (function (BABYLON) {
  83983. /**
  83984. * Render pipeline to produce ssao effect
  83985. */
  83986. var SSAORenderingPipeline = /** @class */ (function (_super) {
  83987. __extends(SSAORenderingPipeline, _super);
  83988. /**
  83989. * @constructor
  83990. * @param name - The rendering pipeline name
  83991. * @param scene - The scene linked to this pipeline
  83992. * @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 }
  83993. * @param cameras - The array of cameras that the rendering pipeline will be attached to
  83994. */
  83995. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  83996. var _this = _super.call(this, scene.getEngine(), name) || this;
  83997. // Members
  83998. /**
  83999. * @ignore
  84000. * The PassPostProcess id in the pipeline that contains the original scene color
  84001. */
  84002. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  84003. /**
  84004. * @ignore
  84005. * The SSAO PostProcess id in the pipeline
  84006. */
  84007. _this.SSAORenderEffect = "SSAORenderEffect";
  84008. /**
  84009. * @ignore
  84010. * The horizontal blur PostProcess id in the pipeline
  84011. */
  84012. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  84013. /**
  84014. * @ignore
  84015. * The vertical blur PostProcess id in the pipeline
  84016. */
  84017. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  84018. /**
  84019. * @ignore
  84020. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  84021. */
  84022. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  84023. /**
  84024. * The output strength of the SSAO post-process. Default value is 1.0.
  84025. */
  84026. _this.totalStrength = 1.0;
  84027. /**
  84028. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  84029. */
  84030. _this.radius = 0.0001;
  84031. /**
  84032. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  84033. * Must not be equal to fallOff and superior to fallOff.
  84034. * Default value is 0.975
  84035. */
  84036. _this.area = 0.0075;
  84037. /**
  84038. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  84039. * Must not be equal to area and inferior to area.
  84040. * Default value is 0.0
  84041. */
  84042. _this.fallOff = 0.000001;
  84043. /**
  84044. * The base color of the SSAO post-process
  84045. * The final result is "base + ssao" between [0, 1]
  84046. */
  84047. _this.base = 0.5;
  84048. _this._firstUpdate = true;
  84049. _this._scene = scene;
  84050. // Set up assets
  84051. _this._createRandomTexture();
  84052. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  84053. var ssaoRatio = ratio.ssaoRatio || ratio;
  84054. var combineRatio = ratio.combineRatio || ratio;
  84055. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  84056. _this._createSSAOPostProcess(ssaoRatio);
  84057. _this._createBlurPostProcess(ssaoRatio);
  84058. _this._createSSAOCombinePostProcess(combineRatio);
  84059. // Set up pipeline
  84060. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  84061. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  84062. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  84063. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  84064. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  84065. // Finish
  84066. scene.postProcessRenderPipelineManager.addPipeline(_this);
  84067. if (cameras) {
  84068. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  84069. }
  84070. return _this;
  84071. }
  84072. // Public Methods
  84073. /**
  84074. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  84075. */
  84076. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  84077. if (disableDepthRender === void 0) { disableDepthRender = false; }
  84078. for (var i = 0; i < this._scene.cameras.length; i++) {
  84079. var camera = this._scene.cameras[i];
  84080. this._originalColorPostProcess.dispose(camera);
  84081. this._ssaoPostProcess.dispose(camera);
  84082. this._blurHPostProcess.dispose(camera);
  84083. this._blurVPostProcess.dispose(camera);
  84084. this._ssaoCombinePostProcess.dispose(camera);
  84085. }
  84086. this._randomTexture.dispose();
  84087. if (disableDepthRender) {
  84088. this._scene.disableDepthRenderer();
  84089. }
  84090. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  84091. _super.prototype.dispose.call(this);
  84092. };
  84093. // Private Methods
  84094. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  84095. var _this = this;
  84096. var size = 16;
  84097. 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);
  84098. 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);
  84099. this._blurHPostProcess.onActivateObservable.add(function () {
  84100. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  84101. _this._blurHPostProcess.kernel = size * dw;
  84102. });
  84103. this._blurVPostProcess.onActivateObservable.add(function () {
  84104. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  84105. _this._blurVPostProcess.kernel = size * dw;
  84106. });
  84107. };
  84108. /** @hidden */
  84109. SSAORenderingPipeline.prototype._rebuild = function () {
  84110. this._firstUpdate = true;
  84111. _super.prototype._rebuild.call(this);
  84112. };
  84113. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  84114. var _this = this;
  84115. var numSamples = 16;
  84116. var sampleSphere = [
  84117. 0.5381, 0.1856, -0.4319,
  84118. 0.1379, 0.2486, 0.4430,
  84119. 0.3371, 0.5679, -0.0057,
  84120. -0.6999, -0.0451, -0.0019,
  84121. 0.0689, -0.1598, -0.8547,
  84122. 0.0560, 0.0069, -0.1843,
  84123. -0.0146, 0.1402, 0.0762,
  84124. 0.0100, -0.1924, -0.0344,
  84125. -0.3577, -0.5301, -0.4358,
  84126. -0.3169, 0.1063, 0.0158,
  84127. 0.0103, -0.5869, 0.0046,
  84128. -0.0897, -0.4940, 0.3287,
  84129. 0.7119, -0.0154, -0.0918,
  84130. -0.0533, 0.0596, -0.5411,
  84131. 0.0352, -0.0631, 0.5460,
  84132. -0.4776, 0.2847, -0.0271
  84133. ];
  84134. var samplesFactor = 1.0 / numSamples;
  84135. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  84136. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  84137. "area", "fallOff", "base", "range", "viewport"
  84138. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  84139. this._ssaoPostProcess.onApply = function (effect) {
  84140. if (_this._firstUpdate) {
  84141. effect.setArray3("sampleSphere", sampleSphere);
  84142. effect.setFloat("samplesFactor", samplesFactor);
  84143. effect.setFloat("randTextureTiles", 4.0);
  84144. }
  84145. effect.setFloat("totalStrength", _this.totalStrength);
  84146. effect.setFloat("radius", _this.radius);
  84147. effect.setFloat("area", _this.area);
  84148. effect.setFloat("fallOff", _this.fallOff);
  84149. effect.setFloat("base", _this.base);
  84150. effect.setTexture("textureSampler", _this._depthTexture);
  84151. effect.setTexture("randomSampler", _this._randomTexture);
  84152. };
  84153. };
  84154. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  84155. var _this = this;
  84156. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  84157. this._ssaoCombinePostProcess.onApply = function (effect) {
  84158. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  84159. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  84160. };
  84161. };
  84162. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  84163. var size = 512;
  84164. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  84165. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  84166. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  84167. var context = this._randomTexture.getContext();
  84168. var rand = function (min, max) {
  84169. return Math.random() * (max - min) + min;
  84170. };
  84171. var randVector = BABYLON.Vector3.Zero();
  84172. for (var x = 0; x < size; x++) {
  84173. for (var y = 0; y < size; y++) {
  84174. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  84175. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  84176. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  84177. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  84178. context.fillRect(x, y, 1, 1);
  84179. }
  84180. }
  84181. this._randomTexture.update(false);
  84182. };
  84183. __decorate([
  84184. BABYLON.serialize()
  84185. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  84186. __decorate([
  84187. BABYLON.serialize()
  84188. ], SSAORenderingPipeline.prototype, "radius", void 0);
  84189. __decorate([
  84190. BABYLON.serialize()
  84191. ], SSAORenderingPipeline.prototype, "area", void 0);
  84192. __decorate([
  84193. BABYLON.serialize()
  84194. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  84195. __decorate([
  84196. BABYLON.serialize()
  84197. ], SSAORenderingPipeline.prototype, "base", void 0);
  84198. return SSAORenderingPipeline;
  84199. }(BABYLON.PostProcessRenderPipeline));
  84200. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  84201. })(BABYLON || (BABYLON = {}));
  84202. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  84203. var BABYLON;
  84204. (function (BABYLON) {
  84205. /**
  84206. * Render pipeline to produce ssao effect
  84207. */
  84208. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  84209. __extends(SSAO2RenderingPipeline, _super);
  84210. /**
  84211. * @constructor
  84212. * @param name The rendering pipeline name
  84213. * @param scene The scene linked to this pipeline
  84214. * @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 }
  84215. * @param cameras The array of cameras that the rendering pipeline will be attached to
  84216. */
  84217. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  84218. var _this = _super.call(this, scene.getEngine(), name) || this;
  84219. // Members
  84220. /**
  84221. * @ignore
  84222. * The PassPostProcess id in the pipeline that contains the original scene color
  84223. */
  84224. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  84225. /**
  84226. * @ignore
  84227. * The SSAO PostProcess id in the pipeline
  84228. */
  84229. _this.SSAORenderEffect = "SSAORenderEffect";
  84230. /**
  84231. * @ignore
  84232. * The horizontal blur PostProcess id in the pipeline
  84233. */
  84234. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  84235. /**
  84236. * @ignore
  84237. * The vertical blur PostProcess id in the pipeline
  84238. */
  84239. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  84240. /**
  84241. * @ignore
  84242. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  84243. */
  84244. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  84245. /**
  84246. * The output strength of the SSAO post-process. Default value is 1.0.
  84247. */
  84248. _this.totalStrength = 1.0;
  84249. /**
  84250. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  84251. */
  84252. _this.maxZ = 100.0;
  84253. /**
  84254. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  84255. */
  84256. _this.minZAspect = 0.2;
  84257. _this._samples = 8;
  84258. _this._textureSamples = 1;
  84259. _this._expensiveBlur = true;
  84260. /**
  84261. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  84262. */
  84263. _this.radius = 2.0;
  84264. /**
  84265. * The base color of the SSAO post-process
  84266. * The final result is "base + ssao" between [0, 1]
  84267. */
  84268. _this.base = 0;
  84269. _this._firstUpdate = true;
  84270. _this._bits = new Uint32Array(1);
  84271. _this._scene = scene;
  84272. _this._ratio = ratio;
  84273. if (!_this.isSupported) {
  84274. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  84275. return _this;
  84276. }
  84277. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  84278. var blurRatio = _this._ratio.blurRatio || ratio;
  84279. // Set up assets
  84280. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  84281. _this._createRandomTexture();
  84282. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  84283. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  84284. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  84285. _this._originalColorPostProcess.samples = _this.textureSamples;
  84286. _this._createSSAOPostProcess(1.0);
  84287. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  84288. _this._createSSAOCombinePostProcess(blurRatio);
  84289. // Set up pipeline
  84290. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  84291. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  84292. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  84293. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  84294. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  84295. // Finish
  84296. scene.postProcessRenderPipelineManager.addPipeline(_this);
  84297. if (cameras) {
  84298. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  84299. }
  84300. return _this;
  84301. }
  84302. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  84303. get: function () {
  84304. return this._samples;
  84305. },
  84306. /**
  84307. * Number of samples used for the SSAO calculations. Default value is 8
  84308. */
  84309. set: function (n) {
  84310. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  84311. this._samples = n;
  84312. this._sampleSphere = this._generateHemisphere();
  84313. this._firstUpdate = true;
  84314. },
  84315. enumerable: true,
  84316. configurable: true
  84317. });
  84318. Object.defineProperty(SSAO2RenderingPipeline.prototype, "textureSamples", {
  84319. get: function () {
  84320. return this._textureSamples;
  84321. },
  84322. /**
  84323. * Number of samples to use for antialiasing
  84324. */
  84325. set: function (n) {
  84326. this._textureSamples = n;
  84327. this._originalColorPostProcess.samples = n;
  84328. this._blurHPostProcess.samples = n;
  84329. this._blurVPostProcess.samples = n;
  84330. this._ssaoPostProcess.samples = n;
  84331. this._ssaoCombinePostProcess.samples = n;
  84332. },
  84333. enumerable: true,
  84334. configurable: true
  84335. });
  84336. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  84337. get: function () {
  84338. return this._expensiveBlur;
  84339. },
  84340. /**
  84341. * If bilateral blur should be used
  84342. */
  84343. set: function (b) {
  84344. 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"]);
  84345. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  84346. this._expensiveBlur = b;
  84347. this._firstUpdate = true;
  84348. },
  84349. enumerable: true,
  84350. configurable: true
  84351. });
  84352. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  84353. /**
  84354. * Support test.
  84355. */
  84356. get: function () {
  84357. var engine = BABYLON.Engine.LastCreatedEngine;
  84358. if (!engine) {
  84359. return false;
  84360. }
  84361. return engine.getCaps().drawBuffersExtension;
  84362. },
  84363. enumerable: true,
  84364. configurable: true
  84365. });
  84366. // Public Methods
  84367. /**
  84368. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  84369. */
  84370. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  84371. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  84372. for (var i = 0; i < this._scene.cameras.length; i++) {
  84373. var camera = this._scene.cameras[i];
  84374. this._originalColorPostProcess.dispose(camera);
  84375. this._ssaoPostProcess.dispose(camera);
  84376. this._blurHPostProcess.dispose(camera);
  84377. this._blurVPostProcess.dispose(camera);
  84378. this._ssaoCombinePostProcess.dispose(camera);
  84379. }
  84380. this._randomTexture.dispose();
  84381. if (disableGeometryBufferRenderer) {
  84382. this._scene.disableGeometryBufferRenderer();
  84383. }
  84384. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  84385. _super.prototype.dispose.call(this);
  84386. };
  84387. // Private Methods
  84388. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  84389. var _this = this;
  84390. this._samplerOffsets = [];
  84391. var expensive = this.expensiveBlur;
  84392. for (var i = -8; i < 8; i++) {
  84393. this._samplerOffsets.push(i * 2 + 0.5);
  84394. }
  84395. 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");
  84396. this._blurHPostProcess.onApply = function (effect) {
  84397. if (!_this._scene.activeCamera) {
  84398. return;
  84399. }
  84400. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  84401. effect.setFloat("near", _this._scene.activeCamera.minZ);
  84402. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  84403. effect.setFloat("radius", _this.radius);
  84404. effect.setTexture("depthSampler", _this._depthTexture);
  84405. if (_this._firstUpdate) {
  84406. effect.setArray("samplerOffsets", _this._samplerOffsets);
  84407. }
  84408. };
  84409. 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");
  84410. this._blurVPostProcess.onApply = function (effect) {
  84411. if (!_this._scene.activeCamera) {
  84412. return;
  84413. }
  84414. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  84415. effect.setFloat("near", _this._scene.activeCamera.minZ);
  84416. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  84417. effect.setFloat("radius", _this.radius);
  84418. effect.setTexture("depthSampler", _this._depthTexture);
  84419. if (_this._firstUpdate) {
  84420. effect.setArray("samplerOffsets", _this._samplerOffsets);
  84421. _this._firstUpdate = false;
  84422. }
  84423. };
  84424. this._blurHPostProcess.samples = this.textureSamples;
  84425. this._blurVPostProcess.samples = this.textureSamples;
  84426. };
  84427. /** @hidden */
  84428. SSAO2RenderingPipeline.prototype._rebuild = function () {
  84429. this._firstUpdate = true;
  84430. _super.prototype._rebuild.call(this);
  84431. };
  84432. //Van der Corput radical inverse
  84433. SSAO2RenderingPipeline.prototype._radicalInverse_VdC = function (i) {
  84434. this._bits[0] = i;
  84435. this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0;
  84436. this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | ((this._bits[0] & 0xAAAAAAAA) >>> 1) >>> 0;
  84437. this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | ((this._bits[0] & 0xCCCCCCCC) >>> 2) >>> 0;
  84438. this._bits[0] = ((this._bits[0] & 0x0F0F0F0F) << 4) | ((this._bits[0] & 0xF0F0F0F0) >>> 4) >>> 0;
  84439. this._bits[0] = ((this._bits[0] & 0x00FF00FF) << 8) | ((this._bits[0] & 0xFF00FF00) >>> 8) >>> 0;
  84440. return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296
  84441. };
  84442. SSAO2RenderingPipeline.prototype._hammersley = function (i, n) {
  84443. return [i / n, this._radicalInverse_VdC(i)];
  84444. };
  84445. SSAO2RenderingPipeline.prototype._hemisphereSample_uniform = function (u, v) {
  84446. var phi = v * 2.0 * Math.PI;
  84447. // rejecting samples that are close to tangent plane to avoid z-fighting artifacts
  84448. var cosTheta = 1.0 - (u * 0.85 + 0.15);
  84449. var sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta);
  84450. return new BABYLON.Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);
  84451. };
  84452. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  84453. var numSamples = this.samples;
  84454. var result = [];
  84455. var vector;
  84456. var i = 0;
  84457. while (i < numSamples) {
  84458. if (numSamples < 16) {
  84459. vector = this._hemisphereSample_uniform(Math.random(), Math.random());
  84460. }
  84461. else {
  84462. var rand = this._hammersley(i, numSamples);
  84463. vector = this._hemisphereSample_uniform(rand[0], rand[1]);
  84464. }
  84465. result.push(vector.x, vector.y, vector.z);
  84466. i++;
  84467. }
  84468. return result;
  84469. };
  84470. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  84471. var _this = this;
  84472. var numSamples = this.samples;
  84473. this._sampleSphere = this._generateHemisphere();
  84474. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  84475. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  84476. "base", "range", "projection", "near", "far", "texelSize",
  84477. "xViewport", "yViewport", "maxZ", "minZAspect"
  84478. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  84479. this._ssaoPostProcess.onApply = function (effect) {
  84480. if (_this._firstUpdate) {
  84481. effect.setArray3("sampleSphere", _this._sampleSphere);
  84482. effect.setFloat("randTextureTiles", 32.0);
  84483. }
  84484. if (!_this._scene.activeCamera) {
  84485. return;
  84486. }
  84487. effect.setFloat("samplesFactor", 1 / _this.samples);
  84488. effect.setFloat("totalStrength", _this.totalStrength);
  84489. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  84490. effect.setFloat("radius", _this.radius);
  84491. effect.setFloat("maxZ", _this.maxZ);
  84492. effect.setFloat("minZAspect", _this.minZAspect);
  84493. effect.setFloat("base", _this.base);
  84494. effect.setFloat("near", _this._scene.activeCamera.minZ);
  84495. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  84496. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  84497. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  84498. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  84499. effect.setTexture("textureSampler", _this._depthTexture);
  84500. effect.setTexture("normalSampler", _this._normalTexture);
  84501. effect.setTexture("randomSampler", _this._randomTexture);
  84502. };
  84503. this._ssaoPostProcess.samples = this.textureSamples;
  84504. };
  84505. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  84506. var _this = this;
  84507. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  84508. this._ssaoCombinePostProcess.onApply = function (effect) {
  84509. var viewport = _this._scene.activeCamera.viewport;
  84510. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  84511. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  84512. };
  84513. this._ssaoCombinePostProcess.samples = this.textureSamples;
  84514. };
  84515. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  84516. var size = 128;
  84517. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  84518. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  84519. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  84520. var context = this._randomTexture.getContext();
  84521. var rand = function (min, max) {
  84522. return Math.random() * (max - min) + min;
  84523. };
  84524. var randVector = BABYLON.Vector3.Zero();
  84525. for (var x = 0; x < size; x++) {
  84526. for (var y = 0; y < size; y++) {
  84527. randVector.x = rand(0.0, 1.0);
  84528. randVector.y = rand(0.0, 1.0);
  84529. randVector.z = 0.0;
  84530. randVector.normalize();
  84531. randVector.scaleInPlace(255);
  84532. randVector.x = Math.floor(randVector.x);
  84533. randVector.y = Math.floor(randVector.y);
  84534. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  84535. context.fillRect(x, y, 1, 1);
  84536. }
  84537. }
  84538. this._randomTexture.update(false);
  84539. };
  84540. /**
  84541. * Serialize the rendering pipeline (Used when exporting)
  84542. * @returns the serialized object
  84543. */
  84544. SSAO2RenderingPipeline.prototype.serialize = function () {
  84545. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  84546. serializationObject.customType = "SSAO2RenderingPipeline";
  84547. return serializationObject;
  84548. };
  84549. /**
  84550. * Parse the serialized pipeline
  84551. * @param source Source pipeline.
  84552. * @param scene The scene to load the pipeline to.
  84553. * @param rootUrl The URL of the serialized pipeline.
  84554. * @returns An instantiated pipeline from the serialized object.
  84555. */
  84556. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  84557. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  84558. };
  84559. __decorate([
  84560. BABYLON.serialize()
  84561. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  84562. __decorate([
  84563. BABYLON.serialize()
  84564. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  84565. __decorate([
  84566. BABYLON.serialize()
  84567. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  84568. __decorate([
  84569. BABYLON.serialize("samples")
  84570. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  84571. __decorate([
  84572. BABYLON.serialize("textureSamples")
  84573. ], SSAO2RenderingPipeline.prototype, "_textureSamples", void 0);
  84574. __decorate([
  84575. BABYLON.serialize()
  84576. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  84577. __decorate([
  84578. BABYLON.serialize("expensiveBlur")
  84579. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  84580. __decorate([
  84581. BABYLON.serialize()
  84582. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  84583. __decorate([
  84584. BABYLON.serialize()
  84585. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  84586. return SSAO2RenderingPipeline;
  84587. }(BABYLON.PostProcessRenderPipeline));
  84588. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  84589. })(BABYLON || (BABYLON = {}));
  84590. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  84591. var BABYLON;
  84592. (function (BABYLON) {
  84593. /**
  84594. * BABYLON.JS Chromatic Aberration GLSL Shader
  84595. * Author: Olivier Guyot
  84596. * Separates very slightly R, G and B colors on the edges of the screen
  84597. * Inspired by Francois Tarlier & Martins Upitis
  84598. */
  84599. var LensRenderingPipeline = /** @class */ (function (_super) {
  84600. __extends(LensRenderingPipeline, _super);
  84601. /**
  84602. * @constructor
  84603. *
  84604. * Effect parameters are as follow:
  84605. * {
  84606. * chromatic_aberration: number; // from 0 to x (1 for realism)
  84607. * edge_blur: number; // from 0 to x (1 for realism)
  84608. * distortion: number; // from 0 to x (1 for realism)
  84609. * grain_amount: number; // from 0 to 1
  84610. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  84611. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  84612. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  84613. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  84614. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  84615. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  84616. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  84617. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  84618. * }
  84619. * Note: if an effect parameter is unset, effect is disabled
  84620. *
  84621. * @param name The rendering pipeline name
  84622. * @param parameters - An object containing all parameters (see above)
  84623. * @param scene The scene linked to this pipeline
  84624. * @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)
  84625. * @param cameras The array of cameras that the rendering pipeline will be attached to
  84626. */
  84627. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  84628. if (ratio === void 0) { ratio = 1.0; }
  84629. var _this = _super.call(this, scene.getEngine(), name) || this;
  84630. // Lens effects can be of the following:
  84631. // - chromatic aberration (slight shift of RGB colors)
  84632. // - blur on the edge of the lens
  84633. // - lens distortion
  84634. // - depth-of-field blur & highlights enhancing
  84635. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  84636. // - grain effect (noise or custom texture)
  84637. // Two additional texture samplers are needed:
  84638. // - depth map (for depth-of-field)
  84639. // - grain texture
  84640. /**
  84641. * @ignore
  84642. * The chromatic aberration PostProcess id in the pipeline
  84643. */
  84644. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  84645. /**
  84646. * @ignore
  84647. * The highlights enhancing PostProcess id in the pipeline
  84648. */
  84649. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  84650. /**
  84651. * @ignore
  84652. * The depth-of-field PostProcess id in the pipeline
  84653. */
  84654. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  84655. _this._scene = scene;
  84656. // Fetch texture samplers
  84657. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  84658. if (parameters.grain_texture) {
  84659. _this._grainTexture = parameters.grain_texture;
  84660. }
  84661. else {
  84662. _this._createGrainTexture();
  84663. }
  84664. // save parameters
  84665. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  84666. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  84667. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  84668. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  84669. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  84670. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  84671. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  84672. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  84673. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  84674. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  84675. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  84676. // Create effects
  84677. _this._createChromaticAberrationPostProcess(ratio);
  84678. _this._createHighlightsPostProcess(ratio);
  84679. _this._createDepthOfFieldPostProcess(ratio / 4);
  84680. // Set up pipeline
  84681. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  84682. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  84683. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  84684. if (_this._highlightsGain === -1) {
  84685. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  84686. }
  84687. // Finish
  84688. scene.postProcessRenderPipelineManager.addPipeline(_this);
  84689. if (cameras) {
  84690. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  84691. }
  84692. return _this;
  84693. }
  84694. // public methods (self explanatory)
  84695. /**
  84696. * Sets the amount of blur at the edges
  84697. * @param amount blur amount
  84698. */
  84699. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  84700. /**
  84701. * Sets edge blur to 0
  84702. */
  84703. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  84704. /**
  84705. * Sets the amout of grain
  84706. * @param amount Amount of grain
  84707. */
  84708. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  84709. /**
  84710. * Set grain amount to 0
  84711. */
  84712. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  84713. /**
  84714. * Sets the chromatic aberration amount
  84715. * @param amount amount of chromatic aberration
  84716. */
  84717. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  84718. /**
  84719. * Sets chromatic aberration amount to 0
  84720. */
  84721. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  84722. /**
  84723. * Sets the EdgeDistortion amount
  84724. * @param amount amount of EdgeDistortion
  84725. */
  84726. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  84727. /**
  84728. * Sets edge distortion to 0
  84729. */
  84730. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  84731. /**
  84732. * Sets the FocusDistance amount
  84733. * @param amount amount of FocusDistance
  84734. */
  84735. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  84736. /**
  84737. * Disables depth of field
  84738. */
  84739. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  84740. /**
  84741. * Sets the Aperture amount
  84742. * @param amount amount of Aperture
  84743. */
  84744. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  84745. /**
  84746. * Sets the DarkenOutOfFocus amount
  84747. * @param amount amount of DarkenOutOfFocus
  84748. */
  84749. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  84750. /**
  84751. * Creates a pentagon bokeh effect
  84752. */
  84753. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  84754. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  84755. };
  84756. /**
  84757. * Disables the pentagon bokeh effect
  84758. */
  84759. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  84760. this._highlightsPostProcess.updateEffect();
  84761. };
  84762. /**
  84763. * Enables noise blur
  84764. */
  84765. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  84766. /**
  84767. * Disables noise blur
  84768. */
  84769. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  84770. /**
  84771. * Sets the HighlightsGain amount
  84772. * @param amount amount of HighlightsGain
  84773. */
  84774. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  84775. this._highlightsGain = amount;
  84776. };
  84777. /**
  84778. * Sets the HighlightsThreshold amount
  84779. * @param amount amount of HighlightsThreshold
  84780. */
  84781. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  84782. if (this._highlightsGain === -1) {
  84783. this._highlightsGain = 1.0;
  84784. }
  84785. this._highlightsThreshold = amount;
  84786. };
  84787. /**
  84788. * Disables highlights
  84789. */
  84790. LensRenderingPipeline.prototype.disableHighlights = function () {
  84791. this._highlightsGain = -1;
  84792. };
  84793. /**
  84794. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  84795. * @param disableDepthRender If the scens depth rendering should be disabled (default: false)
  84796. */
  84797. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  84798. if (disableDepthRender === void 0) { disableDepthRender = false; }
  84799. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  84800. this._chromaticAberrationPostProcess = null;
  84801. this._highlightsPostProcess = null;
  84802. this._depthOfFieldPostProcess = null;
  84803. this._grainTexture.dispose();
  84804. if (disableDepthRender) {
  84805. this._scene.disableDepthRenderer();
  84806. }
  84807. };
  84808. // colors shifting and distortion
  84809. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  84810. var _this = this;
  84811. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  84812. [], // samplers
  84813. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  84814. this._chromaticAberrationPostProcess.onApply = function (effect) {
  84815. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  84816. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  84817. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  84818. effect.setFloat('radialIntensity', 1);
  84819. effect.setFloat2('direction', 17, 17);
  84820. effect.setFloat2('centerPosition', 0.5, 0.5);
  84821. };
  84822. };
  84823. // highlights enhancing
  84824. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  84825. var _this = this;
  84826. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  84827. [], // samplers
  84828. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  84829. this._highlightsPostProcess.onApply = function (effect) {
  84830. effect.setFloat('gain', _this._highlightsGain);
  84831. effect.setFloat('threshold', _this._highlightsThreshold);
  84832. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  84833. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  84834. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  84835. };
  84836. };
  84837. // colors shifting and distortion
  84838. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  84839. var _this = this;
  84840. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  84841. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  84842. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  84843. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  84844. this._depthOfFieldPostProcess.onApply = function (effect) {
  84845. effect.setTexture("depthSampler", _this._depthTexture);
  84846. effect.setTexture("grainSampler", _this._grainTexture);
  84847. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  84848. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  84849. effect.setFloat('grain_amount', _this._grainAmount);
  84850. effect.setBool('blur_noise', _this._blurNoise);
  84851. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  84852. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  84853. effect.setFloat('distortion', _this._distortion);
  84854. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  84855. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  84856. effect.setFloat('aperture', _this._dofAperture);
  84857. effect.setFloat('darken', _this._dofDarken);
  84858. effect.setFloat('edge_blur', _this._edgeBlur);
  84859. effect.setBool('highlights', (_this._highlightsGain !== -1));
  84860. if (_this._scene.activeCamera) {
  84861. effect.setFloat('near', _this._scene.activeCamera.minZ);
  84862. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  84863. }
  84864. };
  84865. };
  84866. // creates a black and white random noise texture, 512x512
  84867. LensRenderingPipeline.prototype._createGrainTexture = function () {
  84868. var size = 512;
  84869. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84870. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  84871. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  84872. var context = this._grainTexture.getContext();
  84873. var rand = function (min, max) {
  84874. return Math.random() * (max - min) + min;
  84875. };
  84876. var value;
  84877. for (var x = 0; x < size; x++) {
  84878. for (var y = 0; y < size; y++) {
  84879. value = Math.floor(rand(0.42, 0.58) * 255);
  84880. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  84881. context.fillRect(x, y, 1, 1);
  84882. }
  84883. }
  84884. this._grainTexture.update(false);
  84885. };
  84886. return LensRenderingPipeline;
  84887. }(BABYLON.PostProcessRenderPipeline));
  84888. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  84889. })(BABYLON || (BABYLON = {}));
  84890. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  84891. var BABYLON;
  84892. (function (BABYLON) {
  84893. /**
  84894. * Standard rendering pipeline
  84895. * Default pipeline should be used going forward but the standard pipeline will be kept for backwards compatibility.
  84896. * @see https://doc.babylonjs.com/how_to/using_standard_rendering_pipeline
  84897. */
  84898. var StandardRenderingPipeline = /** @class */ (function (_super) {
  84899. __extends(StandardRenderingPipeline, _super);
  84900. /**
  84901. * Default pipeline should be used going forward but the standard pipeline will be kept for backwards compatibility.
  84902. * @constructor
  84903. * @param name The rendering pipeline name
  84904. * @param scene The scene linked to this pipeline
  84905. * @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)
  84906. * @param originalPostProcess the custom original color post-process. Must be "reusable". Can be null.
  84907. * @param cameras The array of cameras that the rendering pipeline will be attached to
  84908. */
  84909. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  84910. if (originalPostProcess === void 0) { originalPostProcess = null; }
  84911. var _this = _super.call(this, scene.getEngine(), name) || this;
  84912. /**
  84913. * Post-process used to down scale an image x4
  84914. */
  84915. _this.downSampleX4PostProcess = null;
  84916. /**
  84917. * Post-process used to calculate the illuminated surfaces controlled by a threshold
  84918. */
  84919. _this.brightPassPostProcess = null;
  84920. /**
  84921. * Post-process array storing all the horizontal blur post-processes used by the pipeline
  84922. */
  84923. _this.blurHPostProcesses = [];
  84924. /**
  84925. * Post-process array storing all the vertical blur post-processes used by the pipeline
  84926. */
  84927. _this.blurVPostProcesses = [];
  84928. /**
  84929. * Post-process used to add colors of 2 textures (typically brightness + real scene color)
  84930. */
  84931. _this.textureAdderPostProcess = null;
  84932. /**
  84933. * Post-process used to create volumetric lighting effect
  84934. */
  84935. _this.volumetricLightPostProcess = null;
  84936. /**
  84937. * Post-process used to smooth the previous volumetric light post-process on the X axis
  84938. */
  84939. _this.volumetricLightSmoothXPostProcess = null;
  84940. /**
  84941. * Post-process used to smooth the previous volumetric light post-process on the Y axis
  84942. */
  84943. _this.volumetricLightSmoothYPostProcess = null;
  84944. /**
  84945. * Post-process used to merge the volumetric light effect and the real scene color
  84946. */
  84947. _this.volumetricLightMergePostProces = null;
  84948. /**
  84949. * Post-process used to store the final volumetric light post-process (attach/detach for debug purpose)
  84950. */
  84951. _this.volumetricLightFinalPostProcess = null;
  84952. /**
  84953. * Base post-process used to calculate the average luminance of the final image for HDR
  84954. */
  84955. _this.luminancePostProcess = null;
  84956. /**
  84957. * Post-processes used to create down sample post-processes in order to get
  84958. * the average luminance of the final image for HDR
  84959. * Array of length "StandardRenderingPipeline.LuminanceSteps"
  84960. */
  84961. _this.luminanceDownSamplePostProcesses = [];
  84962. /**
  84963. * Post-process used to create a HDR effect (light adaptation)
  84964. */
  84965. _this.hdrPostProcess = null;
  84966. /**
  84967. * Post-process used to store the final texture adder post-process (attach/detach for debug purpose)
  84968. */
  84969. _this.textureAdderFinalPostProcess = null;
  84970. /**
  84971. * Post-process used to store the final lens flare post-process (attach/detach for debug purpose)
  84972. */
  84973. _this.lensFlareFinalPostProcess = null;
  84974. /**
  84975. * Post-process used to merge the final HDR post-process and the real scene color
  84976. */
  84977. _this.hdrFinalPostProcess = null;
  84978. /**
  84979. * Post-process used to create a lens flare effect
  84980. */
  84981. _this.lensFlarePostProcess = null;
  84982. /**
  84983. * Post-process that merges the result of the lens flare post-process and the real scene color
  84984. */
  84985. _this.lensFlareComposePostProcess = null;
  84986. /**
  84987. * Post-process used to create a motion blur effect
  84988. */
  84989. _this.motionBlurPostProcess = null;
  84990. /**
  84991. * Post-process used to create a depth of field effect
  84992. */
  84993. _this.depthOfFieldPostProcess = null;
  84994. /**
  84995. * The Fast Approximate Anti-Aliasing post process which attemps to remove aliasing from an image.
  84996. */
  84997. _this.fxaaPostProcess = null;
  84998. // Values
  84999. /**
  85000. * Represents the brightness threshold in order to configure the illuminated surfaces
  85001. */
  85002. _this.brightThreshold = 1.0;
  85003. /**
  85004. * Configures the blur intensity used for surexposed surfaces are highlighted surfaces (light halo)
  85005. */
  85006. _this.blurWidth = 512.0;
  85007. /**
  85008. * Sets if the blur for highlighted surfaces must be only horizontal
  85009. */
  85010. _this.horizontalBlur = false;
  85011. /**
  85012. * Sets the overall exposure used by the pipeline
  85013. */
  85014. _this.exposure = 1.0;
  85015. /**
  85016. * Texture used typically to simulate "dirty" on camera lens
  85017. */
  85018. _this.lensTexture = null;
  85019. /**
  85020. * Represents the offset coefficient based on Rayleigh principle. Typically in interval [-0.2, 0.2]
  85021. */
  85022. _this.volumetricLightCoefficient = 0.2;
  85023. /**
  85024. * The overall power of volumetric lights, typically in interval [0, 10] maximum
  85025. */
  85026. _this.volumetricLightPower = 4.0;
  85027. /**
  85028. * Used the set the blur intensity to smooth the volumetric lights
  85029. */
  85030. _this.volumetricLightBlurScale = 64.0;
  85031. /**
  85032. * Light (spot or directional) used to generate the volumetric lights rays
  85033. * The source light must have a shadow generate so the pipeline can get its
  85034. * depth map
  85035. */
  85036. _this.sourceLight = null;
  85037. /**
  85038. * For eye adaptation, represents the minimum luminance the eye can see
  85039. */
  85040. _this.hdrMinimumLuminance = 1.0;
  85041. /**
  85042. * For eye adaptation, represents the decrease luminance speed
  85043. */
  85044. _this.hdrDecreaseRate = 0.5;
  85045. /**
  85046. * For eye adaptation, represents the increase luminance speed
  85047. */
  85048. _this.hdrIncreaseRate = 0.5;
  85049. /**
  85050. * Lens color texture used by the lens flare effect. Mandatory if lens flare effect enabled
  85051. */
  85052. _this.lensColorTexture = null;
  85053. /**
  85054. * The overall strengh for the lens flare effect
  85055. */
  85056. _this.lensFlareStrength = 20.0;
  85057. /**
  85058. * Dispersion coefficient for lens flare ghosts
  85059. */
  85060. _this.lensFlareGhostDispersal = 1.4;
  85061. /**
  85062. * Main lens flare halo width
  85063. */
  85064. _this.lensFlareHaloWidth = 0.7;
  85065. /**
  85066. * Based on the lens distortion effect, defines how much the lens flare result
  85067. * is distorted
  85068. */
  85069. _this.lensFlareDistortionStrength = 16.0;
  85070. /**
  85071. * Lens star texture must be used to simulate rays on the flares and is available
  85072. * in the documentation
  85073. */
  85074. _this.lensStarTexture = null;
  85075. /**
  85076. * As the "lensTexture" (can be the same texture or different), it is used to apply the lens
  85077. * flare effect by taking account of the dirt texture
  85078. */
  85079. _this.lensFlareDirtTexture = null;
  85080. /**
  85081. * Represents the focal length for the depth of field effect
  85082. */
  85083. _this.depthOfFieldDistance = 10.0;
  85084. /**
  85085. * Represents the blur intensity for the blurred part of the depth of field effect
  85086. */
  85087. _this.depthOfFieldBlurWidth = 64.0;
  85088. /**
  85089. * For motion blur, defines how much the image is blurred by the movement
  85090. */
  85091. _this.motionStrength = 1.0;
  85092. /**
  85093. * List of animations for the pipeline (IAnimatable implementation)
  85094. */
  85095. _this.animations = [];
  85096. _this._currentDepthOfFieldSource = null;
  85097. _this._hdrCurrentLuminance = 1.0;
  85098. // Getters and setters
  85099. _this._bloomEnabled = false;
  85100. _this._depthOfFieldEnabled = false;
  85101. _this._vlsEnabled = false;
  85102. _this._lensFlareEnabled = false;
  85103. _this._hdrEnabled = false;
  85104. _this._motionBlurEnabled = false;
  85105. _this._fxaaEnabled = false;
  85106. _this._motionBlurSamples = 64.0;
  85107. _this._volumetricLightStepsCount = 50.0;
  85108. _this._samples = 1;
  85109. _this._cameras = cameras || [];
  85110. // Initialize
  85111. _this._scene = scene;
  85112. _this._basePostProcess = originalPostProcess;
  85113. _this._ratio = ratio;
  85114. // Misc
  85115. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  85116. // Finish
  85117. scene.postProcessRenderPipelineManager.addPipeline(_this);
  85118. _this._buildPipeline();
  85119. return _this;
  85120. }
  85121. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  85122. /**
  85123. * @ignore
  85124. * Specifies if the bloom pipeline is enabled
  85125. */
  85126. get: function () {
  85127. return this._bloomEnabled;
  85128. },
  85129. set: function (enabled) {
  85130. if (this._bloomEnabled === enabled) {
  85131. return;
  85132. }
  85133. this._bloomEnabled = enabled;
  85134. this._buildPipeline();
  85135. },
  85136. enumerable: true,
  85137. configurable: true
  85138. });
  85139. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  85140. /**
  85141. * @ignore
  85142. * Specifies if the depth of field pipeline is enabed
  85143. */
  85144. get: function () {
  85145. return this._depthOfFieldEnabled;
  85146. },
  85147. set: function (enabled) {
  85148. if (this._depthOfFieldEnabled === enabled) {
  85149. return;
  85150. }
  85151. this._depthOfFieldEnabled = enabled;
  85152. this._buildPipeline();
  85153. },
  85154. enumerable: true,
  85155. configurable: true
  85156. });
  85157. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  85158. /**
  85159. * @ignore
  85160. * Specifies if the lens flare pipeline is enabed
  85161. */
  85162. get: function () {
  85163. return this._lensFlareEnabled;
  85164. },
  85165. set: function (enabled) {
  85166. if (this._lensFlareEnabled === enabled) {
  85167. return;
  85168. }
  85169. this._lensFlareEnabled = enabled;
  85170. this._buildPipeline();
  85171. },
  85172. enumerable: true,
  85173. configurable: true
  85174. });
  85175. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  85176. /**
  85177. * @ignore
  85178. * Specifies if the HDR pipeline is enabled
  85179. */
  85180. get: function () {
  85181. return this._hdrEnabled;
  85182. },
  85183. set: function (enabled) {
  85184. if (this._hdrEnabled === enabled) {
  85185. return;
  85186. }
  85187. this._hdrEnabled = enabled;
  85188. this._buildPipeline();
  85189. },
  85190. enumerable: true,
  85191. configurable: true
  85192. });
  85193. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  85194. /**
  85195. * @ignore
  85196. * Specifies if the volumetric lights scattering effect is enabled
  85197. */
  85198. get: function () {
  85199. return this._vlsEnabled;
  85200. },
  85201. set: function (enabled) {
  85202. if (this._vlsEnabled === enabled) {
  85203. return;
  85204. }
  85205. if (enabled) {
  85206. var geometry = this._scene.enableGeometryBufferRenderer();
  85207. if (!geometry) {
  85208. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  85209. return;
  85210. }
  85211. }
  85212. this._vlsEnabled = enabled;
  85213. this._buildPipeline();
  85214. },
  85215. enumerable: true,
  85216. configurable: true
  85217. });
  85218. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  85219. /**
  85220. * @ignore
  85221. * Specifies if the motion blur effect is enabled
  85222. */
  85223. get: function () {
  85224. return this._motionBlurEnabled;
  85225. },
  85226. set: function (enabled) {
  85227. if (this._motionBlurEnabled === enabled) {
  85228. return;
  85229. }
  85230. this._motionBlurEnabled = enabled;
  85231. this._buildPipeline();
  85232. },
  85233. enumerable: true,
  85234. configurable: true
  85235. });
  85236. Object.defineProperty(StandardRenderingPipeline.prototype, "fxaaEnabled", {
  85237. /**
  85238. * Specifies if anti-aliasing is enabled
  85239. */
  85240. get: function () {
  85241. return this._fxaaEnabled;
  85242. },
  85243. set: function (enabled) {
  85244. if (this._fxaaEnabled === enabled) {
  85245. return;
  85246. }
  85247. this._fxaaEnabled = enabled;
  85248. this._buildPipeline();
  85249. },
  85250. enumerable: true,
  85251. configurable: true
  85252. });
  85253. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  85254. /**
  85255. * Specifies the number of steps used to calculate the volumetric lights
  85256. * Typically in interval [50, 200]
  85257. */
  85258. get: function () {
  85259. return this._volumetricLightStepsCount;
  85260. },
  85261. set: function (count) {
  85262. if (this.volumetricLightPostProcess) {
  85263. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  85264. }
  85265. this._volumetricLightStepsCount = count;
  85266. },
  85267. enumerable: true,
  85268. configurable: true
  85269. });
  85270. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  85271. /**
  85272. * Specifies the number of samples used for the motion blur effect
  85273. * Typically in interval [16, 64]
  85274. */
  85275. get: function () {
  85276. return this._motionBlurSamples;
  85277. },
  85278. set: function (samples) {
  85279. if (this.motionBlurPostProcess) {
  85280. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  85281. }
  85282. this._motionBlurSamples = samples;
  85283. },
  85284. enumerable: true,
  85285. configurable: true
  85286. });
  85287. Object.defineProperty(StandardRenderingPipeline.prototype, "samples", {
  85288. /**
  85289. * Specifies MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  85290. */
  85291. get: function () {
  85292. return this._samples;
  85293. },
  85294. set: function (sampleCount) {
  85295. if (this._samples === sampleCount) {
  85296. return;
  85297. }
  85298. this._samples = sampleCount;
  85299. this._buildPipeline();
  85300. },
  85301. enumerable: true,
  85302. configurable: true
  85303. });
  85304. StandardRenderingPipeline.prototype._buildPipeline = function () {
  85305. var _this = this;
  85306. var ratio = this._ratio;
  85307. var scene = this._scene;
  85308. this._disposePostProcesses();
  85309. this._reset();
  85310. // Create pass post-process
  85311. if (!this._basePostProcess) {
  85312. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  85313. this.originalPostProcess.onApply = function (effect) {
  85314. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  85315. };
  85316. }
  85317. else {
  85318. this.originalPostProcess = this._basePostProcess;
  85319. }
  85320. if (this._bloomEnabled || this._vlsEnabled || this._lensFlareEnabled || this._depthOfFieldEnabled || this._motionBlurEnabled) {
  85321. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  85322. }
  85323. this._currentDepthOfFieldSource = this.originalPostProcess;
  85324. if (this._bloomEnabled) {
  85325. // Create down sample X4 post-process
  85326. this._createDownSampleX4PostProcess(scene, ratio / 2);
  85327. // Create bright pass post-process
  85328. this._createBrightPassPostProcess(scene, ratio / 2);
  85329. // Create gaussian blur post-processes (down sampling blurs)
  85330. this._createBlurPostProcesses(scene, ratio / 4, 1);
  85331. // Create texture adder post-process
  85332. this._createTextureAdderPostProcess(scene, ratio);
  85333. // Create depth-of-field source post-process
  85334. 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);
  85335. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  85336. }
  85337. if (this._vlsEnabled) {
  85338. // Create volumetric light
  85339. this._createVolumetricLightPostProcess(scene, ratio);
  85340. // Create volumetric light final post-process
  85341. 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);
  85342. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  85343. }
  85344. if (this._lensFlareEnabled) {
  85345. // Create lens flare post-process
  85346. this._createLensFlarePostProcess(scene, ratio);
  85347. // Create depth-of-field source post-process post lens-flare and disable it now
  85348. 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);
  85349. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  85350. }
  85351. if (this._hdrEnabled) {
  85352. // Create luminance
  85353. this._createLuminancePostProcesses(scene, this._floatTextureType);
  85354. // Create HDR
  85355. this._createHdrPostProcess(scene, ratio);
  85356. // Create depth-of-field source post-process post hdr and disable it now
  85357. 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);
  85358. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  85359. }
  85360. if (this._depthOfFieldEnabled) {
  85361. // Create gaussian blur used by depth-of-field
  85362. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  85363. // Create depth-of-field post-process
  85364. this._createDepthOfFieldPostProcess(scene, ratio);
  85365. }
  85366. if (this._motionBlurEnabled) {
  85367. // Create motion blur post-process
  85368. this._createMotionBlurPostProcess(scene, ratio);
  85369. }
  85370. if (this._fxaaEnabled) {
  85371. // Create fxaa post-process
  85372. this.fxaaPostProcess = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  85373. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRFxaa", function () { return _this.fxaaPostProcess; }, true));
  85374. }
  85375. if (this._cameras !== null) {
  85376. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  85377. }
  85378. if (!this._enableMSAAOnFirstPostProcess(this._samples) && this._samples > 1) {
  85379. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  85380. }
  85381. };
  85382. // Down Sample X4 Post-Processs
  85383. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  85384. var _this = this;
  85385. var downSampleX4Offsets = new Array(32);
  85386. 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);
  85387. this.downSampleX4PostProcess.onApply = function (effect) {
  85388. var id = 0;
  85389. var width = _this.downSampleX4PostProcess.width;
  85390. var height = _this.downSampleX4PostProcess.height;
  85391. for (var i = -2; i < 2; i++) {
  85392. for (var j = -2; j < 2; j++) {
  85393. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  85394. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  85395. id += 2;
  85396. }
  85397. }
  85398. effect.setArray2("dsOffsets", downSampleX4Offsets);
  85399. };
  85400. // Add to pipeline
  85401. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  85402. };
  85403. // Brightpass Post-Process
  85404. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  85405. var _this = this;
  85406. var brightOffsets = new Array(8);
  85407. 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);
  85408. this.brightPassPostProcess.onApply = function (effect) {
  85409. var sU = (1.0 / _this.brightPassPostProcess.width);
  85410. var sV = (1.0 / _this.brightPassPostProcess.height);
  85411. brightOffsets[0] = -0.5 * sU;
  85412. brightOffsets[1] = 0.5 * sV;
  85413. brightOffsets[2] = 0.5 * sU;
  85414. brightOffsets[3] = 0.5 * sV;
  85415. brightOffsets[4] = -0.5 * sU;
  85416. brightOffsets[5] = -0.5 * sV;
  85417. brightOffsets[6] = 0.5 * sU;
  85418. brightOffsets[7] = -0.5 * sV;
  85419. effect.setArray2("dsOffsets", brightOffsets);
  85420. effect.setFloat("brightThreshold", _this.brightThreshold);
  85421. };
  85422. // Add to pipeline
  85423. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  85424. };
  85425. // Create blur H&V post-processes
  85426. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  85427. var _this = this;
  85428. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  85429. var engine = scene.getEngine();
  85430. 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);
  85431. 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);
  85432. blurX.onActivateObservable.add(function () {
  85433. var dw = blurX.width / engine.getRenderWidth();
  85434. blurX.kernel = _this[blurWidthKey] * dw;
  85435. });
  85436. blurY.onActivateObservable.add(function () {
  85437. var dw = blurY.height / engine.getRenderHeight();
  85438. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  85439. });
  85440. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  85441. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  85442. this.blurHPostProcesses.push(blurX);
  85443. this.blurVPostProcesses.push(blurY);
  85444. };
  85445. // Create texture adder post-process
  85446. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  85447. var _this = this;
  85448. 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);
  85449. this.textureAdderPostProcess.onApply = function (effect) {
  85450. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  85451. effect.setTexture("lensSampler", _this.lensTexture);
  85452. effect.setFloat("exposure", _this.exposure);
  85453. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  85454. };
  85455. // Add to pipeline
  85456. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  85457. };
  85458. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  85459. var _this = this;
  85460. var geometryRenderer = scene.enableGeometryBufferRenderer();
  85461. geometryRenderer.enablePosition = true;
  85462. var geometry = geometryRenderer.getGBuffer();
  85463. // Base post-process
  85464. 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));
  85465. var depthValues = BABYLON.Vector2.Zero();
  85466. this.volumetricLightPostProcess.onApply = function (effect) {
  85467. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  85468. var generator = _this.sourceLight.getShadowGenerator();
  85469. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  85470. effect.setTexture("positionSampler", geometry.textures[2]);
  85471. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  85472. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  85473. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  85474. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  85475. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  85476. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  85477. depthValues.x = _this.sourceLight.getDepthMinZ(_this._scene.activeCamera);
  85478. depthValues.y = _this.sourceLight.getDepthMaxZ(_this._scene.activeCamera);
  85479. effect.setVector2("depthValues", depthValues);
  85480. }
  85481. };
  85482. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  85483. // Smooth
  85484. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  85485. // Merge
  85486. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  85487. this.volumetricLightMergePostProces.onApply = function (effect) {
  85488. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  85489. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  85490. };
  85491. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  85492. };
  85493. // Create luminance
  85494. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  85495. var _this = this;
  85496. // Create luminance
  85497. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  85498. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  85499. var offsets = [];
  85500. this.luminancePostProcess.onApply = function (effect) {
  85501. var sU = (1.0 / _this.luminancePostProcess.width);
  85502. var sV = (1.0 / _this.luminancePostProcess.height);
  85503. offsets[0] = -0.5 * sU;
  85504. offsets[1] = 0.5 * sV;
  85505. offsets[2] = 0.5 * sU;
  85506. offsets[3] = 0.5 * sV;
  85507. offsets[4] = -0.5 * sU;
  85508. offsets[5] = -0.5 * sV;
  85509. offsets[6] = 0.5 * sU;
  85510. offsets[7] = -0.5 * sV;
  85511. effect.setArray2("lumOffsets", offsets);
  85512. };
  85513. // Add to pipeline
  85514. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  85515. // Create down sample luminance
  85516. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  85517. var size = Math.pow(3, i);
  85518. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  85519. if (i === 0) {
  85520. defines += "#define FINAL_DOWN_SAMPLER";
  85521. }
  85522. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  85523. this.luminanceDownSamplePostProcesses.push(postProcess);
  85524. }
  85525. // Create callbacks and add effects
  85526. var lastLuminance = this.luminancePostProcess;
  85527. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  85528. var downSampleOffsets = new Array(18);
  85529. pp.onApply = function (effect) {
  85530. if (!lastLuminance) {
  85531. return;
  85532. }
  85533. var id = 0;
  85534. for (var x = -1; x < 2; x++) {
  85535. for (var y = -1; y < 2; y++) {
  85536. downSampleOffsets[id] = x / lastLuminance.width;
  85537. downSampleOffsets[id + 1] = y / lastLuminance.height;
  85538. id += 2;
  85539. }
  85540. }
  85541. effect.setArray2("dsOffsets", downSampleOffsets);
  85542. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  85543. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  85544. lastLuminance = _this.luminancePostProcess;
  85545. }
  85546. else {
  85547. lastLuminance = pp;
  85548. }
  85549. };
  85550. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  85551. pp.onAfterRender = function (effect) {
  85552. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  85553. 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);
  85554. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  85555. };
  85556. }
  85557. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  85558. });
  85559. };
  85560. // Create HDR post-process
  85561. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  85562. var _this = this;
  85563. 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);
  85564. var outputLiminance = 1;
  85565. var time = 0;
  85566. var lastTime = 0;
  85567. this.hdrPostProcess.onApply = function (effect) {
  85568. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  85569. time += scene.getEngine().getDeltaTime();
  85570. if (outputLiminance < 0) {
  85571. outputLiminance = _this._hdrCurrentLuminance;
  85572. }
  85573. else {
  85574. var dt = (lastTime - time) / 1000.0;
  85575. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  85576. outputLiminance += _this.hdrDecreaseRate * dt;
  85577. }
  85578. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  85579. outputLiminance -= _this.hdrIncreaseRate * dt;
  85580. }
  85581. else {
  85582. outputLiminance = _this._hdrCurrentLuminance;
  85583. }
  85584. }
  85585. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  85586. effect.setFloat("averageLuminance", outputLiminance);
  85587. lastTime = time;
  85588. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  85589. };
  85590. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  85591. };
  85592. // Create lens flare post-process
  85593. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  85594. var _this = this;
  85595. 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);
  85596. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  85597. this._createBlurPostProcesses(scene, ratio / 4, 2);
  85598. 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);
  85599. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  85600. var resolution = new BABYLON.Vector2(0, 0);
  85601. // Lens flare
  85602. this.lensFlarePostProcess.onApply = function (effect) {
  85603. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  85604. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  85605. effect.setFloat("strength", _this.lensFlareStrength);
  85606. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  85607. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  85608. // Shift
  85609. resolution.x = _this.lensFlarePostProcess.width;
  85610. resolution.y = _this.lensFlarePostProcess.height;
  85611. effect.setVector2("resolution", resolution);
  85612. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  85613. };
  85614. // Compose
  85615. 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);
  85616. 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);
  85617. this.lensFlareComposePostProcess.onApply = function (effect) {
  85618. if (!_this._scene.activeCamera) {
  85619. return;
  85620. }
  85621. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  85622. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  85623. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  85624. // Lens start rotation matrix
  85625. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  85626. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  85627. 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));
  85628. camRot *= 4.0;
  85629. 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);
  85630. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  85631. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  85632. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  85633. };
  85634. };
  85635. // Create depth-of-field post-process
  85636. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  85637. var _this = this;
  85638. 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);
  85639. this.depthOfFieldPostProcess.onApply = function (effect) {
  85640. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  85641. effect.setTexture("depthSampler", _this._getDepthTexture());
  85642. effect.setFloat("distance", _this.depthOfFieldDistance);
  85643. };
  85644. // Add to pipeline
  85645. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  85646. };
  85647. // Create motion blur post-process
  85648. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  85649. var _this = this;
  85650. 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);
  85651. var motionScale = 0;
  85652. var prevViewProjection = BABYLON.Matrix.Identity();
  85653. var invViewProjection = BABYLON.Matrix.Identity();
  85654. var viewProjection = BABYLON.Matrix.Identity();
  85655. var screenSize = BABYLON.Vector2.Zero();
  85656. this.motionBlurPostProcess.onApply = function (effect) {
  85657. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  85658. viewProjection.invertToRef(invViewProjection);
  85659. effect.setMatrix("inverseViewProjection", invViewProjection);
  85660. effect.setMatrix("prevViewProjection", prevViewProjection);
  85661. prevViewProjection = viewProjection;
  85662. screenSize.x = _this.motionBlurPostProcess.width;
  85663. screenSize.y = _this.motionBlurPostProcess.height;
  85664. effect.setVector2("screenSize", screenSize);
  85665. motionScale = scene.getEngine().getFps() / 60.0;
  85666. effect.setFloat("motionScale", motionScale);
  85667. effect.setFloat("motionStrength", _this.motionStrength);
  85668. effect.setTexture("depthSampler", _this._getDepthTexture());
  85669. };
  85670. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  85671. };
  85672. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  85673. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  85674. var renderer = this._scene.enableGeometryBufferRenderer();
  85675. return renderer.getGBuffer().textures[0];
  85676. }
  85677. return this._scene.enableDepthRenderer().getDepthMap();
  85678. };
  85679. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  85680. for (var i = 0; i < this._cameras.length; i++) {
  85681. var camera = this._cameras[i];
  85682. if (this.originalPostProcess) {
  85683. this.originalPostProcess.dispose(camera);
  85684. }
  85685. if (this.downSampleX4PostProcess) {
  85686. this.downSampleX4PostProcess.dispose(camera);
  85687. }
  85688. if (this.brightPassPostProcess) {
  85689. this.brightPassPostProcess.dispose(camera);
  85690. }
  85691. if (this.textureAdderPostProcess) {
  85692. this.textureAdderPostProcess.dispose(camera);
  85693. }
  85694. if (this.textureAdderFinalPostProcess) {
  85695. this.textureAdderFinalPostProcess.dispose(camera);
  85696. }
  85697. if (this.volumetricLightPostProcess) {
  85698. this.volumetricLightPostProcess.dispose(camera);
  85699. }
  85700. if (this.volumetricLightSmoothXPostProcess) {
  85701. this.volumetricLightSmoothXPostProcess.dispose(camera);
  85702. }
  85703. if (this.volumetricLightSmoothYPostProcess) {
  85704. this.volumetricLightSmoothYPostProcess.dispose(camera);
  85705. }
  85706. if (this.volumetricLightMergePostProces) {
  85707. this.volumetricLightMergePostProces.dispose(camera);
  85708. }
  85709. if (this.volumetricLightFinalPostProcess) {
  85710. this.volumetricLightFinalPostProcess.dispose(camera);
  85711. }
  85712. if (this.lensFlarePostProcess) {
  85713. this.lensFlarePostProcess.dispose(camera);
  85714. }
  85715. if (this.lensFlareComposePostProcess) {
  85716. this.lensFlareComposePostProcess.dispose(camera);
  85717. }
  85718. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  85719. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  85720. }
  85721. if (this.luminancePostProcess) {
  85722. this.luminancePostProcess.dispose(camera);
  85723. }
  85724. if (this.hdrPostProcess) {
  85725. this.hdrPostProcess.dispose(camera);
  85726. }
  85727. if (this.hdrFinalPostProcess) {
  85728. this.hdrFinalPostProcess.dispose(camera);
  85729. }
  85730. if (this.depthOfFieldPostProcess) {
  85731. this.depthOfFieldPostProcess.dispose(camera);
  85732. }
  85733. if (this.motionBlurPostProcess) {
  85734. this.motionBlurPostProcess.dispose(camera);
  85735. }
  85736. if (this.fxaaPostProcess) {
  85737. this.fxaaPostProcess.dispose(camera);
  85738. }
  85739. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  85740. this.blurHPostProcesses[j].dispose(camera);
  85741. }
  85742. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  85743. this.blurVPostProcesses[j].dispose(camera);
  85744. }
  85745. }
  85746. this.originalPostProcess = null;
  85747. this.downSampleX4PostProcess = null;
  85748. this.brightPassPostProcess = null;
  85749. this.textureAdderPostProcess = null;
  85750. this.textureAdderFinalPostProcess = null;
  85751. this.volumetricLightPostProcess = null;
  85752. this.volumetricLightSmoothXPostProcess = null;
  85753. this.volumetricLightSmoothYPostProcess = null;
  85754. this.volumetricLightMergePostProces = null;
  85755. this.volumetricLightFinalPostProcess = null;
  85756. this.lensFlarePostProcess = null;
  85757. this.lensFlareComposePostProcess = null;
  85758. this.luminancePostProcess = null;
  85759. this.hdrPostProcess = null;
  85760. this.hdrFinalPostProcess = null;
  85761. this.depthOfFieldPostProcess = null;
  85762. this.motionBlurPostProcess = null;
  85763. this.fxaaPostProcess = null;
  85764. this.luminanceDownSamplePostProcesses = [];
  85765. this.blurHPostProcesses = [];
  85766. this.blurVPostProcesses = [];
  85767. };
  85768. /**
  85769. * Dispose of the pipeline and stop all post processes
  85770. */
  85771. StandardRenderingPipeline.prototype.dispose = function () {
  85772. this._disposePostProcesses();
  85773. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  85774. _super.prototype.dispose.call(this);
  85775. };
  85776. /**
  85777. * Serialize the rendering pipeline (Used when exporting)
  85778. * @returns the serialized object
  85779. */
  85780. StandardRenderingPipeline.prototype.serialize = function () {
  85781. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  85782. if (this.sourceLight) {
  85783. serializationObject.sourceLightId = this.sourceLight.id;
  85784. }
  85785. serializationObject.customType = "StandardRenderingPipeline";
  85786. return serializationObject;
  85787. };
  85788. /**
  85789. * Parse the serialized pipeline
  85790. * @param source Source pipeline.
  85791. * @param scene The scene to load the pipeline to.
  85792. * @param rootUrl The URL of the serialized pipeline.
  85793. * @returns An instantiated pipeline from the serialized object.
  85794. */
  85795. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  85796. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  85797. if (source.sourceLightId) {
  85798. p.sourceLight = scene.getLightByID(source.sourceLightId);
  85799. }
  85800. return p;
  85801. };
  85802. /**
  85803. * Luminance steps
  85804. */
  85805. StandardRenderingPipeline.LuminanceSteps = 6;
  85806. __decorate([
  85807. BABYLON.serialize()
  85808. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  85809. __decorate([
  85810. BABYLON.serialize()
  85811. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  85812. __decorate([
  85813. BABYLON.serialize()
  85814. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  85815. __decorate([
  85816. BABYLON.serialize()
  85817. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  85818. __decorate([
  85819. BABYLON.serializeAsTexture("lensTexture")
  85820. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  85821. __decorate([
  85822. BABYLON.serialize()
  85823. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  85824. __decorate([
  85825. BABYLON.serialize()
  85826. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  85827. __decorate([
  85828. BABYLON.serialize()
  85829. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  85830. __decorate([
  85831. BABYLON.serialize()
  85832. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  85833. __decorate([
  85834. BABYLON.serialize()
  85835. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  85836. __decorate([
  85837. BABYLON.serialize()
  85838. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  85839. __decorate([
  85840. BABYLON.serializeAsTexture("lensColorTexture")
  85841. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  85842. __decorate([
  85843. BABYLON.serialize()
  85844. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  85845. __decorate([
  85846. BABYLON.serialize()
  85847. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  85848. __decorate([
  85849. BABYLON.serialize()
  85850. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  85851. __decorate([
  85852. BABYLON.serialize()
  85853. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  85854. __decorate([
  85855. BABYLON.serializeAsTexture("lensStarTexture")
  85856. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  85857. __decorate([
  85858. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  85859. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  85860. __decorate([
  85861. BABYLON.serialize()
  85862. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  85863. __decorate([
  85864. BABYLON.serialize()
  85865. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  85866. __decorate([
  85867. BABYLON.serialize()
  85868. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  85869. __decorate([
  85870. BABYLON.serialize()
  85871. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  85872. __decorate([
  85873. BABYLON.serialize()
  85874. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  85875. __decorate([
  85876. BABYLON.serialize()
  85877. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  85878. __decorate([
  85879. BABYLON.serialize()
  85880. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  85881. __decorate([
  85882. BABYLON.serialize()
  85883. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  85884. __decorate([
  85885. BABYLON.serialize()
  85886. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  85887. __decorate([
  85888. BABYLON.serialize()
  85889. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  85890. __decorate([
  85891. BABYLON.serialize()
  85892. ], StandardRenderingPipeline.prototype, "fxaaEnabled", null);
  85893. __decorate([
  85894. BABYLON.serialize()
  85895. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  85896. __decorate([
  85897. BABYLON.serialize()
  85898. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  85899. __decorate([
  85900. BABYLON.serialize()
  85901. ], StandardRenderingPipeline.prototype, "samples", null);
  85902. return StandardRenderingPipeline;
  85903. }(BABYLON.PostProcessRenderPipeline));
  85904. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  85905. })(BABYLON || (BABYLON = {}));
  85906. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  85907. var BABYLON;
  85908. (function (BABYLON) {
  85909. /**
  85910. * Fxaa post process
  85911. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#fxaa
  85912. */
  85913. var FxaaPostProcess = /** @class */ (function (_super) {
  85914. __extends(FxaaPostProcess, _super);
  85915. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  85916. if (camera === void 0) { camera = null; }
  85917. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85918. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  85919. var defines = _this._getDefines();
  85920. _this.updateEffect(defines);
  85921. _this.onApplyObservable.add(function (effect) {
  85922. var texelSize = _this.texelSize;
  85923. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  85924. });
  85925. return _this;
  85926. }
  85927. FxaaPostProcess.prototype._getDefines = function () {
  85928. var engine = this.getEngine();
  85929. if (!engine) {
  85930. return null;
  85931. }
  85932. var glInfo = engine.getGlInfo();
  85933. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  85934. return "#define MALI 1\n";
  85935. }
  85936. return null;
  85937. };
  85938. return FxaaPostProcess;
  85939. }(BABYLON.PostProcess));
  85940. BABYLON.FxaaPostProcess = FxaaPostProcess;
  85941. })(BABYLON || (BABYLON = {}));
  85942. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  85943. var BABYLON;
  85944. (function (BABYLON) {
  85945. /**
  85946. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  85947. */
  85948. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  85949. __extends(ChromaticAberrationPostProcess, _super);
  85950. /**
  85951. * Creates a new instance ChromaticAberrationPostProcess
  85952. * @param name The name of the effect.
  85953. * @param screenWidth The width of the screen to apply the effect on.
  85954. * @param screenHeight The height of the screen to apply the effect on.
  85955. * @param options The required width/height ratio to downsize to before computing the render pass.
  85956. * @param camera The camera to apply the render pass to.
  85957. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  85958. * @param engine The engine which the post process will be applied. (default: current engine)
  85959. * @param reusable If the post process can be reused on the same frame. (default: false)
  85960. * @param textureType Type of textures used when performing the post process. (default: 0)
  85961. * @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)
  85962. */
  85963. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  85964. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85965. if (blockCompilation === void 0) { blockCompilation = false; }
  85966. 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;
  85967. /**
  85968. * The amount of seperation of rgb channels (default: 30)
  85969. */
  85970. _this.aberrationAmount = 30;
  85971. /**
  85972. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  85973. */
  85974. _this.radialIntensity = 0;
  85975. /**
  85976. * 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))
  85977. */
  85978. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  85979. /**
  85980. * 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))
  85981. */
  85982. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  85983. _this.onApplyObservable.add(function (effect) {
  85984. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  85985. effect.setFloat('screen_width', screenWidth);
  85986. effect.setFloat('screen_height', screenHeight);
  85987. effect.setFloat('radialIntensity', _this.radialIntensity);
  85988. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  85989. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  85990. });
  85991. return _this;
  85992. }
  85993. return ChromaticAberrationPostProcess;
  85994. }(BABYLON.PostProcess));
  85995. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  85996. })(BABYLON || (BABYLON = {}));
  85997. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  85998. var BABYLON;
  85999. (function (BABYLON) {
  86000. /**
  86001. * The GrainPostProcess adds noise to the image at mid luminance levels
  86002. */
  86003. var GrainPostProcess = /** @class */ (function (_super) {
  86004. __extends(GrainPostProcess, _super);
  86005. /**
  86006. * Creates a new instance of @see GrainPostProcess
  86007. * @param name The name of the effect.
  86008. * @param options The required width/height ratio to downsize to before computing the render pass.
  86009. * @param camera The camera to apply the render pass to.
  86010. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  86011. * @param engine The engine which the post process will be applied. (default: current engine)
  86012. * @param reusable If the post process can be reused on the same frame. (default: false)
  86013. * @param textureType Type of textures used when performing the post process. (default: 0)
  86014. * @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)
  86015. */
  86016. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  86017. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86018. if (blockCompilation === void 0) { blockCompilation = false; }
  86019. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  86020. /**
  86021. * The intensity of the grain added (default: 30)
  86022. */
  86023. _this.intensity = 30;
  86024. /**
  86025. * If the grain should be randomized on every frame
  86026. */
  86027. _this.animated = false;
  86028. _this.onApplyObservable.add(function (effect) {
  86029. effect.setFloat('intensity', _this.intensity);
  86030. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  86031. });
  86032. return _this;
  86033. }
  86034. return GrainPostProcess;
  86035. }(BABYLON.PostProcess));
  86036. BABYLON.GrainPostProcess = GrainPostProcess;
  86037. })(BABYLON || (BABYLON = {}));
  86038. //# sourceMappingURL=babylon.grainPostProcess.js.map
  86039. var BABYLON;
  86040. (function (BABYLON) {
  86041. /**
  86042. * The SharpenPostProcess applies a sharpen kernel to every pixel
  86043. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  86044. */
  86045. var SharpenPostProcess = /** @class */ (function (_super) {
  86046. __extends(SharpenPostProcess, _super);
  86047. /**
  86048. * Creates a new instance ConvolutionPostProcess
  86049. * @param name The name of the effect.
  86050. * @param options The required width/height ratio to downsize to before computing the render pass.
  86051. * @param camera The camera to apply the render pass to.
  86052. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  86053. * @param engine The engine which the post process will be applied. (default: current engine)
  86054. * @param reusable If the post process can be reused on the same frame. (default: false)
  86055. * @param textureType Type of textures used when performing the post process. (default: 0)
  86056. * @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)
  86057. */
  86058. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  86059. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86060. if (blockCompilation === void 0) { blockCompilation = false; }
  86061. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  86062. /**
  86063. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  86064. */
  86065. _this.colorAmount = 1.0;
  86066. /**
  86067. * How much sharpness should be applied (default: 0.3)
  86068. */
  86069. _this.edgeAmount = 0.3;
  86070. _this.onApply = function (effect) {
  86071. effect.setFloat2("screenSize", _this.width, _this.height);
  86072. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  86073. };
  86074. return _this;
  86075. }
  86076. return SharpenPostProcess;
  86077. }(BABYLON.PostProcess));
  86078. BABYLON.SharpenPostProcess = SharpenPostProcess;
  86079. })(BABYLON || (BABYLON = {}));
  86080. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  86081. var BABYLON;
  86082. (function (BABYLON) {
  86083. /**
  86084. * The Blur Post Process which blurs an image based on a kernel and direction.
  86085. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  86086. */
  86087. var BlurPostProcess = /** @class */ (function (_super) {
  86088. __extends(BlurPostProcess, _super);
  86089. /**
  86090. * Creates a new instance BlurPostProcess
  86091. * @param name The name of the effect.
  86092. * @param direction The direction in which to blur the image.
  86093. * @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.
  86094. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  86095. * @param camera The camera to apply the render pass to.
  86096. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  86097. * @param engine The engine which the post process will be applied. (default: current engine)
  86098. * @param reusable If the post process can be reused on the same frame. (default: false)
  86099. * @param textureType Type of textures used when performing the post process. (default: 0)
  86100. * @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)
  86101. */
  86102. function BlurPostProcess(name,
  86103. /** The direction in which to blur the image. */
  86104. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  86105. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  86106. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86107. if (defines === void 0) { defines = ""; }
  86108. if (blockCompilation === void 0) { blockCompilation = false; }
  86109. 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;
  86110. _this.direction = direction;
  86111. _this.blockCompilation = blockCompilation;
  86112. _this._packedFloat = false;
  86113. _this._staticDefines = "";
  86114. _this._staticDefines = defines;
  86115. _this.onApplyObservable.add(function (effect) {
  86116. if (_this._outputTexture) {
  86117. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  86118. }
  86119. else {
  86120. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  86121. }
  86122. });
  86123. _this.kernel = kernel;
  86124. return _this;
  86125. }
  86126. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  86127. /**
  86128. * Gets the length in pixels of the blur sample region
  86129. */
  86130. get: function () {
  86131. return this._idealKernel;
  86132. },
  86133. /**
  86134. * Sets the length in pixels of the blur sample region
  86135. */
  86136. set: function (v) {
  86137. if (this._idealKernel === v) {
  86138. return;
  86139. }
  86140. v = Math.max(v, 1);
  86141. this._idealKernel = v;
  86142. this._kernel = this._nearestBestKernel(v);
  86143. if (!this.blockCompilation) {
  86144. this._updateParameters();
  86145. }
  86146. },
  86147. enumerable: true,
  86148. configurable: true
  86149. });
  86150. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  86151. /**
  86152. * Gets wether or not the blur is unpacking/repacking floats
  86153. */
  86154. get: function () {
  86155. return this._packedFloat;
  86156. },
  86157. /**
  86158. * Sets wether or not the blur needs to unpack/repack floats
  86159. */
  86160. set: function (v) {
  86161. if (this._packedFloat === v) {
  86162. return;
  86163. }
  86164. this._packedFloat = v;
  86165. if (!this.blockCompilation) {
  86166. this._updateParameters();
  86167. }
  86168. },
  86169. enumerable: true,
  86170. configurable: true
  86171. });
  86172. /**
  86173. * Updates the effect with the current post process compile time values and recompiles the shader.
  86174. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  86175. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  86176. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  86177. * @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
  86178. * @param onCompiled Called when the shader has been compiled.
  86179. * @param onError Called if there is an error when compiling a shader.
  86180. */
  86181. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  86182. if (defines === void 0) { defines = null; }
  86183. if (uniforms === void 0) { uniforms = null; }
  86184. if (samplers === void 0) { samplers = null; }
  86185. this._updateParameters(onCompiled, onError);
  86186. };
  86187. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  86188. // Generate sampling offsets and weights
  86189. var N = this._kernel;
  86190. var centerIndex = (N - 1) / 2;
  86191. // Generate Gaussian sampling weights over kernel
  86192. var offsets = [];
  86193. var weights = [];
  86194. var totalWeight = 0;
  86195. for (var i = 0; i < N; i++) {
  86196. var u = i / (N - 1);
  86197. var w = this._gaussianWeight(u * 2.0 - 1);
  86198. offsets[i] = (i - centerIndex);
  86199. weights[i] = w;
  86200. totalWeight += w;
  86201. }
  86202. // Normalize weights
  86203. for (var i = 0; i < weights.length; i++) {
  86204. weights[i] /= totalWeight;
  86205. }
  86206. // Optimize: combine samples to take advantage of hardware linear sampling
  86207. // Walk from left to center, combining pairs (symmetrically)
  86208. var linearSamplingWeights = [];
  86209. var linearSamplingOffsets = [];
  86210. var linearSamplingMap = [];
  86211. for (var i = 0; i <= centerIndex; i += 2) {
  86212. var j = Math.min(i + 1, Math.floor(centerIndex));
  86213. var singleCenterSample = i === j;
  86214. if (singleCenterSample) {
  86215. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  86216. }
  86217. else {
  86218. var sharedCell = j === centerIndex;
  86219. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  86220. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  86221. if (offsetLinear === 0) {
  86222. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  86223. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  86224. }
  86225. else {
  86226. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  86227. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  86228. }
  86229. }
  86230. }
  86231. for (var i = 0; i < linearSamplingMap.length; i++) {
  86232. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  86233. linearSamplingWeights[i] = linearSamplingMap[i].w;
  86234. }
  86235. // Replace with optimized
  86236. offsets = linearSamplingOffsets;
  86237. weights = linearSamplingWeights;
  86238. // Generate shaders
  86239. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  86240. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  86241. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  86242. var defines = "";
  86243. defines += this._staticDefines;
  86244. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  86245. if (this._staticDefines.indexOf("DOF") != -1) {
  86246. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  86247. varyingCount--;
  86248. }
  86249. for (var i = 0; i < varyingCount; i++) {
  86250. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  86251. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  86252. }
  86253. var depCount = 0;
  86254. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  86255. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  86256. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  86257. depCount++;
  86258. }
  86259. if (this.packedFloat) {
  86260. defines += "#define PACKEDFLOAT 1";
  86261. }
  86262. this.blockCompilation = false;
  86263. _super.prototype.updateEffect.call(this, defines, null, null, {
  86264. varyingCount: varyingCount,
  86265. depCount: depCount
  86266. }, onCompiled, onError);
  86267. };
  86268. /**
  86269. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  86270. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  86271. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  86272. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  86273. * The gaps between physical kernels are compensated for in the weighting of the samples
  86274. * @param idealKernel Ideal blur kernel.
  86275. * @return Nearest best kernel.
  86276. */
  86277. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  86278. var v = Math.round(idealKernel);
  86279. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  86280. var k = _a[_i];
  86281. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  86282. return Math.max(k, 3);
  86283. }
  86284. }
  86285. return Math.max(v, 3);
  86286. };
  86287. /**
  86288. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  86289. * @param x The point on the Gaussian distribution to sample.
  86290. * @return the value of the Gaussian function at x.
  86291. */
  86292. BlurPostProcess.prototype._gaussianWeight = function (x) {
  86293. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  86294. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  86295. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  86296. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  86297. // truncated at around 1.3% of peak strength.
  86298. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  86299. var sigma = (1 / 3);
  86300. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  86301. var exponent = -((x * x) / (2.0 * sigma * sigma));
  86302. var weight = (1.0 / denominator) * Math.exp(exponent);
  86303. return weight;
  86304. };
  86305. /**
  86306. * Generates a string that can be used as a floating point number in GLSL.
  86307. * @param x Value to print.
  86308. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  86309. * @return GLSL float string.
  86310. */
  86311. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  86312. if (decimalFigures === void 0) { decimalFigures = 8; }
  86313. return x.toFixed(decimalFigures).replace(/0+$/, '');
  86314. };
  86315. return BlurPostProcess;
  86316. }(BABYLON.PostProcess));
  86317. BABYLON.BlurPostProcess = BlurPostProcess;
  86318. })(BABYLON || (BABYLON = {}));
  86319. //# sourceMappingURL=babylon.blurPostProcess.js.map
  86320. var BABYLON;
  86321. (function (BABYLON) {
  86322. /**
  86323. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  86324. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  86325. * based on samples that have a large difference in distance than the center pixel.
  86326. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  86327. */
  86328. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  86329. __extends(DepthOfFieldBlurPostProcess, _super);
  86330. /**
  86331. * Creates a new instance CircleOfConfusionPostProcess
  86332. * @param name The name of the effect.
  86333. * @param scene The scene the effect belongs to.
  86334. * @param direction The direction the blur should be applied.
  86335. * @param kernel The size of the kernel used to blur.
  86336. * @param options The required width/height ratio to downsize to before computing the render pass.
  86337. * @param camera The camera to apply the render pass to.
  86338. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  86339. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  86340. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  86341. * @param engine The engine which the post process will be applied. (default: current engine)
  86342. * @param reusable If the post process can be reused on the same frame. (default: false)
  86343. * @param textureType Type of textures used when performing the post process. (default: 0)
  86344. * @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)
  86345. */
  86346. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  86347. if (imageToBlur === void 0) { imageToBlur = null; }
  86348. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  86349. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86350. if (blockCompilation === void 0) { blockCompilation = false; }
  86351. 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;
  86352. _this.direction = direction;
  86353. _this.onApplyObservable.add(function (effect) {
  86354. if (imageToBlur != null) {
  86355. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  86356. }
  86357. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  86358. if (scene.activeCamera) {
  86359. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  86360. }
  86361. });
  86362. return _this;
  86363. }
  86364. return DepthOfFieldBlurPostProcess;
  86365. }(BABYLON.BlurPostProcess));
  86366. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  86367. })(BABYLON || (BABYLON = {}));
  86368. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  86369. var BABYLON;
  86370. (function (BABYLON) {
  86371. /**
  86372. * Options to be set when merging outputs from the default pipeline.
  86373. */
  86374. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  86375. function DepthOfFieldMergePostProcessOptions() {
  86376. }
  86377. return DepthOfFieldMergePostProcessOptions;
  86378. }());
  86379. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  86380. /**
  86381. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  86382. */
  86383. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  86384. __extends(DepthOfFieldMergePostProcess, _super);
  86385. /**
  86386. * Creates a new instance of DepthOfFieldMergePostProcess
  86387. * @param name The name of the effect.
  86388. * @param originalFromInput Post process which's input will be used for the merge.
  86389. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  86390. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  86391. * @param options The required width/height ratio to downsize to before computing the render pass.
  86392. * @param camera The camera to apply the render pass to.
  86393. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  86394. * @param engine The engine which the post process will be applied. (default: current engine)
  86395. * @param reusable If the post process can be reused on the same frame. (default: false)
  86396. * @param textureType Type of textures used when performing the post process. (default: 0)
  86397. * @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)
  86398. */
  86399. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  86400. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86401. if (blockCompilation === void 0) { blockCompilation = false; }
  86402. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  86403. _this.blurSteps = blurSteps;
  86404. _this.onApplyObservable.add(function (effect) {
  86405. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  86406. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  86407. blurSteps.forEach(function (step, index) {
  86408. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  86409. });
  86410. });
  86411. if (!blockCompilation) {
  86412. _this.updateEffect();
  86413. }
  86414. return _this;
  86415. }
  86416. /**
  86417. * Updates the effect with the current post process compile time values and recompiles the shader.
  86418. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  86419. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  86420. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  86421. * @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
  86422. * @param onCompiled Called when the shader has been compiled.
  86423. * @param onError Called if there is an error when compiling a shader.
  86424. */
  86425. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  86426. if (defines === void 0) { defines = null; }
  86427. if (uniforms === void 0) { uniforms = null; }
  86428. if (samplers === void 0) { samplers = null; }
  86429. if (!defines) {
  86430. defines = "";
  86431. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  86432. }
  86433. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  86434. };
  86435. return DepthOfFieldMergePostProcess;
  86436. }(BABYLON.PostProcess));
  86437. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  86438. })(BABYLON || (BABYLON = {}));
  86439. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  86440. var BABYLON;
  86441. (function (BABYLON) {
  86442. /**
  86443. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  86444. */
  86445. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  86446. __extends(CircleOfConfusionPostProcess, _super);
  86447. /**
  86448. * Creates a new instance CircleOfConfusionPostProcess
  86449. * @param name The name of the effect.
  86450. * @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.
  86451. * @param options The required width/height ratio to downsize to before computing the render pass.
  86452. * @param camera The camera to apply the render pass to.
  86453. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  86454. * @param engine The engine which the post process will be applied. (default: current engine)
  86455. * @param reusable If the post process can be reused on the same frame. (default: false)
  86456. * @param textureType Type of textures used when performing the post process. (default: 0)
  86457. * @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)
  86458. */
  86459. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  86460. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86461. if (blockCompilation === void 0) { blockCompilation = false; }
  86462. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  86463. /**
  86464. * 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.
  86465. */
  86466. _this.lensSize = 50;
  86467. /**
  86468. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  86469. */
  86470. _this.fStop = 1.4;
  86471. /**
  86472. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  86473. */
  86474. _this.focusDistance = 2000;
  86475. /**
  86476. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  86477. */
  86478. _this.focalLength = 50;
  86479. _this._depthTexture = null;
  86480. _this._depthTexture = depthTexture;
  86481. _this.onApplyObservable.add(function (effect) {
  86482. if (!_this._depthTexture) {
  86483. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  86484. return;
  86485. }
  86486. effect.setTexture("depthSampler", _this._depthTexture);
  86487. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  86488. var aperture = _this.lensSize / _this.fStop;
  86489. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  86490. effect.setFloat('focusDistance', _this.focusDistance);
  86491. effect.setFloat('cocPrecalculation', cocPrecalculation);
  86492. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  86493. });
  86494. return _this;
  86495. }
  86496. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  86497. /**
  86498. * 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.
  86499. */
  86500. set: function (value) {
  86501. this._depthTexture = value;
  86502. },
  86503. enumerable: true,
  86504. configurable: true
  86505. });
  86506. return CircleOfConfusionPostProcess;
  86507. }(BABYLON.PostProcess));
  86508. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  86509. })(BABYLON || (BABYLON = {}));
  86510. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  86511. var BABYLON;
  86512. (function (BABYLON) {
  86513. /**
  86514. * Specifies the level of max blur that should be applied when using the depth of field effect
  86515. */
  86516. var DepthOfFieldEffectBlurLevel;
  86517. (function (DepthOfFieldEffectBlurLevel) {
  86518. /**
  86519. * Subtle blur
  86520. */
  86521. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  86522. /**
  86523. * Medium blur
  86524. */
  86525. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  86526. /**
  86527. * Large blur
  86528. */
  86529. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  86530. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  86531. /**
  86532. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  86533. */
  86534. var DepthOfFieldEffect = /** @class */ (function (_super) {
  86535. __extends(DepthOfFieldEffect, _super);
  86536. /**
  86537. * Creates a new instance DepthOfFieldEffect
  86538. * @param scene The scene the effect belongs to.
  86539. * @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.
  86540. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  86541. * @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)
  86542. */
  86543. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  86544. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  86545. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  86546. if (blockCompilation === void 0) { blockCompilation = false; }
  86547. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  86548. return _this._effects;
  86549. }, true) || this;
  86550. /**
  86551. * @hidden Internal post processes in depth of field effect
  86552. */
  86553. _this._effects = [];
  86554. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  86555. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  86556. // 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)
  86557. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  86558. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  86559. _this._depthOfFieldBlurY = [];
  86560. _this._depthOfFieldBlurX = [];
  86561. var blurCount = 1;
  86562. var kernelSize = 15;
  86563. switch (blurLevel) {
  86564. case DepthOfFieldEffectBlurLevel.High: {
  86565. blurCount = 3;
  86566. kernelSize = 51;
  86567. break;
  86568. }
  86569. case DepthOfFieldEffectBlurLevel.Medium: {
  86570. blurCount = 2;
  86571. kernelSize = 31;
  86572. break;
  86573. }
  86574. default: {
  86575. kernelSize = 15;
  86576. blurCount = 1;
  86577. break;
  86578. }
  86579. }
  86580. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  86581. var ratio = 1.0;
  86582. for (var i = 0; i < blurCount; i++) {
  86583. 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);
  86584. blurY.autoClear = false;
  86585. ratio = 0.75 / Math.pow(2, i);
  86586. 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);
  86587. blurX.autoClear = false;
  86588. _this._depthOfFieldBlurY.push(blurY);
  86589. _this._depthOfFieldBlurX.push(blurX);
  86590. }
  86591. // Set all post processes on the effect.
  86592. _this._effects = [_this._circleOfConfusion];
  86593. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  86594. _this._effects.push(_this._depthOfFieldBlurY[i]);
  86595. _this._effects.push(_this._depthOfFieldBlurX[i]);
  86596. }
  86597. // Merge blurred images with original image based on circleOfConfusion
  86598. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  86599. _this._dofMerge.autoClear = false;
  86600. _this._effects.push(_this._dofMerge);
  86601. return _this;
  86602. }
  86603. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  86604. get: function () {
  86605. return this._circleOfConfusion.focalLength;
  86606. },
  86607. /**
  86608. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  86609. */
  86610. set: function (value) {
  86611. this._circleOfConfusion.focalLength = value;
  86612. },
  86613. enumerable: true,
  86614. configurable: true
  86615. });
  86616. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  86617. get: function () {
  86618. return this._circleOfConfusion.fStop;
  86619. },
  86620. /**
  86621. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  86622. */
  86623. set: function (value) {
  86624. this._circleOfConfusion.fStop = value;
  86625. },
  86626. enumerable: true,
  86627. configurable: true
  86628. });
  86629. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  86630. get: function () {
  86631. return this._circleOfConfusion.focusDistance;
  86632. },
  86633. /**
  86634. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  86635. */
  86636. set: function (value) {
  86637. this._circleOfConfusion.focusDistance = value;
  86638. },
  86639. enumerable: true,
  86640. configurable: true
  86641. });
  86642. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  86643. get: function () {
  86644. return this._circleOfConfusion.lensSize;
  86645. },
  86646. /**
  86647. * 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.
  86648. */
  86649. set: function (value) {
  86650. this._circleOfConfusion.lensSize = value;
  86651. },
  86652. enumerable: true,
  86653. configurable: true
  86654. });
  86655. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  86656. /**
  86657. * 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.
  86658. */
  86659. set: function (value) {
  86660. this._circleOfConfusion.depthTexture = value;
  86661. },
  86662. enumerable: true,
  86663. configurable: true
  86664. });
  86665. /**
  86666. * Disposes each of the internal effects for a given camera.
  86667. * @param camera The camera to dispose the effect on.
  86668. */
  86669. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  86670. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  86671. this._effects[effectIndex].dispose(camera);
  86672. }
  86673. };
  86674. /**
  86675. * @hidden Internal
  86676. */
  86677. DepthOfFieldEffect.prototype._updateEffects = function () {
  86678. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  86679. this._effects[effectIndex].updateEffect();
  86680. }
  86681. };
  86682. /**
  86683. * Internal
  86684. * @returns if all the contained post processes are ready.
  86685. * @hidden
  86686. */
  86687. DepthOfFieldEffect.prototype._isReady = function () {
  86688. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  86689. if (!this._effects[effectIndex].isReady()) {
  86690. return false;
  86691. }
  86692. }
  86693. return true;
  86694. };
  86695. return DepthOfFieldEffect;
  86696. }(BABYLON.PostProcessRenderEffect));
  86697. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  86698. })(BABYLON || (BABYLON = {}));
  86699. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  86700. var BABYLON;
  86701. (function (BABYLON) {
  86702. /**
  86703. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  86704. */
  86705. var BloomMergePostProcess = /** @class */ (function (_super) {
  86706. __extends(BloomMergePostProcess, _super);
  86707. /**
  86708. * Creates a new instance of @see BloomMergePostProcess
  86709. * @param name The name of the effect.
  86710. * @param originalFromInput Post process which's input will be used for the merge.
  86711. * @param blurred Blurred highlights post process which's output will be used.
  86712. * @param weight Weight of the bloom to be added to the original input.
  86713. * @param options The required width/height ratio to downsize to before computing the render pass.
  86714. * @param camera The camera to apply the render pass to.
  86715. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  86716. * @param engine The engine which the post process will be applied. (default: current engine)
  86717. * @param reusable If the post process can be reused on the same frame. (default: false)
  86718. * @param textureType Type of textures used when performing the post process. (default: 0)
  86719. * @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)
  86720. */
  86721. function BloomMergePostProcess(name, originalFromInput, blurred,
  86722. /** Weight of the bloom to be added to the original input. */
  86723. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  86724. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86725. if (blockCompilation === void 0) { blockCompilation = false; }
  86726. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  86727. _this.weight = weight;
  86728. _this.onApplyObservable.add(function (effect) {
  86729. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  86730. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  86731. effect.setFloat("bloomWeight", _this.weight);
  86732. });
  86733. if (!blockCompilation) {
  86734. _this.updateEffect();
  86735. }
  86736. return _this;
  86737. }
  86738. return BloomMergePostProcess;
  86739. }(BABYLON.PostProcess));
  86740. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  86741. })(BABYLON || (BABYLON = {}));
  86742. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  86743. var BABYLON;
  86744. (function (BABYLON) {
  86745. /**
  86746. * 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.
  86747. */
  86748. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  86749. __extends(ExtractHighlightsPostProcess, _super);
  86750. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  86751. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86752. if (blockCompilation === void 0) { blockCompilation = false; }
  86753. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  86754. /**
  86755. * The luminance threshold, pixels below this value will be set to black.
  86756. */
  86757. _this.threshold = 0.9;
  86758. /** @hidden */
  86759. _this._exposure = 1;
  86760. /**
  86761. * Post process which has the input texture to be used when performing highlight extraction
  86762. * @hidden
  86763. */
  86764. _this._inputPostProcess = null;
  86765. _this.onApplyObservable.add(function (effect) {
  86766. if (_this._inputPostProcess) {
  86767. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  86768. }
  86769. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  86770. effect.setFloat('exposure', _this._exposure);
  86771. });
  86772. return _this;
  86773. }
  86774. return ExtractHighlightsPostProcess;
  86775. }(BABYLON.PostProcess));
  86776. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  86777. })(BABYLON || (BABYLON = {}));
  86778. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  86779. var BABYLON;
  86780. (function (BABYLON) {
  86781. /**
  86782. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  86783. */
  86784. var BloomEffect = /** @class */ (function (_super) {
  86785. __extends(BloomEffect, _super);
  86786. /**
  86787. * Creates a new instance of @see BloomEffect
  86788. * @param scene The scene the effect belongs to.
  86789. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  86790. * @param bloomKernel The size of the kernel to be used when applying the blur.
  86791. * @param bloomWeight The the strength of bloom.
  86792. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  86793. * @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)
  86794. */
  86795. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  86796. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  86797. if (blockCompilation === void 0) { blockCompilation = false; }
  86798. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  86799. return _this._effects;
  86800. }, true) || this;
  86801. _this.bloomScale = bloomScale;
  86802. /**
  86803. * @hidden Internal
  86804. */
  86805. _this._effects = [];
  86806. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  86807. _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);
  86808. _this._blurX.alwaysForcePOT = true;
  86809. _this._blurX.autoClear = false;
  86810. _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);
  86811. _this._blurY.alwaysForcePOT = true;
  86812. _this._blurY.autoClear = false;
  86813. _this.kernel = bloomKernel;
  86814. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  86815. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  86816. _this._merge.autoClear = false;
  86817. _this._effects.push(_this._merge);
  86818. return _this;
  86819. }
  86820. Object.defineProperty(BloomEffect.prototype, "threshold", {
  86821. /**
  86822. * The luminance threshold to find bright areas of the image to bloom.
  86823. */
  86824. get: function () {
  86825. return this._downscale.threshold;
  86826. },
  86827. set: function (value) {
  86828. this._downscale.threshold = value;
  86829. },
  86830. enumerable: true,
  86831. configurable: true
  86832. });
  86833. Object.defineProperty(BloomEffect.prototype, "weight", {
  86834. /**
  86835. * The strength of the bloom.
  86836. */
  86837. get: function () {
  86838. return this._merge.weight;
  86839. },
  86840. set: function (value) {
  86841. this._merge.weight = value;
  86842. },
  86843. enumerable: true,
  86844. configurable: true
  86845. });
  86846. Object.defineProperty(BloomEffect.prototype, "kernel", {
  86847. /**
  86848. * Specifies the size of the bloom blur kernel, relative to the final output size
  86849. */
  86850. get: function () {
  86851. return this._blurX.kernel / this.bloomScale;
  86852. },
  86853. set: function (value) {
  86854. this._blurX.kernel = value * this.bloomScale;
  86855. this._blurY.kernel = value * this.bloomScale;
  86856. },
  86857. enumerable: true,
  86858. configurable: true
  86859. });
  86860. /**
  86861. * Disposes each of the internal effects for a given camera.
  86862. * @param camera The camera to dispose the effect on.
  86863. */
  86864. BloomEffect.prototype.disposeEffects = function (camera) {
  86865. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  86866. this._effects[effectIndex].dispose(camera);
  86867. }
  86868. };
  86869. /**
  86870. * @hidden Internal
  86871. */
  86872. BloomEffect.prototype._updateEffects = function () {
  86873. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  86874. this._effects[effectIndex].updateEffect();
  86875. }
  86876. };
  86877. /**
  86878. * Internal
  86879. * @returns if all the contained post processes are ready.
  86880. * @hidden
  86881. */
  86882. BloomEffect.prototype._isReady = function () {
  86883. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  86884. if (!this._effects[effectIndex].isReady()) {
  86885. return false;
  86886. }
  86887. }
  86888. return true;
  86889. };
  86890. return BloomEffect;
  86891. }(BABYLON.PostProcessRenderEffect));
  86892. BABYLON.BloomEffect = BloomEffect;
  86893. })(BABYLON || (BABYLON = {}));
  86894. //# sourceMappingURL=babylon.bloomEffect.js.map
  86895. var BABYLON;
  86896. (function (BABYLON) {
  86897. /**
  86898. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  86899. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  86900. */
  86901. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  86902. __extends(DefaultRenderingPipeline, _super);
  86903. /**
  86904. * @constructor
  86905. * @param name - The rendering pipeline name (default: "")
  86906. * @param hdr - If high dynamic range textures should be used (default: true)
  86907. * @param scene - The scene linked to this pipeline (default: the last created scene)
  86908. * @param cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  86909. * @param automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  86910. */
  86911. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  86912. if (name === void 0) { name = ""; }
  86913. if (hdr === void 0) { hdr = true; }
  86914. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  86915. if (automaticBuild === void 0) { automaticBuild = true; }
  86916. var _this = _super.call(this, scene.getEngine(), name) || this;
  86917. _this._camerasToBeAttached = [];
  86918. /**
  86919. * ID of the sharpen post process,
  86920. */
  86921. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  86922. /**
  86923. * @ignore
  86924. * ID of the image processing post process;
  86925. */
  86926. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  86927. /**
  86928. * @ignore
  86929. * ID of the Fast Approximate Anti-Aliasing post process;
  86930. */
  86931. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  86932. /**
  86933. * ID of the chromatic aberration post process,
  86934. */
  86935. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  86936. /**
  86937. * ID of the grain post process
  86938. */
  86939. _this.GrainPostProcessId = "GrainPostProcessEffect";
  86940. /**
  86941. * Glow post process which adds a glow to emmisive areas of the image
  86942. */
  86943. _this._glowLayer = null;
  86944. /**
  86945. * Animations which can be used to tweak settings over a period of time
  86946. */
  86947. _this.animations = [];
  86948. _this._imageProcessingConfigurationObserver = null;
  86949. // Values
  86950. _this._sharpenEnabled = false;
  86951. _this._bloomEnabled = false;
  86952. _this._depthOfFieldEnabled = false;
  86953. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  86954. _this._fxaaEnabled = false;
  86955. _this._imageProcessingEnabled = true;
  86956. _this._bloomScale = 0.5;
  86957. _this._chromaticAberrationEnabled = false;
  86958. _this._grainEnabled = false;
  86959. _this._buildAllowed = true;
  86960. _this._resizeObserver = null;
  86961. _this._hardwareScaleLevel = 1.0;
  86962. _this._bloomKernel = 64;
  86963. /**
  86964. * Specifies the weight of the bloom in the final rendering
  86965. */
  86966. _this._bloomWeight = 0.15;
  86967. /**
  86968. * Specifies the luma threshold for the area that will be blurred by the bloom
  86969. */
  86970. _this._bloomThreshold = 0.9;
  86971. _this._samples = 1;
  86972. _this._hasCleared = false;
  86973. _this._prevPostProcess = null;
  86974. _this._prevPrevPostProcess = null;
  86975. _this._depthOfFieldSceneObserver = null;
  86976. _this._cameras = cameras || scene.cameras;
  86977. _this._cameras = _this._cameras.slice();
  86978. _this._camerasToBeAttached = _this._cameras.slice();
  86979. _this._buildAllowed = automaticBuild;
  86980. // Initialize
  86981. _this._scene = scene;
  86982. var caps = _this._scene.getEngine().getCaps();
  86983. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  86984. // Misc
  86985. if (_this._hdr) {
  86986. if (caps.textureHalfFloatRender) {
  86987. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  86988. }
  86989. else if (caps.textureFloatRender) {
  86990. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  86991. }
  86992. }
  86993. else {
  86994. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  86995. }
  86996. // Attach
  86997. scene.postProcessRenderPipelineManager.addPipeline(_this);
  86998. var engine = _this._scene.getEngine();
  86999. // Create post processes before hand so they can be modified before enabled.
  87000. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  87001. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  87002. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  87003. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  87004. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  87005. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  87006. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  87007. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  87008. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  87009. _this._resizeObserver = engine.onResizeObservable.add(function () {
  87010. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  87011. _this.bloomKernel = _this.bloomKernel;
  87012. });
  87013. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  87014. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  87015. });
  87016. _this._buildPipeline();
  87017. return _this;
  87018. }
  87019. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  87020. get: function () {
  87021. return this._sharpenEnabled;
  87022. },
  87023. /**
  87024. * Enable or disable the sharpen process from the pipeline
  87025. */
  87026. set: function (enabled) {
  87027. if (this._sharpenEnabled === enabled) {
  87028. return;
  87029. }
  87030. this._sharpenEnabled = enabled;
  87031. this._buildPipeline();
  87032. },
  87033. enumerable: true,
  87034. configurable: true
  87035. });
  87036. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  87037. /**
  87038. * Specifies the size of the bloom blur kernel, relative to the final output size
  87039. */
  87040. get: function () {
  87041. return this._bloomKernel;
  87042. },
  87043. set: function (value) {
  87044. this._bloomKernel = value;
  87045. this.bloom.kernel = value / this._hardwareScaleLevel;
  87046. },
  87047. enumerable: true,
  87048. configurable: true
  87049. });
  87050. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  87051. get: function () {
  87052. return this._bloomWeight;
  87053. },
  87054. /**
  87055. * The strength of the bloom.
  87056. */
  87057. set: function (value) {
  87058. if (this._bloomWeight === value) {
  87059. return;
  87060. }
  87061. this.bloom.weight = value;
  87062. this._bloomWeight = value;
  87063. },
  87064. enumerable: true,
  87065. configurable: true
  87066. });
  87067. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  87068. get: function () {
  87069. return this._bloomThreshold;
  87070. },
  87071. /**
  87072. * The strength of the bloom.
  87073. */
  87074. set: function (value) {
  87075. if (this._bloomThreshold === value) {
  87076. return;
  87077. }
  87078. this.bloom.threshold = value;
  87079. this._bloomThreshold = value;
  87080. },
  87081. enumerable: true,
  87082. configurable: true
  87083. });
  87084. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  87085. get: function () {
  87086. return this._bloomScale;
  87087. },
  87088. /**
  87089. * The scale of the bloom, lower value will provide better performance.
  87090. */
  87091. set: function (value) {
  87092. if (this._bloomScale === value) {
  87093. return;
  87094. }
  87095. this._bloomScale = value;
  87096. // recreate bloom and dispose old as this setting is not dynamic
  87097. this._rebuildBloom();
  87098. this._buildPipeline();
  87099. },
  87100. enumerable: true,
  87101. configurable: true
  87102. });
  87103. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  87104. get: function () {
  87105. return this._bloomEnabled;
  87106. },
  87107. /**
  87108. * Enable or disable the bloom from the pipeline
  87109. */
  87110. set: function (enabled) {
  87111. if (this._bloomEnabled === enabled) {
  87112. return;
  87113. }
  87114. this._bloomEnabled = enabled;
  87115. this._buildPipeline();
  87116. },
  87117. enumerable: true,
  87118. configurable: true
  87119. });
  87120. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  87121. // recreate bloom and dispose old as this setting is not dynamic
  87122. var oldBloom = this.bloom;
  87123. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  87124. this.bloom.threshold = oldBloom.threshold;
  87125. for (var i = 0; i < this._cameras.length; i++) {
  87126. oldBloom.disposeEffects(this._cameras[i]);
  87127. }
  87128. };
  87129. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  87130. /**
  87131. * If the depth of field is enabled.
  87132. */
  87133. get: function () {
  87134. return this._depthOfFieldEnabled;
  87135. },
  87136. set: function (enabled) {
  87137. if (this._depthOfFieldEnabled === enabled) {
  87138. return;
  87139. }
  87140. this._depthOfFieldEnabled = enabled;
  87141. this._buildPipeline();
  87142. },
  87143. enumerable: true,
  87144. configurable: true
  87145. });
  87146. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  87147. /**
  87148. * Blur level of the depth of field effect. (Higher blur will effect performance)
  87149. */
  87150. get: function () {
  87151. return this._depthOfFieldBlurLevel;
  87152. },
  87153. set: function (value) {
  87154. if (this._depthOfFieldBlurLevel === value) {
  87155. return;
  87156. }
  87157. this._depthOfFieldBlurLevel = value;
  87158. // recreate dof and dispose old as this setting is not dynamic
  87159. var oldDof = this.depthOfField;
  87160. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  87161. this.depthOfField.focalLength = oldDof.focalLength;
  87162. this.depthOfField.focusDistance = oldDof.focusDistance;
  87163. this.depthOfField.fStop = oldDof.fStop;
  87164. this.depthOfField.lensSize = oldDof.lensSize;
  87165. for (var i = 0; i < this._cameras.length; i++) {
  87166. oldDof.disposeEffects(this._cameras[i]);
  87167. }
  87168. this._buildPipeline();
  87169. },
  87170. enumerable: true,
  87171. configurable: true
  87172. });
  87173. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  87174. get: function () {
  87175. return this._fxaaEnabled;
  87176. },
  87177. /**
  87178. * If the anti aliasing is enabled.
  87179. */
  87180. set: function (enabled) {
  87181. if (this._fxaaEnabled === enabled) {
  87182. return;
  87183. }
  87184. this._fxaaEnabled = enabled;
  87185. this._buildPipeline();
  87186. },
  87187. enumerable: true,
  87188. configurable: true
  87189. });
  87190. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  87191. get: function () {
  87192. return this._samples;
  87193. },
  87194. /**
  87195. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  87196. */
  87197. set: function (sampleCount) {
  87198. if (this._samples === sampleCount) {
  87199. return;
  87200. }
  87201. this._samples = sampleCount;
  87202. this._buildPipeline();
  87203. },
  87204. enumerable: true,
  87205. configurable: true
  87206. });
  87207. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  87208. get: function () {
  87209. return this._imageProcessingEnabled;
  87210. },
  87211. /**
  87212. * If image processing is enabled.
  87213. */
  87214. set: function (enabled) {
  87215. if (this._imageProcessingEnabled === enabled) {
  87216. return;
  87217. }
  87218. this._imageProcessingEnabled = enabled;
  87219. this._buildPipeline();
  87220. },
  87221. enumerable: true,
  87222. configurable: true
  87223. });
  87224. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  87225. get: function () {
  87226. return this._glowLayer == null;
  87227. },
  87228. /**
  87229. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  87230. */
  87231. set: function (enabled) {
  87232. if (enabled && !this._glowLayer) {
  87233. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  87234. }
  87235. else if (!enabled && this._glowLayer) {
  87236. this._glowLayer.dispose();
  87237. this._glowLayer = null;
  87238. }
  87239. },
  87240. enumerable: true,
  87241. configurable: true
  87242. });
  87243. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  87244. get: function () {
  87245. return this._chromaticAberrationEnabled;
  87246. },
  87247. /**
  87248. * Enable or disable the chromaticAberration process from the pipeline
  87249. */
  87250. set: function (enabled) {
  87251. if (this._chromaticAberrationEnabled === enabled) {
  87252. return;
  87253. }
  87254. this._chromaticAberrationEnabled = enabled;
  87255. this._buildPipeline();
  87256. },
  87257. enumerable: true,
  87258. configurable: true
  87259. });
  87260. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  87261. get: function () {
  87262. return this._grainEnabled;
  87263. },
  87264. /**
  87265. * Enable or disable the grain process from the pipeline
  87266. */
  87267. set: function (enabled) {
  87268. if (this._grainEnabled === enabled) {
  87269. return;
  87270. }
  87271. this._grainEnabled = enabled;
  87272. this._buildPipeline();
  87273. },
  87274. enumerable: true,
  87275. configurable: true
  87276. });
  87277. /**
  87278. * Force the compilation of the entire pipeline.
  87279. */
  87280. DefaultRenderingPipeline.prototype.prepare = function () {
  87281. var previousState = this._buildAllowed;
  87282. this._buildAllowed = true;
  87283. this._buildPipeline();
  87284. this._buildAllowed = previousState;
  87285. };
  87286. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  87287. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  87288. if (this._hasCleared) {
  87289. postProcess.autoClear = false;
  87290. }
  87291. else {
  87292. postProcess.autoClear = true;
  87293. this._scene.autoClear = false;
  87294. this._hasCleared = true;
  87295. }
  87296. if (!skipTextureSharing) {
  87297. if (this._prevPrevPostProcess) {
  87298. postProcess.shareOutputWith(this._prevPrevPostProcess);
  87299. }
  87300. else {
  87301. postProcess.useOwnOutput();
  87302. }
  87303. if (this._prevPostProcess) {
  87304. this._prevPrevPostProcess = this._prevPostProcess;
  87305. }
  87306. this._prevPostProcess = postProcess;
  87307. }
  87308. };
  87309. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  87310. var _this = this;
  87311. if (!this._buildAllowed) {
  87312. return;
  87313. }
  87314. this._scene.autoClear = true;
  87315. var engine = this._scene.getEngine();
  87316. this._disposePostProcesses();
  87317. if (this._cameras !== null) {
  87318. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  87319. // get back cameras to be used to reattach pipeline
  87320. this._cameras = this._camerasToBeAttached.slice();
  87321. }
  87322. this._reset();
  87323. this._prevPostProcess = null;
  87324. this._prevPrevPostProcess = null;
  87325. this._hasCleared = false;
  87326. if (this.depthOfFieldEnabled) {
  87327. // Multi camera suport
  87328. if (this._cameras.length > 1) {
  87329. for (var _i = 0, _a = this._cameras; _i < _a.length; _i++) {
  87330. var camera = _a[_i];
  87331. var depthRenderer = this._scene.enableDepthRenderer(camera);
  87332. depthRenderer.useOnlyInActiveCamera = true;
  87333. }
  87334. this._depthOfFieldSceneObserver = this._scene.onAfterRenderTargetsRenderObservable.add(function (scene) {
  87335. if (_this._cameras.indexOf(scene.activeCamera) > -1) {
  87336. _this.depthOfField.depthTexture = scene.enableDepthRenderer(scene.activeCamera).getDepthMap();
  87337. }
  87338. });
  87339. }
  87340. else {
  87341. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  87342. var depthRenderer = this._scene.enableDepthRenderer(this._cameras[0]);
  87343. this.depthOfField.depthTexture = depthRenderer.getDepthMap();
  87344. }
  87345. if (!this.depthOfField._isReady()) {
  87346. this.depthOfField._updateEffects();
  87347. }
  87348. this.addEffect(this.depthOfField);
  87349. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  87350. }
  87351. else {
  87352. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  87353. }
  87354. if (this.bloomEnabled) {
  87355. if (!this.bloom._isReady()) {
  87356. this.bloom._updateEffects();
  87357. }
  87358. this.addEffect(this.bloom);
  87359. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  87360. }
  87361. if (this._imageProcessingEnabled) {
  87362. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  87363. if (this._hdr) {
  87364. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  87365. this._setAutoClearAndTextureSharing(this.imageProcessing);
  87366. }
  87367. else {
  87368. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  87369. }
  87370. }
  87371. if (this.sharpenEnabled) {
  87372. if (!this.sharpen.isReady()) {
  87373. this.sharpen.updateEffect();
  87374. }
  87375. this.addEffect(this._sharpenEffect);
  87376. this._setAutoClearAndTextureSharing(this.sharpen);
  87377. }
  87378. if (this.grainEnabled) {
  87379. if (!this.grain.isReady()) {
  87380. this.grain.updateEffect();
  87381. }
  87382. this.addEffect(this._grainEffect);
  87383. this._setAutoClearAndTextureSharing(this.grain);
  87384. }
  87385. if (this.chromaticAberrationEnabled) {
  87386. if (!this.chromaticAberration.isReady()) {
  87387. this.chromaticAberration.updateEffect();
  87388. }
  87389. this.addEffect(this._chromaticAberrationEffect);
  87390. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  87391. }
  87392. if (this.fxaaEnabled) {
  87393. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  87394. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  87395. this._setAutoClearAndTextureSharing(this.fxaa, true);
  87396. }
  87397. if (this._cameras !== null) {
  87398. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  87399. }
  87400. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  87401. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  87402. }
  87403. };
  87404. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  87405. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  87406. for (var i = 0; i < this._cameras.length; i++) {
  87407. var camera = this._cameras[i];
  87408. if (this.imageProcessing) {
  87409. this.imageProcessing.dispose(camera);
  87410. }
  87411. if (this.fxaa) {
  87412. this.fxaa.dispose(camera);
  87413. }
  87414. // These are created in the constructor and should not be disposed on every pipeline change
  87415. if (disposeNonRecreated) {
  87416. if (this.sharpen) {
  87417. this.sharpen.dispose(camera);
  87418. }
  87419. if (this.depthOfField) {
  87420. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  87421. this.depthOfField.disposeEffects(camera);
  87422. }
  87423. if (this.bloom) {
  87424. this.bloom.disposeEffects(camera);
  87425. }
  87426. if (this.chromaticAberration) {
  87427. this.chromaticAberration.dispose(camera);
  87428. }
  87429. if (this.grain) {
  87430. this.grain.dispose(camera);
  87431. }
  87432. if (this._glowLayer) {
  87433. this._glowLayer.dispose();
  87434. }
  87435. }
  87436. }
  87437. this.imageProcessing = null;
  87438. this.fxaa = null;
  87439. if (disposeNonRecreated) {
  87440. this.sharpen = null;
  87441. this._sharpenEffect = null;
  87442. this.depthOfField = null;
  87443. this.bloom = null;
  87444. this.chromaticAberration = null;
  87445. this._chromaticAberrationEffect = null;
  87446. this.grain = null;
  87447. this._grainEffect = null;
  87448. this._glowLayer = null;
  87449. }
  87450. };
  87451. /**
  87452. * Adds a camera to the pipeline
  87453. * @param camera the camera to be added
  87454. */
  87455. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  87456. this._camerasToBeAttached.push(camera);
  87457. this._buildPipeline();
  87458. };
  87459. /**
  87460. * Removes a camera from the pipeline
  87461. * @param camera the camera to remove
  87462. */
  87463. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  87464. var index = this._camerasToBeAttached.indexOf(camera);
  87465. this._camerasToBeAttached.splice(index, 1);
  87466. this._buildPipeline();
  87467. };
  87468. /**
  87469. * Dispose of the pipeline and stop all post processes
  87470. */
  87471. DefaultRenderingPipeline.prototype.dispose = function () {
  87472. this._disposePostProcesses(true);
  87473. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  87474. this._scene.autoClear = true;
  87475. if (this._resizeObserver) {
  87476. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  87477. this._resizeObserver = null;
  87478. }
  87479. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  87480. _super.prototype.dispose.call(this);
  87481. };
  87482. /**
  87483. * Serialize the rendering pipeline (Used when exporting)
  87484. * @returns the serialized object
  87485. */
  87486. DefaultRenderingPipeline.prototype.serialize = function () {
  87487. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  87488. serializationObject.customType = "DefaultRenderingPipeline";
  87489. return serializationObject;
  87490. };
  87491. /**
  87492. * Parse the serialized pipeline
  87493. * @param source Source pipeline.
  87494. * @param scene The scene to load the pipeline to.
  87495. * @param rootUrl The URL of the serialized pipeline.
  87496. * @returns An instantiated pipeline from the serialized object.
  87497. */
  87498. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  87499. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  87500. };
  87501. __decorate([
  87502. BABYLON.serialize()
  87503. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  87504. __decorate([
  87505. BABYLON.serialize()
  87506. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  87507. __decorate([
  87508. BABYLON.serialize()
  87509. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  87510. __decorate([
  87511. BABYLON.serialize()
  87512. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  87513. __decorate([
  87514. BABYLON.serialize()
  87515. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  87516. __decorate([
  87517. BABYLON.serialize()
  87518. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  87519. __decorate([
  87520. BABYLON.serialize()
  87521. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  87522. __decorate([
  87523. BABYLON.serialize()
  87524. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  87525. __decorate([
  87526. BABYLON.serialize()
  87527. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  87528. __decorate([
  87529. BABYLON.serialize()
  87530. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  87531. __decorate([
  87532. BABYLON.serialize()
  87533. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  87534. __decorate([
  87535. BABYLON.serialize()
  87536. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  87537. __decorate([
  87538. BABYLON.serialize()
  87539. ], DefaultRenderingPipeline.prototype, "samples", null);
  87540. __decorate([
  87541. BABYLON.serialize()
  87542. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  87543. __decorate([
  87544. BABYLON.serialize()
  87545. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  87546. __decorate([
  87547. BABYLON.serialize()
  87548. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  87549. __decorate([
  87550. BABYLON.serialize()
  87551. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  87552. return DefaultRenderingPipeline;
  87553. }(BABYLON.PostProcessRenderPipeline));
  87554. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  87555. })(BABYLON || (BABYLON = {}));
  87556. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  87557. var BABYLON;
  87558. (function (BABYLON) {
  87559. /**
  87560. * @hidden
  87561. */
  87562. var ImageProcessingConfigurationDefines = /** @class */ (function (_super) {
  87563. __extends(ImageProcessingConfigurationDefines, _super);
  87564. function ImageProcessingConfigurationDefines() {
  87565. var _this = _super.call(this) || this;
  87566. _this.IMAGEPROCESSING = false;
  87567. _this.VIGNETTE = false;
  87568. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  87569. _this.VIGNETTEBLENDMODEOPAQUE = false;
  87570. _this.TONEMAPPING = false;
  87571. _this.TONEMAPPING_ACES = false;
  87572. _this.CONTRAST = false;
  87573. _this.COLORCURVES = false;
  87574. _this.COLORGRADING = false;
  87575. _this.COLORGRADING3D = false;
  87576. _this.SAMPLER3DGREENDEPTH = false;
  87577. _this.SAMPLER3DBGRMAP = false;
  87578. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  87579. _this.EXPOSURE = false;
  87580. _this.rebuild();
  87581. return _this;
  87582. }
  87583. return ImageProcessingConfigurationDefines;
  87584. }(BABYLON.MaterialDefines));
  87585. BABYLON.ImageProcessingConfigurationDefines = ImageProcessingConfigurationDefines;
  87586. /**
  87587. * This groups together the common properties used for image processing either in direct forward pass
  87588. * or through post processing effect depending on the use of the image processing pipeline in your scene
  87589. * or not.
  87590. */
  87591. var ImageProcessingConfiguration = /** @class */ (function () {
  87592. function ImageProcessingConfiguration() {
  87593. /**
  87594. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  87595. */
  87596. this.colorCurves = new BABYLON.ColorCurves();
  87597. this._colorCurvesEnabled = false;
  87598. this._colorGradingEnabled = false;
  87599. this._colorGradingWithGreenDepth = true;
  87600. this._colorGradingBGR = true;
  87601. /** @hidden */
  87602. this._exposure = 1.0;
  87603. this._toneMappingEnabled = false;
  87604. this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
  87605. this._contrast = 1.0;
  87606. /**
  87607. * Vignette stretch size.
  87608. */
  87609. this.vignetteStretch = 0;
  87610. /**
  87611. * Vignette centre X Offset.
  87612. */
  87613. this.vignetteCentreX = 0;
  87614. /**
  87615. * Vignette centre Y Offset.
  87616. */
  87617. this.vignetteCentreY = 0;
  87618. /**
  87619. * Vignette weight or intensity of the vignette effect.
  87620. */
  87621. this.vignetteWeight = 1.5;
  87622. /**
  87623. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  87624. * if vignetteEnabled is set to true.
  87625. */
  87626. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  87627. /**
  87628. * Camera field of view used by the Vignette effect.
  87629. */
  87630. this.vignetteCameraFov = 0.5;
  87631. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  87632. this._vignetteEnabled = false;
  87633. this._applyByPostProcess = false;
  87634. this._isEnabled = true;
  87635. /**
  87636. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  87637. */
  87638. this.onUpdateParameters = new BABYLON.Observable();
  87639. }
  87640. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  87641. /**
  87642. * Gets wether the color curves effect is enabled.
  87643. */
  87644. get: function () {
  87645. return this._colorCurvesEnabled;
  87646. },
  87647. /**
  87648. * Sets wether the color curves effect is enabled.
  87649. */
  87650. set: function (value) {
  87651. if (this._colorCurvesEnabled === value) {
  87652. return;
  87653. }
  87654. this._colorCurvesEnabled = value;
  87655. this._updateParameters();
  87656. },
  87657. enumerable: true,
  87658. configurable: true
  87659. });
  87660. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingTexture", {
  87661. /**
  87662. * Color grading LUT texture used in the effect if colorGradingEnabled is set to true
  87663. */
  87664. get: function () {
  87665. return this._colorGradingTexture;
  87666. },
  87667. /**
  87668. * Color grading LUT texture used in the effect if colorGradingEnabled is set to true
  87669. */
  87670. set: function (value) {
  87671. if (this._colorGradingTexture === value) {
  87672. return;
  87673. }
  87674. this._colorGradingTexture = value;
  87675. this._updateParameters();
  87676. },
  87677. enumerable: true,
  87678. configurable: true
  87679. });
  87680. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  87681. /**
  87682. * Gets wether the color grading effect is enabled.
  87683. */
  87684. get: function () {
  87685. return this._colorGradingEnabled;
  87686. },
  87687. /**
  87688. * Sets wether the color grading effect is enabled.
  87689. */
  87690. set: function (value) {
  87691. if (this._colorGradingEnabled === value) {
  87692. return;
  87693. }
  87694. this._colorGradingEnabled = value;
  87695. this._updateParameters();
  87696. },
  87697. enumerable: true,
  87698. configurable: true
  87699. });
  87700. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  87701. /**
  87702. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  87703. */
  87704. get: function () {
  87705. return this._colorGradingWithGreenDepth;
  87706. },
  87707. /**
  87708. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  87709. */
  87710. set: function (value) {
  87711. if (this._colorGradingWithGreenDepth === value) {
  87712. return;
  87713. }
  87714. this._colorGradingWithGreenDepth = value;
  87715. this._updateParameters();
  87716. },
  87717. enumerable: true,
  87718. configurable: true
  87719. });
  87720. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  87721. /**
  87722. * Gets wether the color grading texture contains BGR values.
  87723. */
  87724. get: function () {
  87725. return this._colorGradingBGR;
  87726. },
  87727. /**
  87728. * Sets wether the color grading texture contains BGR values.
  87729. */
  87730. set: function (value) {
  87731. if (this._colorGradingBGR === value) {
  87732. return;
  87733. }
  87734. this._colorGradingBGR = value;
  87735. this._updateParameters();
  87736. },
  87737. enumerable: true,
  87738. configurable: true
  87739. });
  87740. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  87741. /**
  87742. * Gets the Exposure used in the effect.
  87743. */
  87744. get: function () {
  87745. return this._exposure;
  87746. },
  87747. /**
  87748. * Sets the Exposure used in the effect.
  87749. */
  87750. set: function (value) {
  87751. if (this._exposure === value) {
  87752. return;
  87753. }
  87754. this._exposure = value;
  87755. this._updateParameters();
  87756. },
  87757. enumerable: true,
  87758. configurable: true
  87759. });
  87760. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  87761. /**
  87762. * Gets wether the tone mapping effect is enabled.
  87763. */
  87764. get: function () {
  87765. return this._toneMappingEnabled;
  87766. },
  87767. /**
  87768. * Sets wether the tone mapping effect is enabled.
  87769. */
  87770. set: function (value) {
  87771. if (this._toneMappingEnabled === value) {
  87772. return;
  87773. }
  87774. this._toneMappingEnabled = value;
  87775. this._updateParameters();
  87776. },
  87777. enumerable: true,
  87778. configurable: true
  87779. });
  87780. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", {
  87781. /**
  87782. * Gets the type of tone mapping effect.
  87783. */
  87784. get: function () {
  87785. return this._toneMappingType;
  87786. },
  87787. /**
  87788. * Sets the type of tone mapping effect used in BabylonJS.
  87789. */
  87790. set: function (value) {
  87791. if (this._toneMappingType === value) {
  87792. return;
  87793. }
  87794. this._toneMappingType = value;
  87795. this._updateParameters();
  87796. },
  87797. enumerable: true,
  87798. configurable: true
  87799. });
  87800. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  87801. /**
  87802. * Gets the contrast used in the effect.
  87803. */
  87804. get: function () {
  87805. return this._contrast;
  87806. },
  87807. /**
  87808. * Sets the contrast used in the effect.
  87809. */
  87810. set: function (value) {
  87811. if (this._contrast === value) {
  87812. return;
  87813. }
  87814. this._contrast = value;
  87815. this._updateParameters();
  87816. },
  87817. enumerable: true,
  87818. configurable: true
  87819. });
  87820. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  87821. /**
  87822. * Gets the vignette blend mode allowing different kind of effect.
  87823. */
  87824. get: function () {
  87825. return this._vignetteBlendMode;
  87826. },
  87827. /**
  87828. * Sets the vignette blend mode allowing different kind of effect.
  87829. */
  87830. set: function (value) {
  87831. if (this._vignetteBlendMode === value) {
  87832. return;
  87833. }
  87834. this._vignetteBlendMode = value;
  87835. this._updateParameters();
  87836. },
  87837. enumerable: true,
  87838. configurable: true
  87839. });
  87840. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  87841. /**
  87842. * Gets wether the vignette effect is enabled.
  87843. */
  87844. get: function () {
  87845. return this._vignetteEnabled;
  87846. },
  87847. /**
  87848. * Sets wether the vignette effect is enabled.
  87849. */
  87850. set: function (value) {
  87851. if (this._vignetteEnabled === value) {
  87852. return;
  87853. }
  87854. this._vignetteEnabled = value;
  87855. this._updateParameters();
  87856. },
  87857. enumerable: true,
  87858. configurable: true
  87859. });
  87860. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  87861. /**
  87862. * Gets wether the image processing is applied through a post process or not.
  87863. */
  87864. get: function () {
  87865. return this._applyByPostProcess;
  87866. },
  87867. /**
  87868. * Sets wether the image processing is applied through a post process or not.
  87869. */
  87870. set: function (value) {
  87871. if (this._applyByPostProcess === value) {
  87872. return;
  87873. }
  87874. this._applyByPostProcess = value;
  87875. this._updateParameters();
  87876. },
  87877. enumerable: true,
  87878. configurable: true
  87879. });
  87880. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  87881. /**
  87882. * Gets wether the image processing is enabled or not.
  87883. */
  87884. get: function () {
  87885. return this._isEnabled;
  87886. },
  87887. /**
  87888. * Sets wether the image processing is enabled or not.
  87889. */
  87890. set: function (value) {
  87891. if (this._isEnabled === value) {
  87892. return;
  87893. }
  87894. this._isEnabled = value;
  87895. this._updateParameters();
  87896. },
  87897. enumerable: true,
  87898. configurable: true
  87899. });
  87900. /**
  87901. * Method called each time the image processing information changes requires to recompile the effect.
  87902. */
  87903. ImageProcessingConfiguration.prototype._updateParameters = function () {
  87904. this.onUpdateParameters.notifyObservers(this);
  87905. };
  87906. /**
  87907. * Gets the current class name.
  87908. * @return "ImageProcessingConfiguration"
  87909. */
  87910. ImageProcessingConfiguration.prototype.getClassName = function () {
  87911. return "ImageProcessingConfiguration";
  87912. };
  87913. /**
  87914. * Prepare the list of uniforms associated with the Image Processing effects.
  87915. * @param uniforms The list of uniforms used in the effect
  87916. * @param defines the list of defines currently in use
  87917. */
  87918. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  87919. if (defines.EXPOSURE) {
  87920. uniforms.push("exposureLinear");
  87921. }
  87922. if (defines.CONTRAST) {
  87923. uniforms.push("contrast");
  87924. }
  87925. if (defines.COLORGRADING) {
  87926. uniforms.push("colorTransformSettings");
  87927. }
  87928. if (defines.VIGNETTE) {
  87929. uniforms.push("vInverseScreenSize");
  87930. uniforms.push("vignetteSettings1");
  87931. uniforms.push("vignetteSettings2");
  87932. }
  87933. if (defines.COLORCURVES) {
  87934. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  87935. }
  87936. };
  87937. /**
  87938. * Prepare the list of samplers associated with the Image Processing effects.
  87939. * @param samplersList The list of uniforms used in the effect
  87940. * @param defines the list of defines currently in use
  87941. */
  87942. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  87943. if (defines.COLORGRADING) {
  87944. samplersList.push("txColorTransform");
  87945. }
  87946. };
  87947. /**
  87948. * Prepare the list of defines associated to the shader.
  87949. * @param defines the list of defines to complete
  87950. * @param forPostProcess Define if we are currently in post process mode or not
  87951. */
  87952. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  87953. if (forPostProcess === void 0) { forPostProcess = false; }
  87954. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  87955. defines.VIGNETTE = false;
  87956. defines.TONEMAPPING = false;
  87957. defines.TONEMAPPING_ACES = false;
  87958. defines.CONTRAST = false;
  87959. defines.EXPOSURE = false;
  87960. defines.COLORCURVES = false;
  87961. defines.COLORGRADING = false;
  87962. defines.COLORGRADING3D = false;
  87963. defines.IMAGEPROCESSING = false;
  87964. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  87965. return;
  87966. }
  87967. defines.VIGNETTE = this.vignetteEnabled;
  87968. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  87969. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  87970. defines.TONEMAPPING = this.toneMappingEnabled;
  87971. switch (this._toneMappingType) {
  87972. case ImageProcessingConfiguration.TONEMAPPING_ACES:
  87973. defines.TONEMAPPING_ACES = true;
  87974. break;
  87975. }
  87976. defines.CONTRAST = (this.contrast !== 1.0);
  87977. defines.EXPOSURE = (this.exposure !== 1.0);
  87978. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  87979. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  87980. if (defines.COLORGRADING) {
  87981. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  87982. }
  87983. else {
  87984. defines.COLORGRADING3D = false;
  87985. }
  87986. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  87987. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  87988. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  87989. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  87990. };
  87991. /**
  87992. * Returns true if all the image processing information are ready.
  87993. * @returns True if ready, otherwise, false
  87994. */
  87995. ImageProcessingConfiguration.prototype.isReady = function () {
  87996. // Color Grading texure can not be none blocking.
  87997. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  87998. };
  87999. /**
  88000. * Binds the image processing to the shader.
  88001. * @param effect The effect to bind to
  88002. * @param aspectRatio Define the current aspect ratio of the effect
  88003. */
  88004. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  88005. if (aspectRatio === void 0) { aspectRatio = 1; }
  88006. // Color Curves
  88007. if (this._colorCurvesEnabled && this.colorCurves) {
  88008. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  88009. }
  88010. // Vignette
  88011. if (this._vignetteEnabled) {
  88012. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  88013. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  88014. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  88015. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  88016. var vignetteScaleX = vignetteScaleY * aspectRatio;
  88017. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  88018. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  88019. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  88020. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  88021. var vignettePower = -2.0 * this.vignetteWeight;
  88022. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  88023. }
  88024. // Exposure
  88025. effect.setFloat("exposureLinear", this.exposure);
  88026. // Contrast
  88027. effect.setFloat("contrast", this.contrast);
  88028. // Color transform settings
  88029. if (this.colorGradingTexture) {
  88030. effect.setTexture("txColorTransform", this.colorGradingTexture);
  88031. var textureSize = this.colorGradingTexture.getSize().height;
  88032. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  88033. 0.5 / textureSize, // textureOffset
  88034. textureSize, // textureSize
  88035. this.colorGradingTexture.level // weight
  88036. );
  88037. }
  88038. };
  88039. /**
  88040. * Clones the current image processing instance.
  88041. * @return The cloned image processing
  88042. */
  88043. ImageProcessingConfiguration.prototype.clone = function () {
  88044. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  88045. };
  88046. /**
  88047. * Serializes the current image processing instance to a json representation.
  88048. * @return a JSON representation
  88049. */
  88050. ImageProcessingConfiguration.prototype.serialize = function () {
  88051. return BABYLON.SerializationHelper.Serialize(this);
  88052. };
  88053. /**
  88054. * Parses the image processing from a json representation.
  88055. * @param source the JSON source to parse
  88056. * @return The parsed image processing
  88057. */
  88058. ImageProcessingConfiguration.Parse = function (source) {
  88059. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  88060. };
  88061. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  88062. /**
  88063. * Used to apply the vignette as a mix with the pixel color.
  88064. */
  88065. get: function () {
  88066. return this._VIGNETTEMODE_MULTIPLY;
  88067. },
  88068. enumerable: true,
  88069. configurable: true
  88070. });
  88071. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  88072. /**
  88073. * Used to apply the vignette as a replacement of the pixel color.
  88074. */
  88075. get: function () {
  88076. return this._VIGNETTEMODE_OPAQUE;
  88077. },
  88078. enumerable: true,
  88079. configurable: true
  88080. });
  88081. /**
  88082. * Default tone mapping applied in BabylonJS.
  88083. */
  88084. ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
  88085. /**
  88086. * ACES Tone mapping (used by default in unreal and unity). This can help getting closer
  88087. * to other engines rendering to increase portability.
  88088. */
  88089. ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
  88090. // Static constants associated to the image processing.
  88091. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  88092. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  88093. __decorate([
  88094. BABYLON.serializeAsColorCurves()
  88095. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  88096. __decorate([
  88097. BABYLON.serialize()
  88098. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  88099. __decorate([
  88100. BABYLON.serializeAsTexture("colorGradingTexture")
  88101. ], ImageProcessingConfiguration.prototype, "_colorGradingTexture", void 0);
  88102. __decorate([
  88103. BABYLON.serialize()
  88104. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  88105. __decorate([
  88106. BABYLON.serialize()
  88107. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  88108. __decorate([
  88109. BABYLON.serialize()
  88110. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  88111. __decorate([
  88112. BABYLON.serialize()
  88113. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  88114. __decorate([
  88115. BABYLON.serialize()
  88116. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  88117. __decorate([
  88118. BABYLON.serialize()
  88119. ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0);
  88120. __decorate([
  88121. BABYLON.serialize()
  88122. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  88123. __decorate([
  88124. BABYLON.serialize()
  88125. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  88126. __decorate([
  88127. BABYLON.serialize()
  88128. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  88129. __decorate([
  88130. BABYLON.serialize()
  88131. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  88132. __decorate([
  88133. BABYLON.serialize()
  88134. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  88135. __decorate([
  88136. BABYLON.serializeAsColor4()
  88137. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  88138. __decorate([
  88139. BABYLON.serialize()
  88140. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  88141. __decorate([
  88142. BABYLON.serialize()
  88143. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  88144. __decorate([
  88145. BABYLON.serialize()
  88146. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  88147. __decorate([
  88148. BABYLON.serialize()
  88149. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  88150. __decorate([
  88151. BABYLON.serialize()
  88152. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  88153. return ImageProcessingConfiguration;
  88154. }());
  88155. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  88156. })(BABYLON || (BABYLON = {}));
  88157. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  88158. var BABYLON;
  88159. (function (BABYLON) {
  88160. /**
  88161. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  88162. * It can help converting any input color in a desired output one. This can then be used to create effects
  88163. * from sepia, black and white to sixties or futuristic rendering...
  88164. *
  88165. * The only supported format is currently 3dl.
  88166. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table
  88167. */
  88168. var ColorGradingTexture = /** @class */ (function (_super) {
  88169. __extends(ColorGradingTexture, _super);
  88170. /**
  88171. * Instantiates a ColorGradingTexture from the following parameters.
  88172. *
  88173. * @param url The location of the color gradind data (currently only supporting 3dl)
  88174. * @param scene The scene the texture will be used in
  88175. */
  88176. function ColorGradingTexture(url, scene) {
  88177. var _this = _super.call(this, scene) || this;
  88178. if (!url) {
  88179. return _this;
  88180. }
  88181. _this._engine = scene.getEngine();
  88182. _this._textureMatrix = BABYLON.Matrix.Identity();
  88183. _this.name = url;
  88184. _this.url = url;
  88185. _this.hasAlpha = false;
  88186. _this.isCube = false;
  88187. _this.is3D = _this._engine.webGLVersion > 1;
  88188. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88189. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88190. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88191. _this.anisotropicFilteringLevel = 1;
  88192. _this._texture = _this._getFromCache(url, true);
  88193. if (!_this._texture) {
  88194. if (!scene.useDelayedTextureLoading) {
  88195. _this.loadTexture();
  88196. }
  88197. else {
  88198. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  88199. }
  88200. }
  88201. return _this;
  88202. }
  88203. /**
  88204. * Returns the texture matrix used in most of the material.
  88205. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  88206. */
  88207. ColorGradingTexture.prototype.getTextureMatrix = function () {
  88208. return this._textureMatrix;
  88209. };
  88210. /**
  88211. * Occurs when the file being loaded is a .3dl LUT file.
  88212. */
  88213. ColorGradingTexture.prototype.load3dlTexture = function () {
  88214. var engine = this._engine;
  88215. var texture;
  88216. if (engine.webGLVersion === 1) {
  88217. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  88218. }
  88219. else {
  88220. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  88221. }
  88222. this._texture = texture;
  88223. var callback = function (text) {
  88224. if (typeof text !== "string") {
  88225. return;
  88226. }
  88227. var data = null;
  88228. var tempData = null;
  88229. var line;
  88230. var lines = text.split('\n');
  88231. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  88232. var maxColor = 0;
  88233. for (var i = 0; i < lines.length; i++) {
  88234. line = lines[i];
  88235. if (!ColorGradingTexture._noneEmptyLineRegex.test(line)) {
  88236. continue;
  88237. }
  88238. if (line.indexOf('#') === 0) {
  88239. continue;
  88240. }
  88241. var words = line.split(" ");
  88242. if (size === 0) {
  88243. // Number of space + one
  88244. size = words.length;
  88245. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  88246. tempData = new Float32Array(size * size * size * 4);
  88247. continue;
  88248. }
  88249. if (size != 0) {
  88250. var r = Math.max(parseInt(words[0]), 0);
  88251. var g = Math.max(parseInt(words[1]), 0);
  88252. var b = Math.max(parseInt(words[2]), 0);
  88253. maxColor = Math.max(r, maxColor);
  88254. maxColor = Math.max(g, maxColor);
  88255. maxColor = Math.max(b, maxColor);
  88256. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  88257. if (tempData) {
  88258. tempData[pixelStorageIndex + 0] = r;
  88259. tempData[pixelStorageIndex + 1] = g;
  88260. tempData[pixelStorageIndex + 2] = b;
  88261. }
  88262. // Keep for reference in case of back compat problems.
  88263. // pixelIndexSlice++;
  88264. // if (pixelIndexSlice % size == 0) {
  88265. // pixelIndexH++;
  88266. // pixelIndexSlice = 0;
  88267. // if (pixelIndexH % size == 0) {
  88268. // pixelIndexW++;
  88269. // pixelIndexH = 0;
  88270. // }
  88271. // }
  88272. pixelIndexH++;
  88273. if (pixelIndexH % size == 0) {
  88274. pixelIndexSlice++;
  88275. pixelIndexH = 0;
  88276. if (pixelIndexSlice % size == 0) {
  88277. pixelIndexW++;
  88278. pixelIndexSlice = 0;
  88279. }
  88280. }
  88281. }
  88282. }
  88283. if (tempData && data) {
  88284. for (var i = 0; i < tempData.length; i++) {
  88285. if (i > 0 && (i + 1) % 4 === 0) {
  88286. data[i] = 255;
  88287. }
  88288. else {
  88289. var value = tempData[i];
  88290. data[i] = (value / maxColor * 255);
  88291. }
  88292. }
  88293. }
  88294. if (texture.is3D) {
  88295. texture.updateSize(size, size, size);
  88296. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  88297. }
  88298. else {
  88299. texture.updateSize(size * size, size);
  88300. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  88301. }
  88302. };
  88303. var scene = this.getScene();
  88304. if (scene) {
  88305. scene._loadFile(this.url, callback);
  88306. }
  88307. else {
  88308. this._engine._loadFile(this.url, callback);
  88309. }
  88310. return this._texture;
  88311. };
  88312. /**
  88313. * Starts the loading process of the texture.
  88314. */
  88315. ColorGradingTexture.prototype.loadTexture = function () {
  88316. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  88317. this.load3dlTexture();
  88318. }
  88319. };
  88320. /**
  88321. * Clones the color gradind texture.
  88322. */
  88323. ColorGradingTexture.prototype.clone = function () {
  88324. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  88325. // Base texture
  88326. newTexture.level = this.level;
  88327. return newTexture;
  88328. };
  88329. /**
  88330. * Called during delayed load for textures.
  88331. */
  88332. ColorGradingTexture.prototype.delayLoad = function () {
  88333. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  88334. return;
  88335. }
  88336. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  88337. this._texture = this._getFromCache(this.url, true);
  88338. if (!this._texture) {
  88339. this.loadTexture();
  88340. }
  88341. };
  88342. /**
  88343. * Parses a color grading texture serialized by Babylon.
  88344. * @param parsedTexture The texture information being parsedTexture
  88345. * @param scene The scene to load the texture in
  88346. * @param rootUrl The root url of the data assets to load
  88347. * @return A color gradind texture
  88348. */
  88349. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  88350. var texture = null;
  88351. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  88352. texture = new ColorGradingTexture(parsedTexture.name, scene);
  88353. texture.name = parsedTexture.name;
  88354. texture.level = parsedTexture.level;
  88355. }
  88356. return texture;
  88357. };
  88358. /**
  88359. * Serializes the LUT texture to json format.
  88360. */
  88361. ColorGradingTexture.prototype.serialize = function () {
  88362. if (!this.name) {
  88363. return null;
  88364. }
  88365. var serializationObject = {};
  88366. serializationObject.name = this.name;
  88367. serializationObject.level = this.level;
  88368. serializationObject.customType = "BABYLON.ColorGradingTexture";
  88369. return serializationObject;
  88370. };
  88371. /**
  88372. * Empty line regex stored for GC.
  88373. */
  88374. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  88375. return ColorGradingTexture;
  88376. }(BABYLON.BaseTexture));
  88377. BABYLON.ColorGradingTexture = ColorGradingTexture;
  88378. })(BABYLON || (BABYLON = {}));
  88379. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  88380. var BABYLON;
  88381. (function (BABYLON) {
  88382. /**
  88383. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  88384. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  88385. * 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;
  88386. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  88387. */
  88388. var ColorCurves = /** @class */ (function () {
  88389. function ColorCurves() {
  88390. this._dirty = true;
  88391. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  88392. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  88393. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  88394. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  88395. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  88396. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  88397. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  88398. this._globalHue = 30;
  88399. this._globalDensity = 0;
  88400. this._globalSaturation = 0;
  88401. this._globalExposure = 0;
  88402. this._highlightsHue = 30;
  88403. this._highlightsDensity = 0;
  88404. this._highlightsSaturation = 0;
  88405. this._highlightsExposure = 0;
  88406. this._midtonesHue = 30;
  88407. this._midtonesDensity = 0;
  88408. this._midtonesSaturation = 0;
  88409. this._midtonesExposure = 0;
  88410. this._shadowsHue = 30;
  88411. this._shadowsDensity = 0;
  88412. this._shadowsSaturation = 0;
  88413. this._shadowsExposure = 0;
  88414. }
  88415. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  88416. /**
  88417. * Gets the global Hue value.
  88418. * 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).
  88419. */
  88420. get: function () {
  88421. return this._globalHue;
  88422. },
  88423. /**
  88424. * Sets the global Hue value.
  88425. * 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).
  88426. */
  88427. set: function (value) {
  88428. this._globalHue = value;
  88429. this._dirty = true;
  88430. },
  88431. enumerable: true,
  88432. configurable: true
  88433. });
  88434. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  88435. /**
  88436. * Gets the global Density value.
  88437. * 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.
  88438. * Values less than zero provide a filter of opposite hue.
  88439. */
  88440. get: function () {
  88441. return this._globalDensity;
  88442. },
  88443. /**
  88444. * Sets the global Density value.
  88445. * 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.
  88446. * Values less than zero provide a filter of opposite hue.
  88447. */
  88448. set: function (value) {
  88449. this._globalDensity = value;
  88450. this._dirty = true;
  88451. },
  88452. enumerable: true,
  88453. configurable: true
  88454. });
  88455. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  88456. /**
  88457. * Gets the global Saturation value.
  88458. * 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.
  88459. */
  88460. get: function () {
  88461. return this._globalSaturation;
  88462. },
  88463. /**
  88464. * Sets the global Saturation value.
  88465. * 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.
  88466. */
  88467. set: function (value) {
  88468. this._globalSaturation = value;
  88469. this._dirty = true;
  88470. },
  88471. enumerable: true,
  88472. configurable: true
  88473. });
  88474. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  88475. /**
  88476. * Gets the global Exposure value.
  88477. * 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.
  88478. */
  88479. get: function () {
  88480. return this._globalExposure;
  88481. },
  88482. /**
  88483. * Sets the global Exposure value.
  88484. * 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.
  88485. */
  88486. set: function (value) {
  88487. this._globalExposure = value;
  88488. this._dirty = true;
  88489. },
  88490. enumerable: true,
  88491. configurable: true
  88492. });
  88493. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  88494. /**
  88495. * Gets the highlights Hue value.
  88496. * 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).
  88497. */
  88498. get: function () {
  88499. return this._highlightsHue;
  88500. },
  88501. /**
  88502. * Sets the highlights Hue value.
  88503. * 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).
  88504. */
  88505. set: function (value) {
  88506. this._highlightsHue = value;
  88507. this._dirty = true;
  88508. },
  88509. enumerable: true,
  88510. configurable: true
  88511. });
  88512. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  88513. /**
  88514. * Gets the highlights Density value.
  88515. * 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.
  88516. * Values less than zero provide a filter of opposite hue.
  88517. */
  88518. get: function () {
  88519. return this._highlightsDensity;
  88520. },
  88521. /**
  88522. * Sets the highlights Density value.
  88523. * 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.
  88524. * Values less than zero provide a filter of opposite hue.
  88525. */
  88526. set: function (value) {
  88527. this._highlightsDensity = value;
  88528. this._dirty = true;
  88529. },
  88530. enumerable: true,
  88531. configurable: true
  88532. });
  88533. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  88534. /**
  88535. * Gets the highlights Saturation value.
  88536. * 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.
  88537. */
  88538. get: function () {
  88539. return this._highlightsSaturation;
  88540. },
  88541. /**
  88542. * Sets the highlights Saturation value.
  88543. * 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.
  88544. */
  88545. set: function (value) {
  88546. this._highlightsSaturation = value;
  88547. this._dirty = true;
  88548. },
  88549. enumerable: true,
  88550. configurable: true
  88551. });
  88552. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  88553. /**
  88554. * Gets the highlights Exposure value.
  88555. * 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.
  88556. */
  88557. get: function () {
  88558. return this._highlightsExposure;
  88559. },
  88560. /**
  88561. * Sets the highlights Exposure value.
  88562. * 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.
  88563. */
  88564. set: function (value) {
  88565. this._highlightsExposure = value;
  88566. this._dirty = true;
  88567. },
  88568. enumerable: true,
  88569. configurable: true
  88570. });
  88571. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  88572. /**
  88573. * Gets the midtones Hue value.
  88574. * 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).
  88575. */
  88576. get: function () {
  88577. return this._midtonesHue;
  88578. },
  88579. /**
  88580. * Sets the midtones Hue value.
  88581. * 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).
  88582. */
  88583. set: function (value) {
  88584. this._midtonesHue = value;
  88585. this._dirty = true;
  88586. },
  88587. enumerable: true,
  88588. configurable: true
  88589. });
  88590. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  88591. /**
  88592. * Gets the midtones Density value.
  88593. * 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.
  88594. * Values less than zero provide a filter of opposite hue.
  88595. */
  88596. get: function () {
  88597. return this._midtonesDensity;
  88598. },
  88599. /**
  88600. * Sets the midtones Density value.
  88601. * 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.
  88602. * Values less than zero provide a filter of opposite hue.
  88603. */
  88604. set: function (value) {
  88605. this._midtonesDensity = value;
  88606. this._dirty = true;
  88607. },
  88608. enumerable: true,
  88609. configurable: true
  88610. });
  88611. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  88612. /**
  88613. * Gets the midtones Saturation value.
  88614. * 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.
  88615. */
  88616. get: function () {
  88617. return this._midtonesSaturation;
  88618. },
  88619. /**
  88620. * Sets the midtones Saturation value.
  88621. * 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.
  88622. */
  88623. set: function (value) {
  88624. this._midtonesSaturation = value;
  88625. this._dirty = true;
  88626. },
  88627. enumerable: true,
  88628. configurable: true
  88629. });
  88630. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  88631. /**
  88632. * Gets the midtones Exposure value.
  88633. * 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.
  88634. */
  88635. get: function () {
  88636. return this._midtonesExposure;
  88637. },
  88638. /**
  88639. * Sets the midtones Exposure value.
  88640. * 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.
  88641. */
  88642. set: function (value) {
  88643. this._midtonesExposure = value;
  88644. this._dirty = true;
  88645. },
  88646. enumerable: true,
  88647. configurable: true
  88648. });
  88649. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  88650. /**
  88651. * Gets the shadows Hue value.
  88652. * 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).
  88653. */
  88654. get: function () {
  88655. return this._shadowsHue;
  88656. },
  88657. /**
  88658. * Sets the shadows Hue value.
  88659. * 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).
  88660. */
  88661. set: function (value) {
  88662. this._shadowsHue = value;
  88663. this._dirty = true;
  88664. },
  88665. enumerable: true,
  88666. configurable: true
  88667. });
  88668. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  88669. /**
  88670. * Gets the shadows Density value.
  88671. * 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.
  88672. * Values less than zero provide a filter of opposite hue.
  88673. */
  88674. get: function () {
  88675. return this._shadowsDensity;
  88676. },
  88677. /**
  88678. * Sets the shadows Density value.
  88679. * 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.
  88680. * Values less than zero provide a filter of opposite hue.
  88681. */
  88682. set: function (value) {
  88683. this._shadowsDensity = value;
  88684. this._dirty = true;
  88685. },
  88686. enumerable: true,
  88687. configurable: true
  88688. });
  88689. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  88690. /**
  88691. * Gets the shadows Saturation value.
  88692. * 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.
  88693. */
  88694. get: function () {
  88695. return this._shadowsSaturation;
  88696. },
  88697. /**
  88698. * Sets the shadows Saturation value.
  88699. * 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.
  88700. */
  88701. set: function (value) {
  88702. this._shadowsSaturation = value;
  88703. this._dirty = true;
  88704. },
  88705. enumerable: true,
  88706. configurable: true
  88707. });
  88708. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  88709. /**
  88710. * Gets the shadows Exposure value.
  88711. * 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.
  88712. */
  88713. get: function () {
  88714. return this._shadowsExposure;
  88715. },
  88716. /**
  88717. * Sets the shadows Exposure value.
  88718. * 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.
  88719. */
  88720. set: function (value) {
  88721. this._shadowsExposure = value;
  88722. this._dirty = true;
  88723. },
  88724. enumerable: true,
  88725. configurable: true
  88726. });
  88727. /**
  88728. * Returns the class name
  88729. * @returns The class name
  88730. */
  88731. ColorCurves.prototype.getClassName = function () {
  88732. return "ColorCurves";
  88733. };
  88734. /**
  88735. * Binds the color curves to the shader.
  88736. * @param colorCurves The color curve to bind
  88737. * @param effect The effect to bind to
  88738. * @param positiveUniform The positive uniform shader parameter
  88739. * @param neutralUniform The neutral uniform shader parameter
  88740. * @param negativeUniform The negative uniform shader parameter
  88741. */
  88742. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  88743. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  88744. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  88745. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  88746. if (colorCurves._dirty) {
  88747. colorCurves._dirty = false;
  88748. // Fill in global info.
  88749. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  88750. // Compute highlights info.
  88751. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  88752. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  88753. // Compute midtones info.
  88754. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  88755. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  88756. // Compute shadows info.
  88757. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  88758. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  88759. // Compute deltas (neutral is midtones).
  88760. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  88761. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  88762. }
  88763. if (effect) {
  88764. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  88765. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  88766. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  88767. }
  88768. };
  88769. /**
  88770. * Prepare the list of uniforms associated with the ColorCurves effects.
  88771. * @param uniformsList The list of uniforms used in the effect
  88772. */
  88773. ColorCurves.PrepareUniforms = function (uniformsList) {
  88774. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  88775. };
  88776. /**
  88777. * Returns color grading data based on a hue, density, saturation and exposure value.
  88778. * @param filterHue The hue of the color filter.
  88779. * @param filterDensity The density of the color filter.
  88780. * @param saturation The saturation.
  88781. * @param exposure The exposure.
  88782. * @param result The result data container.
  88783. */
  88784. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  88785. if (hue == null) {
  88786. return;
  88787. }
  88788. hue = ColorCurves.clamp(hue, 0, 360);
  88789. density = ColorCurves.clamp(density, -100, 100);
  88790. saturation = ColorCurves.clamp(saturation, -100, 100);
  88791. exposure = ColorCurves.clamp(exposure, -100, 100);
  88792. // Remap the slider/config filter density with non-linear mapping and also scale by half
  88793. // so that the maximum filter density is only 50% control. This provides fine control
  88794. // for small values and reasonable range.
  88795. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  88796. density *= 0.5;
  88797. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  88798. if (density < 0) {
  88799. density *= -1;
  88800. hue = (hue + 180) % 360;
  88801. }
  88802. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  88803. result.scaleToRef(2, result);
  88804. result.a = 1 + 0.01 * saturation;
  88805. };
  88806. /**
  88807. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  88808. * @param value The input slider value in range [-100,100].
  88809. * @returns Adjusted value.
  88810. */
  88811. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  88812. value /= 100;
  88813. var x = Math.abs(value);
  88814. x = Math.pow(x, 2);
  88815. if (value < 0) {
  88816. x *= -1;
  88817. }
  88818. x *= 100;
  88819. return x;
  88820. };
  88821. /**
  88822. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  88823. * @param hue The hue (H) input.
  88824. * @param saturation The saturation (S) input.
  88825. * @param brightness The brightness (B) input.
  88826. * @result An RGBA color represented as Vector4.
  88827. */
  88828. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  88829. var h = ColorCurves.clamp(hue, 0, 360);
  88830. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  88831. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  88832. if (s === 0) {
  88833. result.r = v;
  88834. result.g = v;
  88835. result.b = v;
  88836. }
  88837. else {
  88838. // sector 0 to 5
  88839. h /= 60;
  88840. var i = Math.floor(h);
  88841. // fractional part of h
  88842. var f = h - i;
  88843. var p = v * (1 - s);
  88844. var q = v * (1 - s * f);
  88845. var t = v * (1 - s * (1 - f));
  88846. switch (i) {
  88847. case 0:
  88848. result.r = v;
  88849. result.g = t;
  88850. result.b = p;
  88851. break;
  88852. case 1:
  88853. result.r = q;
  88854. result.g = v;
  88855. result.b = p;
  88856. break;
  88857. case 2:
  88858. result.r = p;
  88859. result.g = v;
  88860. result.b = t;
  88861. break;
  88862. case 3:
  88863. result.r = p;
  88864. result.g = q;
  88865. result.b = v;
  88866. break;
  88867. case 4:
  88868. result.r = t;
  88869. result.g = p;
  88870. result.b = v;
  88871. break;
  88872. default: // case 5:
  88873. result.r = v;
  88874. result.g = p;
  88875. result.b = q;
  88876. break;
  88877. }
  88878. }
  88879. result.a = 1;
  88880. };
  88881. /**
  88882. * Returns a value clamped between min and max
  88883. * @param value The value to clamp
  88884. * @param min The minimum of value
  88885. * @param max The maximum of value
  88886. * @returns The clamped value.
  88887. */
  88888. ColorCurves.clamp = function (value, min, max) {
  88889. return Math.min(Math.max(value, min), max);
  88890. };
  88891. /**
  88892. * Clones the current color curve instance.
  88893. * @return The cloned curves
  88894. */
  88895. ColorCurves.prototype.clone = function () {
  88896. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  88897. };
  88898. /**
  88899. * Serializes the current color curve instance to a json representation.
  88900. * @return a JSON representation
  88901. */
  88902. ColorCurves.prototype.serialize = function () {
  88903. return BABYLON.SerializationHelper.Serialize(this);
  88904. };
  88905. /**
  88906. * Parses the color curve from a json representation.
  88907. * @param source the JSON source to parse
  88908. * @return The parsed curves
  88909. */
  88910. ColorCurves.Parse = function (source) {
  88911. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  88912. };
  88913. __decorate([
  88914. BABYLON.serialize()
  88915. ], ColorCurves.prototype, "_globalHue", void 0);
  88916. __decorate([
  88917. BABYLON.serialize()
  88918. ], ColorCurves.prototype, "_globalDensity", void 0);
  88919. __decorate([
  88920. BABYLON.serialize()
  88921. ], ColorCurves.prototype, "_globalSaturation", void 0);
  88922. __decorate([
  88923. BABYLON.serialize()
  88924. ], ColorCurves.prototype, "_globalExposure", void 0);
  88925. __decorate([
  88926. BABYLON.serialize()
  88927. ], ColorCurves.prototype, "_highlightsHue", void 0);
  88928. __decorate([
  88929. BABYLON.serialize()
  88930. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  88931. __decorate([
  88932. BABYLON.serialize()
  88933. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  88934. __decorate([
  88935. BABYLON.serialize()
  88936. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  88937. __decorate([
  88938. BABYLON.serialize()
  88939. ], ColorCurves.prototype, "_midtonesHue", void 0);
  88940. __decorate([
  88941. BABYLON.serialize()
  88942. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  88943. __decorate([
  88944. BABYLON.serialize()
  88945. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  88946. __decorate([
  88947. BABYLON.serialize()
  88948. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  88949. return ColorCurves;
  88950. }());
  88951. BABYLON.ColorCurves = ColorCurves;
  88952. })(BABYLON || (BABYLON = {}));
  88953. //# sourceMappingURL=babylon.colorCurves.js.map
  88954. var BABYLON;
  88955. (function (BABYLON) {
  88956. /**
  88957. * Post process which applies a refractin texture
  88958. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#refraction
  88959. */
  88960. var RefractionPostProcess = /** @class */ (function (_super) {
  88961. __extends(RefractionPostProcess, _super);
  88962. /**
  88963. * Initializes the RefractionPostProcess
  88964. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#refraction
  88965. * @param name The name of the effect.
  88966. * @param refractionTextureUrl Url of the refraction texture to use
  88967. * @param color the base color of the refraction (used to taint the rendering)
  88968. * @param depth simulated refraction depth
  88969. * @param colorLevel the coefficient of the base color (0 to remove base color tainting)
  88970. * @param camera The camera to apply the render pass to.
  88971. * @param options The required width/height ratio to downsize to before computing the render pass.
  88972. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  88973. * @param engine The engine which the post process will be applied. (default: current engine)
  88974. * @param reusable If the post process can be reused on the same frame. (default: false)
  88975. */
  88976. function RefractionPostProcess(name, refractionTextureUrl,
  88977. /** the base color of the refraction (used to taint the rendering) */
  88978. color,
  88979. /** simulated refraction depth */
  88980. depth,
  88981. /** the coefficient of the base color (0 to remove base color tainting) */
  88982. colorLevel, options, camera, samplingMode, engine, reusable) {
  88983. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  88984. _this.color = color;
  88985. _this.depth = depth;
  88986. _this.colorLevel = colorLevel;
  88987. _this._ownRefractionTexture = true;
  88988. _this.onActivateObservable.add(function (cam) {
  88989. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  88990. });
  88991. _this.onApplyObservable.add(function (effect) {
  88992. effect.setColor3("baseColor", _this.color);
  88993. effect.setFloat("depth", _this.depth);
  88994. effect.setFloat("colorLevel", _this.colorLevel);
  88995. effect.setTexture("refractionSampler", _this._refTexture);
  88996. });
  88997. return _this;
  88998. }
  88999. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  89000. /**
  89001. * Gets or sets the refraction texture
  89002. * Please note that you are responsible for disposing the texture if you set it manually
  89003. */
  89004. get: function () {
  89005. return this._refTexture;
  89006. },
  89007. set: function (value) {
  89008. if (this._refTexture && this._ownRefractionTexture) {
  89009. this._refTexture.dispose();
  89010. }
  89011. this._refTexture = value;
  89012. this._ownRefractionTexture = false;
  89013. },
  89014. enumerable: true,
  89015. configurable: true
  89016. });
  89017. // Methods
  89018. /**
  89019. * Disposes of the post process
  89020. * @param camera Camera to dispose post process on
  89021. */
  89022. RefractionPostProcess.prototype.dispose = function (camera) {
  89023. if (this._refTexture && this._ownRefractionTexture) {
  89024. this._refTexture.dispose();
  89025. this._refTexture = null;
  89026. }
  89027. _super.prototype.dispose.call(this, camera);
  89028. };
  89029. return RefractionPostProcess;
  89030. }(BABYLON.PostProcess));
  89031. BABYLON.RefractionPostProcess = RefractionPostProcess;
  89032. })(BABYLON || (BABYLON = {}));
  89033. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  89034. var BABYLON;
  89035. (function (BABYLON) {
  89036. /**
  89037. * Post process used to render in black and white
  89038. */
  89039. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  89040. __extends(BlackAndWhitePostProcess, _super);
  89041. /**
  89042. * Creates a black and white post process
  89043. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#black-and-white
  89044. * @param name The name of the effect.
  89045. * @param options The required width/height ratio to downsize to before computing the render pass.
  89046. * @param camera The camera to apply the render pass to.
  89047. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  89048. * @param engine The engine which the post process will be applied. (default: current engine)
  89049. * @param reusable If the post process can be reused on the same frame. (default: false)
  89050. */
  89051. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  89052. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  89053. /**
  89054. * Linear about to convert he result to black and white (default: 1)
  89055. */
  89056. _this.degree = 1;
  89057. _this.onApplyObservable.add(function (effect) {
  89058. effect.setFloat("degree", _this.degree);
  89059. });
  89060. return _this;
  89061. }
  89062. return BlackAndWhitePostProcess;
  89063. }(BABYLON.PostProcess));
  89064. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  89065. })(BABYLON || (BABYLON = {}));
  89066. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  89067. var BABYLON;
  89068. (function (BABYLON) {
  89069. /**
  89070. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  89071. * input texture to perform effects such as edge detection or sharpening
  89072. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  89073. */
  89074. var ConvolutionPostProcess = /** @class */ (function (_super) {
  89075. __extends(ConvolutionPostProcess, _super);
  89076. /**
  89077. * Creates a new instance ConvolutionPostProcess
  89078. * @param name The name of the effect.
  89079. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  89080. * @param options The required width/height ratio to downsize to before computing the render pass.
  89081. * @param camera The camera to apply the render pass to.
  89082. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  89083. * @param engine The engine which the post process will be applied. (default: current engine)
  89084. * @param reusable If the post process can be reused on the same frame. (default: false)
  89085. * @param textureType Type of textures used when performing the post process. (default: 0)
  89086. */
  89087. function ConvolutionPostProcess(name,
  89088. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  89089. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  89090. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  89091. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  89092. _this.kernel = kernel;
  89093. _this.onApply = function (effect) {
  89094. effect.setFloat2("screenSize", _this.width, _this.height);
  89095. effect.setArray("kernel", _this.kernel);
  89096. };
  89097. return _this;
  89098. }
  89099. // Statics
  89100. /**
  89101. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  89102. */
  89103. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  89104. /**
  89105. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  89106. */
  89107. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  89108. /**
  89109. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  89110. */
  89111. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  89112. /**
  89113. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  89114. */
  89115. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  89116. /**
  89117. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  89118. */
  89119. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  89120. /**
  89121. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  89122. */
  89123. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  89124. return ConvolutionPostProcess;
  89125. }(BABYLON.PostProcess));
  89126. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  89127. })(BABYLON || (BABYLON = {}));
  89128. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  89129. var BABYLON;
  89130. (function (BABYLON) {
  89131. /**
  89132. * Applies a kernel filter to the image
  89133. */
  89134. var FilterPostProcess = /** @class */ (function (_super) {
  89135. __extends(FilterPostProcess, _super);
  89136. /**
  89137. *
  89138. * @param name The name of the effect.
  89139. * @param kernelMatrix The matrix to be applied to the image
  89140. * @param options The required width/height ratio to downsize to before computing the render pass.
  89141. * @param camera The camera to apply the render pass to.
  89142. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  89143. * @param engine The engine which the post process will be applied. (default: current engine)
  89144. * @param reusable If the post process can be reused on the same frame. (default: false)
  89145. */
  89146. function FilterPostProcess(name,
  89147. /** The matrix to be applied to the image */
  89148. kernelMatrix, options, camera, samplingMode, engine, reusable) {
  89149. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  89150. _this.kernelMatrix = kernelMatrix;
  89151. _this.onApply = function (effect) {
  89152. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  89153. };
  89154. return _this;
  89155. }
  89156. return FilterPostProcess;
  89157. }(BABYLON.PostProcess));
  89158. BABYLON.FilterPostProcess = FilterPostProcess;
  89159. })(BABYLON || (BABYLON = {}));
  89160. //# sourceMappingURL=babylon.filterPostProcess.js.map
  89161. var BABYLON;
  89162. (function (BABYLON) {
  89163. /**
  89164. * Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  89165. */
  89166. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  89167. __extends(VolumetricLightScatteringPostProcess, _super);
  89168. /**
  89169. * @constructor
  89170. * @param name The post-process name
  89171. * @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)
  89172. * @param camera The camera that the post-process will be attached to
  89173. * @param mesh The mesh used to create the light scattering
  89174. * @param samples The post-process quality, default 100
  89175. * @param samplingModeThe post-process filtering mode
  89176. * @param engine The babylon engine
  89177. * @param reusable If the post-process is reusable
  89178. * @param scene The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided
  89179. */
  89180. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  89181. if (samples === void 0) { samples = 100; }
  89182. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  89183. 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;
  89184. _this._screenCoordinates = BABYLON.Vector2.Zero();
  89185. /**
  89186. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  89187. */
  89188. _this.customMeshPosition = BABYLON.Vector3.Zero();
  89189. /**
  89190. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  89191. */
  89192. _this.useCustomMeshPosition = false;
  89193. /**
  89194. * If the post-process should inverse the light scattering direction
  89195. */
  89196. _this.invert = true;
  89197. /**
  89198. * Array containing the excluded meshes not rendered in the internal pass
  89199. */
  89200. _this.excludedMeshes = new Array();
  89201. /**
  89202. * Controls the overall intensity of the post-process
  89203. */
  89204. _this.exposure = 0.3;
  89205. /**
  89206. * Dissipates each sample's contribution in range [0, 1]
  89207. */
  89208. _this.decay = 0.96815;
  89209. /**
  89210. * Controls the overall intensity of each sample
  89211. */
  89212. _this.weight = 0.58767;
  89213. /**
  89214. * Controls the density of each sample
  89215. */
  89216. _this.density = 0.926;
  89217. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  89218. engine = scene.getEngine();
  89219. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  89220. // Configure mesh
  89221. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  89222. // Configure
  89223. _this._createPass(scene, ratio.passRatio || ratio);
  89224. _this.onActivate = function (camera) {
  89225. if (!_this.isSupported) {
  89226. _this.dispose(camera);
  89227. }
  89228. _this.onActivate = null;
  89229. };
  89230. _this.onApplyObservable.add(function (effect) {
  89231. _this._updateMeshScreenCoordinates(scene);
  89232. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  89233. effect.setFloat("exposure", _this.exposure);
  89234. effect.setFloat("decay", _this.decay);
  89235. effect.setFloat("weight", _this.weight);
  89236. effect.setFloat("density", _this.density);
  89237. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  89238. });
  89239. return _this;
  89240. }
  89241. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  89242. /**
  89243. * @hidden
  89244. * VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead
  89245. */
  89246. get: function () {
  89247. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  89248. return false;
  89249. },
  89250. set: function (useDiffuseColor) {
  89251. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  89252. },
  89253. enumerable: true,
  89254. configurable: true
  89255. });
  89256. /**
  89257. * Returns the string "VolumetricLightScatteringPostProcess"
  89258. * @returns "VolumetricLightScatteringPostProcess"
  89259. */
  89260. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  89261. return "VolumetricLightScatteringPostProcess";
  89262. };
  89263. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  89264. var mesh = subMesh.getMesh();
  89265. // Render this.mesh as default
  89266. if (mesh === this.mesh && mesh.material) {
  89267. return mesh.material.isReady(mesh);
  89268. }
  89269. var defines = [];
  89270. var attribs = [BABYLON.VertexBuffer.PositionKind];
  89271. var material = subMesh.getMaterial();
  89272. // Alpha test
  89273. if (material) {
  89274. if (material.needAlphaTesting()) {
  89275. defines.push("#define ALPHATEST");
  89276. }
  89277. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  89278. attribs.push(BABYLON.VertexBuffer.UVKind);
  89279. defines.push("#define UV1");
  89280. }
  89281. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  89282. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  89283. defines.push("#define UV2");
  89284. }
  89285. }
  89286. // Bones
  89287. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  89288. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  89289. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  89290. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  89291. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  89292. }
  89293. else {
  89294. defines.push("#define NUM_BONE_INFLUENCERS 0");
  89295. }
  89296. // Instances
  89297. if (useInstances) {
  89298. defines.push("#define INSTANCES");
  89299. attribs.push("world0");
  89300. attribs.push("world1");
  89301. attribs.push("world2");
  89302. attribs.push("world3");
  89303. }
  89304. // Get correct effect
  89305. var join = defines.join("\n");
  89306. if (this._cachedDefines !== join) {
  89307. this._cachedDefines = join;
  89308. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  89309. }
  89310. return this._volumetricLightScatteringPass.isReady();
  89311. };
  89312. /**
  89313. * Sets the new light position for light scattering effect
  89314. * @param position The new custom light position
  89315. */
  89316. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  89317. this.customMeshPosition = position;
  89318. };
  89319. /**
  89320. * Returns the light position for light scattering effect
  89321. * @return Vector3 The custom light position
  89322. */
  89323. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  89324. return this.customMeshPosition;
  89325. };
  89326. /**
  89327. * Disposes the internal assets and detaches the post-process from the camera
  89328. */
  89329. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  89330. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  89331. if (rttIndex !== -1) {
  89332. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  89333. }
  89334. this._volumetricLightScatteringRTT.dispose();
  89335. _super.prototype.dispose.call(this, camera);
  89336. };
  89337. /**
  89338. * Returns the render target texture used by the post-process
  89339. * @return the render target texture used by the post-process
  89340. */
  89341. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  89342. return this._volumetricLightScatteringRTT;
  89343. };
  89344. // Private methods
  89345. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  89346. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  89347. return true;
  89348. }
  89349. return false;
  89350. };
  89351. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  89352. var _this = this;
  89353. var engine = scene.getEngine();
  89354. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  89355. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89356. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89357. this._volumetricLightScatteringRTT.renderList = null;
  89358. this._volumetricLightScatteringRTT.renderParticles = false;
  89359. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  89360. var camera = this.getCamera();
  89361. if (camera) {
  89362. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  89363. }
  89364. else {
  89365. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  89366. }
  89367. // Custom render function for submeshes
  89368. var renderSubMesh = function (subMesh) {
  89369. var mesh = subMesh.getRenderingMesh();
  89370. if (_this._meshExcluded(mesh)) {
  89371. return;
  89372. }
  89373. var material = subMesh.getMaterial();
  89374. if (!material) {
  89375. return;
  89376. }
  89377. var scene = mesh.getScene();
  89378. var engine = scene.getEngine();
  89379. // Culling
  89380. engine.setState(material.backFaceCulling);
  89381. // Managing instances
  89382. var batch = mesh._getInstancesRenderList(subMesh._id);
  89383. if (batch.mustReturn) {
  89384. return;
  89385. }
  89386. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  89387. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  89388. var effect = _this._volumetricLightScatteringPass;
  89389. if (mesh === _this.mesh) {
  89390. if (subMesh.effect) {
  89391. effect = subMesh.effect;
  89392. }
  89393. else {
  89394. effect = material.getEffect();
  89395. }
  89396. }
  89397. engine.enableEffect(effect);
  89398. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  89399. if (mesh === _this.mesh) {
  89400. material.bind(mesh.getWorldMatrix(), mesh);
  89401. }
  89402. else {
  89403. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  89404. // Alpha test
  89405. if (material && material.needAlphaTesting()) {
  89406. var alphaTexture = material.getAlphaTestTexture();
  89407. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  89408. if (alphaTexture) {
  89409. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  89410. }
  89411. }
  89412. // Bones
  89413. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  89414. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  89415. }
  89416. }
  89417. // Draw
  89418. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  89419. }
  89420. };
  89421. // Render target texture callbacks
  89422. var savedSceneClearColor;
  89423. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  89424. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  89425. savedSceneClearColor = scene.clearColor;
  89426. scene.clearColor = sceneClearColor;
  89427. });
  89428. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  89429. scene.clearColor = savedSceneClearColor;
  89430. });
  89431. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  89432. var engine = scene.getEngine();
  89433. var index;
  89434. if (depthOnlySubMeshes.length) {
  89435. engine.setColorWrite(false);
  89436. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  89437. renderSubMesh(depthOnlySubMeshes.data[index]);
  89438. }
  89439. engine.setColorWrite(true);
  89440. }
  89441. for (index = 0; index < opaqueSubMeshes.length; index++) {
  89442. renderSubMesh(opaqueSubMeshes.data[index]);
  89443. }
  89444. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  89445. renderSubMesh(alphaTestSubMeshes.data[index]);
  89446. }
  89447. if (transparentSubMeshes.length) {
  89448. // Sort sub meshes
  89449. for (index = 0; index < transparentSubMeshes.length; index++) {
  89450. var submesh = transparentSubMeshes.data[index];
  89451. var boundingInfo = submesh.getBoundingInfo();
  89452. if (boundingInfo && scene.activeCamera) {
  89453. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  89454. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  89455. }
  89456. }
  89457. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  89458. sortedArray.sort(function (a, b) {
  89459. // Alpha index first
  89460. if (a._alphaIndex > b._alphaIndex) {
  89461. return 1;
  89462. }
  89463. if (a._alphaIndex < b._alphaIndex) {
  89464. return -1;
  89465. }
  89466. // Then distance to camera
  89467. if (a._distanceToCamera < b._distanceToCamera) {
  89468. return 1;
  89469. }
  89470. if (a._distanceToCamera > b._distanceToCamera) {
  89471. return -1;
  89472. }
  89473. return 0;
  89474. });
  89475. // Render sub meshes
  89476. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  89477. for (index = 0; index < sortedArray.length; index++) {
  89478. renderSubMesh(sortedArray[index]);
  89479. }
  89480. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  89481. }
  89482. };
  89483. };
  89484. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  89485. var transform = scene.getTransformMatrix();
  89486. var meshPosition;
  89487. if (this.useCustomMeshPosition) {
  89488. meshPosition = this.customMeshPosition;
  89489. }
  89490. else if (this.attachedNode) {
  89491. meshPosition = this.attachedNode.position;
  89492. }
  89493. else {
  89494. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  89495. }
  89496. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  89497. this._screenCoordinates.x = pos.x / this._viewPort.width;
  89498. this._screenCoordinates.y = pos.y / this._viewPort.height;
  89499. if (this.invert) {
  89500. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  89501. }
  89502. };
  89503. // Static methods
  89504. /**
  89505. * Creates a default mesh for the Volumeric Light Scattering post-process
  89506. * @param name The mesh name
  89507. * @param scene The scene where to create the mesh
  89508. * @return the default mesh
  89509. */
  89510. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  89511. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  89512. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  89513. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  89514. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  89515. mesh.material = material;
  89516. return mesh;
  89517. };
  89518. __decorate([
  89519. BABYLON.serializeAsVector3()
  89520. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  89521. __decorate([
  89522. BABYLON.serialize()
  89523. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  89524. __decorate([
  89525. BABYLON.serialize()
  89526. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  89527. __decorate([
  89528. BABYLON.serializeAsMeshReference()
  89529. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  89530. __decorate([
  89531. BABYLON.serialize()
  89532. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  89533. __decorate([
  89534. BABYLON.serialize()
  89535. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  89536. __decorate([
  89537. BABYLON.serialize()
  89538. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  89539. __decorate([
  89540. BABYLON.serialize()
  89541. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  89542. __decorate([
  89543. BABYLON.serialize()
  89544. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  89545. return VolumetricLightScatteringPostProcess;
  89546. }(BABYLON.PostProcess));
  89547. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  89548. })(BABYLON || (BABYLON = {}));
  89549. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  89550. var BABYLON;
  89551. (function (BABYLON) {
  89552. /**
  89553. *
  89554. * This post-process allows the modification of rendered colors by using
  89555. * a 'look-up table' (LUT). This effect is also called Color Grading.
  89556. *
  89557. * The object needs to be provided an url to a texture containing the color
  89558. * look-up table: the texture must be 256 pixels wide and 16 pixels high.
  89559. * Use an image editing software to tweak the LUT to match your needs.
  89560. *
  89561. * For an example of a color LUT, see here:
  89562. * @see http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  89563. * For explanations on color grading, see here:
  89564. * @see http://udn.epicgames.com/Three/ColorGrading.html
  89565. *
  89566. */
  89567. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  89568. __extends(ColorCorrectionPostProcess, _super);
  89569. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  89570. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  89571. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  89572. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  89573. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89574. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89575. _this.onApply = function (effect) {
  89576. effect.setTexture("colorTable", _this._colorTableTexture);
  89577. };
  89578. return _this;
  89579. }
  89580. return ColorCorrectionPostProcess;
  89581. }(BABYLON.PostProcess));
  89582. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  89583. })(BABYLON || (BABYLON = {}));
  89584. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  89585. var BABYLON;
  89586. (function (BABYLON) {
  89587. /** Defines operator used for tonemapping */
  89588. var TonemappingOperator;
  89589. (function (TonemappingOperator) {
  89590. /** Hable */
  89591. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  89592. /** Reinhard */
  89593. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  89594. /** HejiDawson */
  89595. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  89596. /** Photographic */
  89597. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  89598. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  89599. /**
  89600. * Defines a post process to apply tone mapping
  89601. */
  89602. var TonemapPostProcess = /** @class */ (function (_super) {
  89603. __extends(TonemapPostProcess, _super);
  89604. /**
  89605. * Creates a new TonemapPostProcess
  89606. * @param name defines the name of the postprocess
  89607. * @param _operator defines the operator to use
  89608. * @param exposureAdjustment defines the required exposure adjustement
  89609. * @param camera defines the camera to use (can be null)
  89610. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  89611. * @param engine defines the hosting engine (can be ignore if camera is set)
  89612. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  89613. */
  89614. function TonemapPostProcess(name, _operator,
  89615. /** Defines the required exposure adjustement */
  89616. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  89617. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  89618. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  89619. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  89620. _this._operator = _operator;
  89621. _this.exposureAdjustment = exposureAdjustment;
  89622. var defines = "#define ";
  89623. if (_this._operator === TonemappingOperator.Hable) {
  89624. defines += "HABLE_TONEMAPPING";
  89625. }
  89626. else if (_this._operator === TonemappingOperator.Reinhard) {
  89627. defines += "REINHARD_TONEMAPPING";
  89628. }
  89629. else if (_this._operator === TonemappingOperator.HejiDawson) {
  89630. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  89631. }
  89632. else if (_this._operator === TonemappingOperator.Photographic) {
  89633. defines += "PHOTOGRAPHIC_TONEMAPPING";
  89634. }
  89635. //sadly a second call to create the effect.
  89636. _this.updateEffect(defines);
  89637. _this.onApply = function (effect) {
  89638. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  89639. };
  89640. return _this;
  89641. }
  89642. return TonemapPostProcess;
  89643. }(BABYLON.PostProcess));
  89644. BABYLON.TonemapPostProcess = TonemapPostProcess;
  89645. })(BABYLON || (BABYLON = {}));
  89646. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  89647. var BABYLON;
  89648. (function (BABYLON) {
  89649. /**
  89650. * DisplayPassPostProcess which produces an output the same as it's input
  89651. */
  89652. var DisplayPassPostProcess = /** @class */ (function (_super) {
  89653. __extends(DisplayPassPostProcess, _super);
  89654. /**
  89655. * Creates the DisplayPassPostProcess
  89656. * @param name The name of the effect.
  89657. * @param options The required width/height ratio to downsize to before computing the render pass.
  89658. * @param camera The camera to apply the render pass to.
  89659. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  89660. * @param engine The engine which the post process will be applied. (default: current engine)
  89661. * @param reusable If the post process can be reused on the same frame. (default: false)
  89662. */
  89663. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  89664. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  89665. }
  89666. return DisplayPassPostProcess;
  89667. }(BABYLON.PostProcess));
  89668. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  89669. })(BABYLON || (BABYLON = {}));
  89670. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  89671. var BABYLON;
  89672. (function (BABYLON) {
  89673. /**
  89674. * Extracts highlights from the image
  89675. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  89676. */
  89677. var HighlightsPostProcess = /** @class */ (function (_super) {
  89678. __extends(HighlightsPostProcess, _super);
  89679. /**
  89680. * Extracts highlights from the image
  89681. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  89682. * @param name The name of the effect.
  89683. * @param options The required width/height ratio to downsize to before computing the render pass.
  89684. * @param camera The camera to apply the render pass to.
  89685. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  89686. * @param engine The engine which the post process will be applied. (default: current engine)
  89687. * @param reusable If the post process can be reused on the same frame. (default: false)
  89688. * @param textureType Type of texture for the post process (default: Engine.TEXTURETYPE_UNSIGNED_INT)
  89689. */
  89690. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  89691. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  89692. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  89693. }
  89694. return HighlightsPostProcess;
  89695. }(BABYLON.PostProcess));
  89696. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  89697. })(BABYLON || (BABYLON = {}));
  89698. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  89699. var BABYLON;
  89700. (function (BABYLON) {
  89701. /**
  89702. * ImageProcessingPostProcess
  89703. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#imageprocessing
  89704. */
  89705. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  89706. __extends(ImageProcessingPostProcess, _super);
  89707. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  89708. if (camera === void 0) { camera = null; }
  89709. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  89710. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  89711. _this._fromLinearSpace = true;
  89712. /**
  89713. * Defines cache preventing GC.
  89714. */
  89715. _this._defines = {
  89716. IMAGEPROCESSING: false,
  89717. VIGNETTE: false,
  89718. VIGNETTEBLENDMODEMULTIPLY: false,
  89719. VIGNETTEBLENDMODEOPAQUE: false,
  89720. TONEMAPPING: false,
  89721. TONEMAPPING_ACES: false,
  89722. CONTRAST: false,
  89723. COLORCURVES: false,
  89724. COLORGRADING: false,
  89725. COLORGRADING3D: false,
  89726. FROMLINEARSPACE: false,
  89727. SAMPLER3DGREENDEPTH: false,
  89728. SAMPLER3DBGRMAP: false,
  89729. IMAGEPROCESSINGPOSTPROCESS: false,
  89730. EXPOSURE: false,
  89731. };
  89732. // Setup the configuration as forced by the constructor. This would then not force the
  89733. // scene materials output in linear space and let untouched the default forward pass.
  89734. if (imageProcessingConfiguration) {
  89735. imageProcessingConfiguration.applyByPostProcess = true;
  89736. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  89737. // This will cause the shader to be compiled
  89738. _this.fromLinearSpace = false;
  89739. }
  89740. // Setup the default processing configuration to the scene.
  89741. else {
  89742. _this._attachImageProcessingConfiguration(null, true);
  89743. _this.imageProcessingConfiguration.applyByPostProcess = true;
  89744. }
  89745. _this.onApply = function (effect) {
  89746. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  89747. };
  89748. return _this;
  89749. }
  89750. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  89751. /**
  89752. * Gets the image processing configuration used either in this material.
  89753. */
  89754. get: function () {
  89755. return this._imageProcessingConfiguration;
  89756. },
  89757. /**
  89758. * Sets the Default image processing configuration used either in the this material.
  89759. *
  89760. * If sets to null, the scene one is in use.
  89761. */
  89762. set: function (value) {
  89763. this._attachImageProcessingConfiguration(value);
  89764. },
  89765. enumerable: true,
  89766. configurable: true
  89767. });
  89768. /**
  89769. * Attaches a new image processing configuration to the PBR Material.
  89770. * @param configuration
  89771. */
  89772. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  89773. var _this = this;
  89774. if (doNotBuild === void 0) { doNotBuild = false; }
  89775. if (configuration === this._imageProcessingConfiguration) {
  89776. return;
  89777. }
  89778. // Detaches observer.
  89779. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  89780. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  89781. }
  89782. // Pick the scene configuration if needed.
  89783. if (!configuration) {
  89784. var scene = null;
  89785. var engine = this.getEngine();
  89786. var camera = this.getCamera();
  89787. if (camera) {
  89788. scene = camera.getScene();
  89789. }
  89790. else if (engine && engine.scenes) {
  89791. var scenes = engine.scenes;
  89792. scene = scenes[scenes.length - 1];
  89793. }
  89794. else {
  89795. scene = BABYLON.Engine.LastCreatedScene;
  89796. }
  89797. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  89798. }
  89799. else {
  89800. this._imageProcessingConfiguration = configuration;
  89801. }
  89802. // Attaches observer.
  89803. if (this._imageProcessingConfiguration) {
  89804. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  89805. _this._updateParameters();
  89806. });
  89807. }
  89808. // Ensure the effect will be rebuilt.
  89809. if (!doNotBuild) {
  89810. this._updateParameters();
  89811. }
  89812. };
  89813. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  89814. /**
  89815. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  89816. */
  89817. get: function () {
  89818. return this.imageProcessingConfiguration.colorCurves;
  89819. },
  89820. /**
  89821. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  89822. */
  89823. set: function (value) {
  89824. this.imageProcessingConfiguration.colorCurves = value;
  89825. },
  89826. enumerable: true,
  89827. configurable: true
  89828. });
  89829. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  89830. /**
  89831. * Gets wether the color curves effect is enabled.
  89832. */
  89833. get: function () {
  89834. return this.imageProcessingConfiguration.colorCurvesEnabled;
  89835. },
  89836. /**
  89837. * Sets wether the color curves effect is enabled.
  89838. */
  89839. set: function (value) {
  89840. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  89841. },
  89842. enumerable: true,
  89843. configurable: true
  89844. });
  89845. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  89846. /**
  89847. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  89848. */
  89849. get: function () {
  89850. return this.imageProcessingConfiguration.colorGradingTexture;
  89851. },
  89852. /**
  89853. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  89854. */
  89855. set: function (value) {
  89856. this.imageProcessingConfiguration.colorGradingTexture = value;
  89857. },
  89858. enumerable: true,
  89859. configurable: true
  89860. });
  89861. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  89862. /**
  89863. * Gets wether the color grading effect is enabled.
  89864. */
  89865. get: function () {
  89866. return this.imageProcessingConfiguration.colorGradingEnabled;
  89867. },
  89868. /**
  89869. * Gets wether the color grading effect is enabled.
  89870. */
  89871. set: function (value) {
  89872. this.imageProcessingConfiguration.colorGradingEnabled = value;
  89873. },
  89874. enumerable: true,
  89875. configurable: true
  89876. });
  89877. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  89878. /**
  89879. * Gets exposure used in the effect.
  89880. */
  89881. get: function () {
  89882. return this.imageProcessingConfiguration.exposure;
  89883. },
  89884. /**
  89885. * Sets exposure used in the effect.
  89886. */
  89887. set: function (value) {
  89888. this.imageProcessingConfiguration.exposure = value;
  89889. },
  89890. enumerable: true,
  89891. configurable: true
  89892. });
  89893. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  89894. /**
  89895. * Gets wether tonemapping is enabled or not.
  89896. */
  89897. get: function () {
  89898. return this._imageProcessingConfiguration.toneMappingEnabled;
  89899. },
  89900. /**
  89901. * Sets wether tonemapping is enabled or not
  89902. */
  89903. set: function (value) {
  89904. this._imageProcessingConfiguration.toneMappingEnabled = value;
  89905. },
  89906. enumerable: true,
  89907. configurable: true
  89908. });
  89909. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  89910. /**
  89911. * Gets contrast used in the effect.
  89912. */
  89913. get: function () {
  89914. return this.imageProcessingConfiguration.contrast;
  89915. },
  89916. /**
  89917. * Sets contrast used in the effect.
  89918. */
  89919. set: function (value) {
  89920. this.imageProcessingConfiguration.contrast = value;
  89921. },
  89922. enumerable: true,
  89923. configurable: true
  89924. });
  89925. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  89926. /**
  89927. * Gets Vignette stretch size.
  89928. */
  89929. get: function () {
  89930. return this.imageProcessingConfiguration.vignetteStretch;
  89931. },
  89932. /**
  89933. * Sets Vignette stretch size.
  89934. */
  89935. set: function (value) {
  89936. this.imageProcessingConfiguration.vignetteStretch = value;
  89937. },
  89938. enumerable: true,
  89939. configurable: true
  89940. });
  89941. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  89942. /**
  89943. * Gets Vignette centre X Offset.
  89944. */
  89945. get: function () {
  89946. return this.imageProcessingConfiguration.vignetteCentreX;
  89947. },
  89948. /**
  89949. * Sets Vignette centre X Offset.
  89950. */
  89951. set: function (value) {
  89952. this.imageProcessingConfiguration.vignetteCentreX = value;
  89953. },
  89954. enumerable: true,
  89955. configurable: true
  89956. });
  89957. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  89958. /**
  89959. * Gets Vignette centre Y Offset.
  89960. */
  89961. get: function () {
  89962. return this.imageProcessingConfiguration.vignetteCentreY;
  89963. },
  89964. /**
  89965. * Sets Vignette centre Y Offset.
  89966. */
  89967. set: function (value) {
  89968. this.imageProcessingConfiguration.vignetteCentreY = value;
  89969. },
  89970. enumerable: true,
  89971. configurable: true
  89972. });
  89973. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  89974. /**
  89975. * Gets Vignette weight or intensity of the vignette effect.
  89976. */
  89977. get: function () {
  89978. return this.imageProcessingConfiguration.vignetteWeight;
  89979. },
  89980. /**
  89981. * Sets Vignette weight or intensity of the vignette effect.
  89982. */
  89983. set: function (value) {
  89984. this.imageProcessingConfiguration.vignetteWeight = value;
  89985. },
  89986. enumerable: true,
  89987. configurable: true
  89988. });
  89989. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  89990. /**
  89991. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  89992. * if vignetteEnabled is set to true.
  89993. */
  89994. get: function () {
  89995. return this.imageProcessingConfiguration.vignetteColor;
  89996. },
  89997. /**
  89998. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  89999. * if vignetteEnabled is set to true.
  90000. */
  90001. set: function (value) {
  90002. this.imageProcessingConfiguration.vignetteColor = value;
  90003. },
  90004. enumerable: true,
  90005. configurable: true
  90006. });
  90007. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  90008. /**
  90009. * Gets Camera field of view used by the Vignette effect.
  90010. */
  90011. get: function () {
  90012. return this.imageProcessingConfiguration.vignetteCameraFov;
  90013. },
  90014. /**
  90015. * Sets Camera field of view used by the Vignette effect.
  90016. */
  90017. set: function (value) {
  90018. this.imageProcessingConfiguration.vignetteCameraFov = value;
  90019. },
  90020. enumerable: true,
  90021. configurable: true
  90022. });
  90023. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  90024. /**
  90025. * Gets the vignette blend mode allowing different kind of effect.
  90026. */
  90027. get: function () {
  90028. return this.imageProcessingConfiguration.vignetteBlendMode;
  90029. },
  90030. /**
  90031. * Sets the vignette blend mode allowing different kind of effect.
  90032. */
  90033. set: function (value) {
  90034. this.imageProcessingConfiguration.vignetteBlendMode = value;
  90035. },
  90036. enumerable: true,
  90037. configurable: true
  90038. });
  90039. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  90040. /**
  90041. * Gets wether the vignette effect is enabled.
  90042. */
  90043. get: function () {
  90044. return this.imageProcessingConfiguration.vignetteEnabled;
  90045. },
  90046. /**
  90047. * Sets wether the vignette effect is enabled.
  90048. */
  90049. set: function (value) {
  90050. this.imageProcessingConfiguration.vignetteEnabled = value;
  90051. },
  90052. enumerable: true,
  90053. configurable: true
  90054. });
  90055. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  90056. /**
  90057. * Gets wether the input of the processing is in Gamma or Linear Space.
  90058. */
  90059. get: function () {
  90060. return this._fromLinearSpace;
  90061. },
  90062. /**
  90063. * Sets wether the input of the processing is in Gamma or Linear Space.
  90064. */
  90065. set: function (value) {
  90066. if (this._fromLinearSpace === value) {
  90067. return;
  90068. }
  90069. this._fromLinearSpace = value;
  90070. this._updateParameters();
  90071. },
  90072. enumerable: true,
  90073. configurable: true
  90074. });
  90075. /**
  90076. * "ImageProcessingPostProcess"
  90077. * @returns "ImageProcessingPostProcess"
  90078. */
  90079. ImageProcessingPostProcess.prototype.getClassName = function () {
  90080. return "ImageProcessingPostProcess";
  90081. };
  90082. ImageProcessingPostProcess.prototype._updateParameters = function () {
  90083. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  90084. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  90085. var defines = "";
  90086. for (var define in this._defines) {
  90087. if (this._defines[define]) {
  90088. defines += "#define " + define + ";\r\n";
  90089. }
  90090. }
  90091. var samplers = ["textureSampler"];
  90092. var uniforms = ["scale"];
  90093. if (BABYLON.ImageProcessingConfiguration) {
  90094. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  90095. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  90096. }
  90097. this.updateEffect(defines, uniforms, samplers);
  90098. };
  90099. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  90100. _super.prototype.dispose.call(this, camera);
  90101. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  90102. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  90103. }
  90104. if (this._imageProcessingConfiguration) {
  90105. this.imageProcessingConfiguration.applyByPostProcess = false;
  90106. }
  90107. };
  90108. __decorate([
  90109. BABYLON.serialize()
  90110. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  90111. return ImageProcessingPostProcess;
  90112. }(BABYLON.PostProcess));
  90113. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  90114. })(BABYLON || (BABYLON = {}));
  90115. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  90116. var BABYLON;
  90117. (function (BABYLON) {
  90118. /**
  90119. * Class used to store bone information
  90120. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  90121. */
  90122. var Bone = /** @class */ (function (_super) {
  90123. __extends(Bone, _super);
  90124. /**
  90125. * Create a new bone
  90126. * @param name defines the bone name
  90127. * @param skeleton defines the parent skeleton
  90128. * @param parentBone defines the parent (can be null if the bone is the root)
  90129. * @param localMatrix defines the local matrix
  90130. * @param restPose defines the rest pose matrix
  90131. * @param baseMatrix defines the base matrix
  90132. * @param index defines index of the bone in the hiearchy
  90133. */
  90134. function Bone(
  90135. /**
  90136. * defines the bone name
  90137. */
  90138. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  90139. if (parentBone === void 0) { parentBone = null; }
  90140. if (localMatrix === void 0) { localMatrix = null; }
  90141. if (restPose === void 0) { restPose = null; }
  90142. if (baseMatrix === void 0) { baseMatrix = null; }
  90143. if (index === void 0) { index = null; }
  90144. var _this = _super.call(this, name, skeleton.getScene()) || this;
  90145. _this.name = name;
  90146. /**
  90147. * Gets the list of child bones
  90148. */
  90149. _this.children = new Array();
  90150. /** Gets the animations associated with this bone */
  90151. _this.animations = new Array();
  90152. /**
  90153. * @hidden Internal only
  90154. * Set this value to map this bone to a different index in the transform matrices
  90155. * Set this value to -1 to exclude the bone from the transform matrices
  90156. */
  90157. _this._index = null;
  90158. _this._absoluteTransform = new BABYLON.Matrix();
  90159. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  90160. _this._scalingDeterminant = 1;
  90161. _this._worldTransform = new BABYLON.Matrix();
  90162. _this._needToDecompose = true;
  90163. _this._needToCompose = false;
  90164. _this._skeleton = skeleton;
  90165. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  90166. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  90167. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  90168. _this._index = index;
  90169. skeleton.bones.push(_this);
  90170. _this.setParent(parentBone, false);
  90171. if (baseMatrix || localMatrix) {
  90172. _this._updateDifferenceMatrix();
  90173. }
  90174. return _this;
  90175. }
  90176. Object.defineProperty(Bone.prototype, "_matrix", {
  90177. /** @hidden */
  90178. get: function () {
  90179. this._compose();
  90180. return this._localMatrix;
  90181. },
  90182. /** @hidden */
  90183. set: function (value) {
  90184. this._localMatrix.copyFrom(value);
  90185. this._needToDecompose = true;
  90186. },
  90187. enumerable: true,
  90188. configurable: true
  90189. });
  90190. // Members
  90191. /**
  90192. * Gets the parent skeleton
  90193. * @returns a skeleton
  90194. */
  90195. Bone.prototype.getSkeleton = function () {
  90196. return this._skeleton;
  90197. };
  90198. /**
  90199. * Gets parent bone
  90200. * @returns a bone or null if the bone is the root of the bone hierarchy
  90201. */
  90202. Bone.prototype.getParent = function () {
  90203. return this._parent;
  90204. };
  90205. /**
  90206. * Sets the parent bone
  90207. * @param parent defines the parent (can be null if the bone is the root)
  90208. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  90209. */
  90210. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  90211. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  90212. if (this._parent === parent) {
  90213. return;
  90214. }
  90215. if (this._parent) {
  90216. var index = this._parent.children.indexOf(this);
  90217. if (index !== -1) {
  90218. this._parent.children.splice(index, 1);
  90219. }
  90220. }
  90221. this._parent = parent;
  90222. if (this._parent) {
  90223. this._parent.children.push(this);
  90224. }
  90225. if (updateDifferenceMatrix) {
  90226. this._updateDifferenceMatrix();
  90227. }
  90228. this.markAsDirty();
  90229. };
  90230. /**
  90231. * Gets the local matrix
  90232. * @returns a matrix
  90233. */
  90234. Bone.prototype.getLocalMatrix = function () {
  90235. this._compose();
  90236. return this._localMatrix;
  90237. };
  90238. /**
  90239. * Gets the base matrix (initial matrix which remains unchanged)
  90240. * @returns a matrix
  90241. */
  90242. Bone.prototype.getBaseMatrix = function () {
  90243. return this._baseMatrix;
  90244. };
  90245. /**
  90246. * Gets the rest pose matrix
  90247. * @returns a matrix
  90248. */
  90249. Bone.prototype.getRestPose = function () {
  90250. return this._restPose;
  90251. };
  90252. /**
  90253. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  90254. */
  90255. Bone.prototype.getWorldMatrix = function () {
  90256. return this._worldTransform;
  90257. };
  90258. /**
  90259. * Sets the local matrix to rest pose matrix
  90260. */
  90261. Bone.prototype.returnToRest = function () {
  90262. this.updateMatrix(this._restPose.clone());
  90263. };
  90264. /**
  90265. * Gets the inverse of the absolute transform matrix.
  90266. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  90267. * @returns a matrix
  90268. */
  90269. Bone.prototype.getInvertedAbsoluteTransform = function () {
  90270. return this._invertedAbsoluteTransform;
  90271. };
  90272. /**
  90273. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  90274. * @returns a matrix
  90275. */
  90276. Bone.prototype.getAbsoluteTransform = function () {
  90277. return this._absoluteTransform;
  90278. };
  90279. Object.defineProperty(Bone.prototype, "position", {
  90280. // Properties (matches AbstractMesh properties)
  90281. /** Gets or sets current position (in local space) */
  90282. get: function () {
  90283. this._decompose();
  90284. return this._localPosition;
  90285. },
  90286. set: function (newPosition) {
  90287. this._decompose();
  90288. this._localPosition.copyFrom(newPosition);
  90289. this._markAsDirtyAndCompose();
  90290. },
  90291. enumerable: true,
  90292. configurable: true
  90293. });
  90294. Object.defineProperty(Bone.prototype, "rotation", {
  90295. /** Gets or sets current rotation (in local space) */
  90296. get: function () {
  90297. return this.getRotation();
  90298. },
  90299. set: function (newRotation) {
  90300. this.setRotation(newRotation);
  90301. },
  90302. enumerable: true,
  90303. configurable: true
  90304. });
  90305. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  90306. /** Gets or sets current rotation quaternion (in local space) */
  90307. get: function () {
  90308. this._decompose();
  90309. return this._localRotation;
  90310. },
  90311. set: function (newRotation) {
  90312. this.setRotationQuaternion(newRotation);
  90313. },
  90314. enumerable: true,
  90315. configurable: true
  90316. });
  90317. Object.defineProperty(Bone.prototype, "scaling", {
  90318. /** Gets or sets current scaling (in local space) */
  90319. get: function () {
  90320. return this.getScale();
  90321. },
  90322. set: function (newScaling) {
  90323. this.setScale(newScaling);
  90324. },
  90325. enumerable: true,
  90326. configurable: true
  90327. });
  90328. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  90329. /**
  90330. * Gets the animation properties override
  90331. */
  90332. get: function () {
  90333. return this._skeleton.animationPropertiesOverride;
  90334. },
  90335. enumerable: true,
  90336. configurable: true
  90337. });
  90338. // Methods
  90339. Bone.prototype._decompose = function () {
  90340. if (!this._needToDecompose) {
  90341. return;
  90342. }
  90343. this._needToDecompose = false;
  90344. if (!this._localScaling) {
  90345. this._localScaling = BABYLON.Vector3.Zero();
  90346. this._localRotation = BABYLON.Quaternion.Zero();
  90347. this._localPosition = BABYLON.Vector3.Zero();
  90348. }
  90349. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  90350. };
  90351. Bone.prototype._compose = function () {
  90352. if (!this._needToCompose) {
  90353. return;
  90354. }
  90355. this._needToCompose = false;
  90356. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  90357. };
  90358. /**
  90359. * Update the base and local matrices
  90360. * @param matrix defines the new base or local matrix
  90361. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  90362. * @param updateLocalMatrix defines if the local matrix should be updated
  90363. */
  90364. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  90365. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  90366. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  90367. this._baseMatrix.copyFrom(matrix);
  90368. if (updateDifferenceMatrix) {
  90369. this._updateDifferenceMatrix();
  90370. }
  90371. if (updateLocalMatrix) {
  90372. this._localMatrix.copyFrom(matrix);
  90373. this._markAsDirtyAndDecompose();
  90374. }
  90375. else {
  90376. this.markAsDirty();
  90377. }
  90378. };
  90379. /** @hidden */
  90380. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  90381. if (updateChildren === void 0) { updateChildren = true; }
  90382. if (!rootMatrix) {
  90383. rootMatrix = this._baseMatrix;
  90384. }
  90385. if (this._parent) {
  90386. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  90387. }
  90388. else {
  90389. this._absoluteTransform.copyFrom(rootMatrix);
  90390. }
  90391. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  90392. if (updateChildren) {
  90393. for (var index = 0; index < this.children.length; index++) {
  90394. this.children[index]._updateDifferenceMatrix();
  90395. }
  90396. }
  90397. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  90398. };
  90399. /**
  90400. * Flag the bone as dirty (Forcing it to update everything)
  90401. */
  90402. Bone.prototype.markAsDirty = function () {
  90403. this._currentRenderId++;
  90404. this._childRenderId++;
  90405. this._skeleton._markAsDirty();
  90406. };
  90407. Bone.prototype._markAsDirtyAndCompose = function () {
  90408. this.markAsDirty();
  90409. this._needToCompose = true;
  90410. };
  90411. Bone.prototype._markAsDirtyAndDecompose = function () {
  90412. this.markAsDirty();
  90413. this._needToDecompose = true;
  90414. };
  90415. /**
  90416. * Copy an animation range from another bone
  90417. * @param source defines the source bone
  90418. * @param rangeName defines the range name to copy
  90419. * @param frameOffset defines the frame offset
  90420. * @param rescaleAsRequired defines if rescaling must be applied if required
  90421. * @param skelDimensionsRatio defines the scaling ratio
  90422. * @returns true if operation was successful
  90423. */
  90424. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  90425. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  90426. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  90427. // all animation may be coming from a library skeleton, so may need to create animation
  90428. if (this.animations.length === 0) {
  90429. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  90430. this.animations[0].setKeys([]);
  90431. }
  90432. // get animation info / verify there is such a range from the source bone
  90433. var sourceRange = source.animations[0].getRange(rangeName);
  90434. if (!sourceRange) {
  90435. return false;
  90436. }
  90437. var from = sourceRange.from;
  90438. var to = sourceRange.to;
  90439. var sourceKeys = source.animations[0].getKeys();
  90440. // rescaling prep
  90441. var sourceBoneLength = source.length;
  90442. var sourceParent = source.getParent();
  90443. var parent = this.getParent();
  90444. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  90445. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  90446. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  90447. var destKeys = this.animations[0].getKeys();
  90448. // loop vars declaration
  90449. var orig;
  90450. var origTranslation;
  90451. var mat;
  90452. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  90453. orig = sourceKeys[key];
  90454. if (orig.frame >= from && orig.frame <= to) {
  90455. if (rescaleAsRequired) {
  90456. mat = orig.value.clone();
  90457. // scale based on parent ratio, when bone has parent
  90458. if (parentScalingReqd) {
  90459. origTranslation = mat.getTranslation();
  90460. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  90461. // scale based on skeleton dimension ratio when root bone, and value is passed
  90462. }
  90463. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  90464. origTranslation = mat.getTranslation();
  90465. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  90466. // use original when root bone, and no data for skelDimensionsRatio
  90467. }
  90468. else {
  90469. mat = orig.value;
  90470. }
  90471. }
  90472. else {
  90473. mat = orig.value;
  90474. }
  90475. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  90476. }
  90477. }
  90478. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  90479. return true;
  90480. };
  90481. /**
  90482. * Translate the bone in local or world space
  90483. * @param vec The amount to translate the bone
  90484. * @param space The space that the translation is in
  90485. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90486. */
  90487. Bone.prototype.translate = function (vec, space, mesh) {
  90488. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90489. var lm = this.getLocalMatrix();
  90490. if (space == BABYLON.Space.LOCAL) {
  90491. lm.m[12] += vec.x;
  90492. lm.m[13] += vec.y;
  90493. lm.m[14] += vec.z;
  90494. }
  90495. else {
  90496. var wm = null;
  90497. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  90498. if (mesh) {
  90499. wm = mesh.getWorldMatrix();
  90500. }
  90501. this._skeleton.computeAbsoluteTransforms();
  90502. var tmat = Bone._tmpMats[0];
  90503. var tvec = Bone._tmpVecs[0];
  90504. if (this._parent) {
  90505. if (mesh && wm) {
  90506. tmat.copyFrom(this._parent.getAbsoluteTransform());
  90507. tmat.multiplyToRef(wm, tmat);
  90508. }
  90509. else {
  90510. tmat.copyFrom(this._parent.getAbsoluteTransform());
  90511. }
  90512. }
  90513. tmat.m[12] = 0;
  90514. tmat.m[13] = 0;
  90515. tmat.m[14] = 0;
  90516. tmat.invert();
  90517. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  90518. lm.m[12] += tvec.x;
  90519. lm.m[13] += tvec.y;
  90520. lm.m[14] += tvec.z;
  90521. }
  90522. this._markAsDirtyAndDecompose();
  90523. };
  90524. /**
  90525. * Set the postion of the bone in local or world space
  90526. * @param position The position to set the bone
  90527. * @param space The space that the position is in
  90528. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90529. */
  90530. Bone.prototype.setPosition = function (position, space, mesh) {
  90531. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90532. var lm = this.getLocalMatrix();
  90533. if (space == BABYLON.Space.LOCAL) {
  90534. lm.m[12] = position.x;
  90535. lm.m[13] = position.y;
  90536. lm.m[14] = position.z;
  90537. }
  90538. else {
  90539. var wm = null;
  90540. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  90541. if (mesh) {
  90542. wm = mesh.getWorldMatrix();
  90543. }
  90544. this._skeleton.computeAbsoluteTransforms();
  90545. var tmat = Bone._tmpMats[0];
  90546. var vec = Bone._tmpVecs[0];
  90547. if (this._parent) {
  90548. if (mesh && wm) {
  90549. tmat.copyFrom(this._parent.getAbsoluteTransform());
  90550. tmat.multiplyToRef(wm, tmat);
  90551. }
  90552. else {
  90553. tmat.copyFrom(this._parent.getAbsoluteTransform());
  90554. }
  90555. }
  90556. tmat.invert();
  90557. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  90558. lm.m[12] = vec.x;
  90559. lm.m[13] = vec.y;
  90560. lm.m[14] = vec.z;
  90561. }
  90562. this._markAsDirtyAndDecompose();
  90563. };
  90564. /**
  90565. * Set the absolute position of the bone (world space)
  90566. * @param position The position to set the bone
  90567. * @param mesh The mesh that this bone is attached to
  90568. */
  90569. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  90570. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  90571. };
  90572. /**
  90573. * Scale the bone on the x, y and z axes (in local space)
  90574. * @param x The amount to scale the bone on the x axis
  90575. * @param y The amount to scale the bone on the y axis
  90576. * @param z The amount to scale the bone on the z axis
  90577. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  90578. */
  90579. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  90580. if (scaleChildren === void 0) { scaleChildren = false; }
  90581. var locMat = this.getLocalMatrix();
  90582. // Apply new scaling on top of current local matrix
  90583. var scaleMat = Bone._tmpMats[0];
  90584. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  90585. scaleMat.multiplyToRef(locMat, locMat);
  90586. // Invert scaling matrix and apply the inverse to all children
  90587. scaleMat.invert();
  90588. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  90589. var child = _a[_i];
  90590. var cm = child.getLocalMatrix();
  90591. cm.multiplyToRef(scaleMat, cm);
  90592. cm.m[12] *= x;
  90593. cm.m[13] *= y;
  90594. cm.m[14] *= z;
  90595. child._markAsDirtyAndDecompose();
  90596. }
  90597. this._markAsDirtyAndDecompose();
  90598. if (scaleChildren) {
  90599. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  90600. var child = _c[_b];
  90601. child.scale(x, y, z, scaleChildren);
  90602. }
  90603. }
  90604. };
  90605. /**
  90606. * Set the bone scaling in local space
  90607. * @param scale defines the scaling vector
  90608. */
  90609. Bone.prototype.setScale = function (scale) {
  90610. this._decompose();
  90611. this._localScaling.copyFrom(scale);
  90612. this._markAsDirtyAndCompose();
  90613. };
  90614. /**
  90615. * Gets the current scaling in local space
  90616. * @returns the current scaling vector
  90617. */
  90618. Bone.prototype.getScale = function () {
  90619. this._decompose();
  90620. return this._localScaling;
  90621. };
  90622. /**
  90623. * Gets the current scaling in local space and stores it in a target vector
  90624. * @param result defines the target vector
  90625. */
  90626. Bone.prototype.getScaleToRef = function (result) {
  90627. this._decompose();
  90628. result.copyFrom(this._localScaling);
  90629. };
  90630. /**
  90631. * Set the yaw, pitch, and roll of the bone in local or world space
  90632. * @param yaw The rotation of the bone on the y axis
  90633. * @param pitch The rotation of the bone on the x axis
  90634. * @param roll The rotation of the bone on the z axis
  90635. * @param space The space that the axes of rotation are in
  90636. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90637. */
  90638. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  90639. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90640. if (space === BABYLON.Space.LOCAL) {
  90641. var quat = Bone._tmpQuat;
  90642. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  90643. this.setRotationQuaternion(quat, space, mesh);
  90644. return;
  90645. }
  90646. var rotMatInv = Bone._tmpMats[0];
  90647. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  90648. return;
  90649. }
  90650. var rotMat = Bone._tmpMats[1];
  90651. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  90652. rotMatInv.multiplyToRef(rotMat, rotMat);
  90653. this._rotateWithMatrix(rotMat, space, mesh);
  90654. };
  90655. /**
  90656. * Add a rotation to the bone on an axis in local or world space
  90657. * @param axis The axis to rotate the bone on
  90658. * @param amount The amount to rotate the bone
  90659. * @param space The space that the axis is in
  90660. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90661. */
  90662. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  90663. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90664. var rmat = Bone._tmpMats[0];
  90665. rmat.m[12] = 0;
  90666. rmat.m[13] = 0;
  90667. rmat.m[14] = 0;
  90668. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  90669. this._rotateWithMatrix(rmat, space, mesh);
  90670. };
  90671. /**
  90672. * Set the rotation of the bone to a particular axis angle in local or world space
  90673. * @param axis The axis to rotate the bone on
  90674. * @param angle The angle that the bone should be rotated to
  90675. * @param space The space that the axis is in
  90676. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90677. */
  90678. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  90679. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90680. if (space === BABYLON.Space.LOCAL) {
  90681. var quat = Bone._tmpQuat;
  90682. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  90683. this.setRotationQuaternion(quat, space, mesh);
  90684. return;
  90685. }
  90686. var rotMatInv = Bone._tmpMats[0];
  90687. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  90688. return;
  90689. }
  90690. var rotMat = Bone._tmpMats[1];
  90691. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  90692. rotMatInv.multiplyToRef(rotMat, rotMat);
  90693. this._rotateWithMatrix(rotMat, space, mesh);
  90694. };
  90695. /**
  90696. * Set the euler rotation of the bone in local of world space
  90697. * @param rotation The euler rotation that the bone should be set to
  90698. * @param space The space that the rotation is in
  90699. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90700. */
  90701. Bone.prototype.setRotation = function (rotation, space, mesh) {
  90702. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90703. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  90704. };
  90705. /**
  90706. * Set the quaternion rotation of the bone in local of world space
  90707. * @param quat The quaternion rotation that the bone should be set to
  90708. * @param space The space that the rotation is in
  90709. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90710. */
  90711. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  90712. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90713. if (space === BABYLON.Space.LOCAL) {
  90714. this._decompose();
  90715. this._localRotation.copyFrom(quat);
  90716. this._markAsDirtyAndCompose();
  90717. return;
  90718. }
  90719. var rotMatInv = Bone._tmpMats[0];
  90720. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  90721. return;
  90722. }
  90723. var rotMat = Bone._tmpMats[1];
  90724. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  90725. rotMatInv.multiplyToRef(rotMat, rotMat);
  90726. this._rotateWithMatrix(rotMat, space, mesh);
  90727. };
  90728. /**
  90729. * Set the rotation matrix of the bone in local of world space
  90730. * @param rotMat The rotation matrix that the bone should be set to
  90731. * @param space The space that the rotation is in
  90732. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90733. */
  90734. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  90735. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90736. if (space === BABYLON.Space.LOCAL) {
  90737. var quat = Bone._tmpQuat;
  90738. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  90739. this.setRotationQuaternion(quat, space, mesh);
  90740. return;
  90741. }
  90742. var rotMatInv = Bone._tmpMats[0];
  90743. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  90744. return;
  90745. }
  90746. var rotMat2 = Bone._tmpMats[1];
  90747. rotMat2.copyFrom(rotMat);
  90748. rotMatInv.multiplyToRef(rotMat, rotMat2);
  90749. this._rotateWithMatrix(rotMat2, space, mesh);
  90750. };
  90751. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  90752. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90753. var lmat = this.getLocalMatrix();
  90754. var lx = lmat.m[12];
  90755. var ly = lmat.m[13];
  90756. var lz = lmat.m[14];
  90757. var parent = this.getParent();
  90758. var parentScale = Bone._tmpMats[3];
  90759. var parentScaleInv = Bone._tmpMats[4];
  90760. if (parent && space == BABYLON.Space.WORLD) {
  90761. if (mesh) {
  90762. parentScale.copyFrom(mesh.getWorldMatrix());
  90763. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  90764. }
  90765. else {
  90766. parentScale.copyFrom(parent.getAbsoluteTransform());
  90767. }
  90768. parentScaleInv.copyFrom(parentScale);
  90769. parentScaleInv.invert();
  90770. lmat.multiplyToRef(parentScale, lmat);
  90771. lmat.multiplyToRef(rmat, lmat);
  90772. lmat.multiplyToRef(parentScaleInv, lmat);
  90773. }
  90774. else {
  90775. if (space == BABYLON.Space.WORLD && mesh) {
  90776. parentScale.copyFrom(mesh.getWorldMatrix());
  90777. parentScaleInv.copyFrom(parentScale);
  90778. parentScaleInv.invert();
  90779. lmat.multiplyToRef(parentScale, lmat);
  90780. lmat.multiplyToRef(rmat, lmat);
  90781. lmat.multiplyToRef(parentScaleInv, lmat);
  90782. }
  90783. else {
  90784. lmat.multiplyToRef(rmat, lmat);
  90785. }
  90786. }
  90787. lmat.m[12] = lx;
  90788. lmat.m[13] = ly;
  90789. lmat.m[14] = lz;
  90790. this.computeAbsoluteTransforms();
  90791. this._markAsDirtyAndDecompose();
  90792. };
  90793. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  90794. var scaleMatrix = Bone._tmpMats[2];
  90795. rotMatInv.copyFrom(this.getAbsoluteTransform());
  90796. if (mesh) {
  90797. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  90798. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  90799. }
  90800. rotMatInv.invert();
  90801. if (isNaN(rotMatInv.m[0])) {
  90802. // Matrix failed to invert.
  90803. // This can happen if scale is zero for example.
  90804. return false;
  90805. }
  90806. scaleMatrix.m[0] *= this._scalingDeterminant;
  90807. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  90808. return true;
  90809. };
  90810. /**
  90811. * Get the position of the bone in local or world space
  90812. * @param space The space that the returned position is in
  90813. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90814. * @returns The position of the bone
  90815. */
  90816. Bone.prototype.getPosition = function (space, mesh) {
  90817. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90818. if (mesh === void 0) { mesh = null; }
  90819. var pos = BABYLON.Vector3.Zero();
  90820. this.getPositionToRef(space, mesh, pos);
  90821. return pos;
  90822. };
  90823. /**
  90824. * Copy the position of the bone to a vector3 in local or world space
  90825. * @param space The space that the returned position is in
  90826. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90827. * @param result The vector3 to copy the position to
  90828. */
  90829. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  90830. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90831. if (space == BABYLON.Space.LOCAL) {
  90832. var lm = this.getLocalMatrix();
  90833. result.x = lm.m[12];
  90834. result.y = lm.m[13];
  90835. result.z = lm.m[14];
  90836. }
  90837. else {
  90838. var wm = null;
  90839. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  90840. if (mesh) {
  90841. wm = mesh.getWorldMatrix();
  90842. }
  90843. this._skeleton.computeAbsoluteTransforms();
  90844. var tmat = Bone._tmpMats[0];
  90845. if (mesh && wm) {
  90846. tmat.copyFrom(this.getAbsoluteTransform());
  90847. tmat.multiplyToRef(wm, tmat);
  90848. }
  90849. else {
  90850. tmat = this.getAbsoluteTransform();
  90851. }
  90852. result.x = tmat.m[12];
  90853. result.y = tmat.m[13];
  90854. result.z = tmat.m[14];
  90855. }
  90856. };
  90857. /**
  90858. * Get the absolute position of the bone (world space)
  90859. * @param mesh The mesh that this bone is attached to
  90860. * @returns The absolute position of the bone
  90861. */
  90862. Bone.prototype.getAbsolutePosition = function (mesh) {
  90863. if (mesh === void 0) { mesh = null; }
  90864. var pos = BABYLON.Vector3.Zero();
  90865. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  90866. return pos;
  90867. };
  90868. /**
  90869. * Copy the absolute position of the bone (world space) to the result param
  90870. * @param mesh The mesh that this bone is attached to
  90871. * @param result The vector3 to copy the absolute position to
  90872. */
  90873. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  90874. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  90875. };
  90876. /**
  90877. * Compute the absolute transforms of this bone and its children
  90878. */
  90879. Bone.prototype.computeAbsoluteTransforms = function () {
  90880. this._compose();
  90881. if (this._parent) {
  90882. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  90883. }
  90884. else {
  90885. this._absoluteTransform.copyFrom(this._localMatrix);
  90886. var poseMatrix = this._skeleton.getPoseMatrix();
  90887. if (poseMatrix) {
  90888. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  90889. }
  90890. }
  90891. var children = this.children;
  90892. var len = children.length;
  90893. for (var i = 0; i < len; i++) {
  90894. children[i].computeAbsoluteTransforms();
  90895. }
  90896. };
  90897. /**
  90898. * Get the world direction from an axis that is in the local space of the bone
  90899. * @param localAxis The local direction that is used to compute the world direction
  90900. * @param mesh The mesh that this bone is attached to
  90901. * @returns The world direction
  90902. */
  90903. Bone.prototype.getDirection = function (localAxis, mesh) {
  90904. if (mesh === void 0) { mesh = null; }
  90905. var result = BABYLON.Vector3.Zero();
  90906. this.getDirectionToRef(localAxis, mesh, result);
  90907. return result;
  90908. };
  90909. /**
  90910. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  90911. * @param localAxis The local direction that is used to compute the world direction
  90912. * @param mesh The mesh that this bone is attached to
  90913. * @param result The vector3 that the world direction will be copied to
  90914. */
  90915. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  90916. if (mesh === void 0) { mesh = null; }
  90917. var wm = null;
  90918. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  90919. if (mesh) {
  90920. wm = mesh.getWorldMatrix();
  90921. }
  90922. this._skeleton.computeAbsoluteTransforms();
  90923. var mat = Bone._tmpMats[0];
  90924. mat.copyFrom(this.getAbsoluteTransform());
  90925. if (mesh && wm) {
  90926. mat.multiplyToRef(wm, mat);
  90927. }
  90928. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  90929. result.normalize();
  90930. };
  90931. /**
  90932. * Get the euler rotation of the bone in local or world space
  90933. * @param space The space that the rotation should be in
  90934. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90935. * @returns The euler rotation
  90936. */
  90937. Bone.prototype.getRotation = function (space, mesh) {
  90938. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90939. if (mesh === void 0) { mesh = null; }
  90940. var result = BABYLON.Vector3.Zero();
  90941. this.getRotationToRef(space, mesh, result);
  90942. return result;
  90943. };
  90944. /**
  90945. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  90946. * @param space The space that the rotation should be in
  90947. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90948. * @param result The vector3 that the rotation should be copied to
  90949. */
  90950. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  90951. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90952. if (mesh === void 0) { mesh = null; }
  90953. var quat = Bone._tmpQuat;
  90954. this.getRotationQuaternionToRef(space, mesh, quat);
  90955. quat.toEulerAnglesToRef(result);
  90956. };
  90957. /**
  90958. * Get the quaternion rotation of the bone in either local or world space
  90959. * @param space The space that the rotation should be in
  90960. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90961. * @returns The quaternion rotation
  90962. */
  90963. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  90964. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90965. if (mesh === void 0) { mesh = null; }
  90966. var result = BABYLON.Quaternion.Identity();
  90967. this.getRotationQuaternionToRef(space, mesh, result);
  90968. return result;
  90969. };
  90970. /**
  90971. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  90972. * @param space The space that the rotation should be in
  90973. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90974. * @param result The quaternion that the rotation should be copied to
  90975. */
  90976. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  90977. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90978. if (mesh === void 0) { mesh = null; }
  90979. if (space == BABYLON.Space.LOCAL) {
  90980. this._decompose();
  90981. result.copyFrom(this._localRotation);
  90982. }
  90983. else {
  90984. var mat = Bone._tmpMats[0];
  90985. var amat = this.getAbsoluteTransform();
  90986. if (mesh) {
  90987. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  90988. }
  90989. else {
  90990. mat.copyFrom(amat);
  90991. }
  90992. mat.m[0] *= this._scalingDeterminant;
  90993. mat.m[1] *= this._scalingDeterminant;
  90994. mat.m[2] *= this._scalingDeterminant;
  90995. mat.decompose(undefined, result, undefined);
  90996. }
  90997. };
  90998. /**
  90999. * Get the rotation matrix of the bone in local or world space
  91000. * @param space The space that the rotation should be in
  91001. * @param mesh The mesh that this bone is attached to. This is only used in world space
  91002. * @returns The rotation matrix
  91003. */
  91004. Bone.prototype.getRotationMatrix = function (space, mesh) {
  91005. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  91006. var result = BABYLON.Matrix.Identity();
  91007. this.getRotationMatrixToRef(space, mesh, result);
  91008. return result;
  91009. };
  91010. /**
  91011. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  91012. * @param space The space that the rotation should be in
  91013. * @param mesh The mesh that this bone is attached to. This is only used in world space
  91014. * @param result The quaternion that the rotation should be copied to
  91015. */
  91016. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  91017. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  91018. if (space == BABYLON.Space.LOCAL) {
  91019. this.getLocalMatrix().getRotationMatrixToRef(result);
  91020. }
  91021. else {
  91022. var mat = Bone._tmpMats[0];
  91023. var amat = this.getAbsoluteTransform();
  91024. if (mesh) {
  91025. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  91026. }
  91027. else {
  91028. mat.copyFrom(amat);
  91029. }
  91030. mat.m[0] *= this._scalingDeterminant;
  91031. mat.m[1] *= this._scalingDeterminant;
  91032. mat.m[2] *= this._scalingDeterminant;
  91033. mat.getRotationMatrixToRef(result);
  91034. }
  91035. };
  91036. /**
  91037. * Get the world position of a point that is in the local space of the bone
  91038. * @param position The local position
  91039. * @param mesh The mesh that this bone is attached to
  91040. * @returns The world position
  91041. */
  91042. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  91043. if (mesh === void 0) { mesh = null; }
  91044. var result = BABYLON.Vector3.Zero();
  91045. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  91046. return result;
  91047. };
  91048. /**
  91049. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  91050. * @param position The local position
  91051. * @param mesh The mesh that this bone is attached to
  91052. * @param result The vector3 that the world position should be copied to
  91053. */
  91054. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  91055. if (mesh === void 0) { mesh = null; }
  91056. var wm = null;
  91057. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  91058. if (mesh) {
  91059. wm = mesh.getWorldMatrix();
  91060. }
  91061. this._skeleton.computeAbsoluteTransforms();
  91062. var tmat = Bone._tmpMats[0];
  91063. if (mesh && wm) {
  91064. tmat.copyFrom(this.getAbsoluteTransform());
  91065. tmat.multiplyToRef(wm, tmat);
  91066. }
  91067. else {
  91068. tmat = this.getAbsoluteTransform();
  91069. }
  91070. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  91071. };
  91072. /**
  91073. * Get the local position of a point that is in world space
  91074. * @param position The world position
  91075. * @param mesh The mesh that this bone is attached to
  91076. * @returns The local position
  91077. */
  91078. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  91079. if (mesh === void 0) { mesh = null; }
  91080. var result = BABYLON.Vector3.Zero();
  91081. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  91082. return result;
  91083. };
  91084. /**
  91085. * Get the local position of a point that is in world space and copy it to the result param
  91086. * @param position The world position
  91087. * @param mesh The mesh that this bone is attached to
  91088. * @param result The vector3 that the local position should be copied to
  91089. */
  91090. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  91091. if (mesh === void 0) { mesh = null; }
  91092. var wm = null;
  91093. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  91094. if (mesh) {
  91095. wm = mesh.getWorldMatrix();
  91096. }
  91097. this._skeleton.computeAbsoluteTransforms();
  91098. var tmat = Bone._tmpMats[0];
  91099. tmat.copyFrom(this.getAbsoluteTransform());
  91100. if (mesh && wm) {
  91101. tmat.multiplyToRef(wm, tmat);
  91102. }
  91103. tmat.invert();
  91104. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  91105. };
  91106. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  91107. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  91108. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  91109. return Bone;
  91110. }(BABYLON.Node));
  91111. BABYLON.Bone = Bone;
  91112. })(BABYLON || (BABYLON = {}));
  91113. //# sourceMappingURL=babylon.bone.js.map
  91114. var BABYLON;
  91115. (function (BABYLON) {
  91116. /**
  91117. * Class used to apply inverse kinematics to bones
  91118. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  91119. */
  91120. var BoneIKController = /** @class */ (function () {
  91121. /**
  91122. * Creates a new BoneIKController
  91123. * @param mesh defines the mesh to control
  91124. * @param bone defines the bone to control
  91125. * @param options defines options to set up the controller
  91126. */
  91127. function BoneIKController(mesh, bone, options) {
  91128. /**
  91129. * Gets or sets the target position
  91130. */
  91131. this.targetPosition = BABYLON.Vector3.Zero();
  91132. /**
  91133. * Gets or sets the pole target position
  91134. */
  91135. this.poleTargetPosition = BABYLON.Vector3.Zero();
  91136. /**
  91137. * Gets or sets the pole target local offset
  91138. */
  91139. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  91140. /**
  91141. * Gets or sets the pole angle
  91142. */
  91143. this.poleAngle = 0;
  91144. /**
  91145. * 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)
  91146. */
  91147. this.slerpAmount = 1;
  91148. this._bone1Quat = BABYLON.Quaternion.Identity();
  91149. this._bone1Mat = BABYLON.Matrix.Identity();
  91150. this._bone2Ang = Math.PI;
  91151. this._maxAngle = Math.PI;
  91152. this._rightHandedSystem = false;
  91153. this._bendAxis = BABYLON.Vector3.Right();
  91154. this._slerping = false;
  91155. this._adjustRoll = 0;
  91156. this._bone2 = bone;
  91157. this._bone1 = bone.getParent();
  91158. if (!this._bone1) {
  91159. return;
  91160. }
  91161. this.mesh = mesh;
  91162. var bonePos = bone.getPosition();
  91163. if (bone.getAbsoluteTransform().determinant() > 0) {
  91164. this._rightHandedSystem = true;
  91165. this._bendAxis.x = 0;
  91166. this._bendAxis.y = 0;
  91167. this._bendAxis.z = -1;
  91168. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  91169. this._adjustRoll = Math.PI * .5;
  91170. this._bendAxis.z = 1;
  91171. }
  91172. }
  91173. if (this._bone1.length) {
  91174. var boneScale1 = this._bone1.getScale();
  91175. var boneScale2 = this._bone2.getScale();
  91176. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  91177. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  91178. }
  91179. else if (this._bone1.children[0]) {
  91180. mesh.computeWorldMatrix(true);
  91181. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  91182. var pos2 = this._bone2.getAbsolutePosition(mesh);
  91183. var pos3 = this._bone1.getAbsolutePosition(mesh);
  91184. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  91185. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  91186. }
  91187. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  91188. this.maxAngle = Math.PI;
  91189. if (options) {
  91190. if (options.targetMesh) {
  91191. this.targetMesh = options.targetMesh;
  91192. this.targetMesh.computeWorldMatrix(true);
  91193. }
  91194. if (options.poleTargetMesh) {
  91195. this.poleTargetMesh = options.poleTargetMesh;
  91196. this.poleTargetMesh.computeWorldMatrix(true);
  91197. }
  91198. else if (options.poleTargetBone) {
  91199. this.poleTargetBone = options.poleTargetBone;
  91200. }
  91201. else if (this._bone1.getParent()) {
  91202. this.poleTargetBone = this._bone1.getParent();
  91203. }
  91204. if (options.poleTargetLocalOffset) {
  91205. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  91206. }
  91207. if (options.poleAngle) {
  91208. this.poleAngle = options.poleAngle;
  91209. }
  91210. if (options.bendAxis) {
  91211. this._bendAxis.copyFrom(options.bendAxis);
  91212. }
  91213. if (options.maxAngle) {
  91214. this.maxAngle = options.maxAngle;
  91215. }
  91216. if (options.slerpAmount) {
  91217. this.slerpAmount = options.slerpAmount;
  91218. }
  91219. }
  91220. }
  91221. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  91222. /**
  91223. * Gets or sets maximum allowed angle
  91224. */
  91225. get: function () {
  91226. return this._maxAngle;
  91227. },
  91228. set: function (value) {
  91229. this._setMaxAngle(value);
  91230. },
  91231. enumerable: true,
  91232. configurable: true
  91233. });
  91234. BoneIKController.prototype._setMaxAngle = function (ang) {
  91235. if (ang < 0) {
  91236. ang = 0;
  91237. }
  91238. if (ang > Math.PI || ang == undefined) {
  91239. ang = Math.PI;
  91240. }
  91241. this._maxAngle = ang;
  91242. var a = this._bone1Length;
  91243. var b = this._bone2Length;
  91244. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  91245. };
  91246. /**
  91247. * Force the controller to update the bones
  91248. */
  91249. BoneIKController.prototype.update = function () {
  91250. var bone1 = this._bone1;
  91251. if (!bone1) {
  91252. return;
  91253. }
  91254. var target = this.targetPosition;
  91255. var poleTarget = this.poleTargetPosition;
  91256. var mat1 = BoneIKController._tmpMats[0];
  91257. var mat2 = BoneIKController._tmpMats[1];
  91258. if (this.targetMesh) {
  91259. target.copyFrom(this.targetMesh.getAbsolutePosition());
  91260. }
  91261. if (this.poleTargetBone) {
  91262. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  91263. }
  91264. else if (this.poleTargetMesh) {
  91265. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  91266. }
  91267. var bonePos = BoneIKController._tmpVecs[0];
  91268. var zaxis = BoneIKController._tmpVecs[1];
  91269. var xaxis = BoneIKController._tmpVecs[2];
  91270. var yaxis = BoneIKController._tmpVecs[3];
  91271. var upAxis = BoneIKController._tmpVecs[4];
  91272. var _tmpQuat = BoneIKController._tmpQuat;
  91273. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  91274. poleTarget.subtractToRef(bonePos, upAxis);
  91275. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  91276. upAxis.y = 1;
  91277. }
  91278. else {
  91279. upAxis.normalize();
  91280. }
  91281. target.subtractToRef(bonePos, yaxis);
  91282. yaxis.normalize();
  91283. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  91284. zaxis.normalize();
  91285. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  91286. xaxis.normalize();
  91287. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  91288. var a = this._bone1Length;
  91289. var b = this._bone2Length;
  91290. var c = BABYLON.Vector3.Distance(bonePos, target);
  91291. if (this._maxReach > 0) {
  91292. c = Math.min(this._maxReach, c);
  91293. }
  91294. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  91295. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  91296. if (acosa > 1) {
  91297. acosa = 1;
  91298. }
  91299. if (acosb > 1) {
  91300. acosb = 1;
  91301. }
  91302. if (acosa < -1) {
  91303. acosa = -1;
  91304. }
  91305. if (acosb < -1) {
  91306. acosb = -1;
  91307. }
  91308. var angA = Math.acos(acosa);
  91309. var angB = Math.acos(acosb);
  91310. var angC = -angA - angB;
  91311. if (this._rightHandedSystem) {
  91312. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  91313. mat2.multiplyToRef(mat1, mat1);
  91314. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  91315. mat2.multiplyToRef(mat1, mat1);
  91316. }
  91317. else {
  91318. var _tmpVec = BoneIKController._tmpVecs[5];
  91319. _tmpVec.copyFrom(this._bendAxis);
  91320. _tmpVec.x *= -1;
  91321. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  91322. mat2.multiplyToRef(mat1, mat1);
  91323. }
  91324. if (this.poleAngle) {
  91325. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  91326. mat1.multiplyToRef(mat2, mat1);
  91327. }
  91328. if (this._bone1) {
  91329. if (this.slerpAmount < 1) {
  91330. if (!this._slerping) {
  91331. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  91332. }
  91333. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  91334. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  91335. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  91336. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  91337. this._slerping = true;
  91338. }
  91339. else {
  91340. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  91341. this._bone1Mat.copyFrom(mat1);
  91342. this._slerping = false;
  91343. }
  91344. }
  91345. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  91346. this._bone2Ang = angC;
  91347. };
  91348. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  91349. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  91350. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  91351. return BoneIKController;
  91352. }());
  91353. BABYLON.BoneIKController = BoneIKController;
  91354. })(BABYLON || (BABYLON = {}));
  91355. //# sourceMappingURL=babylon.boneIKController.js.map
  91356. var BABYLON;
  91357. (function (BABYLON) {
  91358. /**
  91359. * Class used to make a bone look toward a point in space
  91360. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  91361. */
  91362. var BoneLookController = /** @class */ (function () {
  91363. /**
  91364. * Create a BoneLookController
  91365. * @param mesh the mesh that the bone belongs to
  91366. * @param bone the bone that will be looking to the target
  91367. * @param target the target Vector3 to look at
  91368. * @param settings optional settings:
  91369. * * maxYaw: the maximum angle the bone will yaw to
  91370. * * minYaw: the minimum angle the bone will yaw to
  91371. * * maxPitch: the maximum angle the bone will pitch to
  91372. * * minPitch: the minimum angle the bone will yaw to
  91373. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  91374. * * upAxis: the up axis of the coordinate system
  91375. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  91376. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  91377. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  91378. * * adjustYaw: used to make an adjustment to the yaw of the bone
  91379. * * adjustPitch: used to make an adjustment to the pitch of the bone
  91380. * * adjustRoll: used to make an adjustment to the roll of the bone
  91381. **/
  91382. function BoneLookController(mesh, bone, target, options) {
  91383. /**
  91384. * The up axis of the coordinate system that is used when the bone is rotated
  91385. */
  91386. this.upAxis = BABYLON.Vector3.Up();
  91387. /**
  91388. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  91389. */
  91390. this.upAxisSpace = BABYLON.Space.LOCAL;
  91391. /**
  91392. * Used to make an adjustment to the yaw of the bone
  91393. */
  91394. this.adjustYaw = 0;
  91395. /**
  91396. * Used to make an adjustment to the pitch of the bone
  91397. */
  91398. this.adjustPitch = 0;
  91399. /**
  91400. * Used to make an adjustment to the roll of the bone
  91401. */
  91402. this.adjustRoll = 0;
  91403. /**
  91404. * 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)
  91405. */
  91406. this.slerpAmount = 1;
  91407. this._boneQuat = BABYLON.Quaternion.Identity();
  91408. this._slerping = false;
  91409. this._firstFrameSkipped = false;
  91410. this._fowardAxis = BABYLON.Vector3.Forward();
  91411. this.mesh = mesh;
  91412. this.bone = bone;
  91413. this.target = target;
  91414. if (options) {
  91415. if (options.adjustYaw) {
  91416. this.adjustYaw = options.adjustYaw;
  91417. }
  91418. if (options.adjustPitch) {
  91419. this.adjustPitch = options.adjustPitch;
  91420. }
  91421. if (options.adjustRoll) {
  91422. this.adjustRoll = options.adjustRoll;
  91423. }
  91424. if (options.maxYaw != null) {
  91425. this.maxYaw = options.maxYaw;
  91426. }
  91427. else {
  91428. this.maxYaw = Math.PI;
  91429. }
  91430. if (options.minYaw != null) {
  91431. this.minYaw = options.minYaw;
  91432. }
  91433. else {
  91434. this.minYaw = -Math.PI;
  91435. }
  91436. if (options.maxPitch != null) {
  91437. this.maxPitch = options.maxPitch;
  91438. }
  91439. else {
  91440. this.maxPitch = Math.PI;
  91441. }
  91442. if (options.minPitch != null) {
  91443. this.minPitch = options.minPitch;
  91444. }
  91445. else {
  91446. this.minPitch = -Math.PI;
  91447. }
  91448. if (options.slerpAmount != null) {
  91449. this.slerpAmount = options.slerpAmount;
  91450. }
  91451. if (options.upAxis != null) {
  91452. this.upAxis = options.upAxis;
  91453. }
  91454. if (options.upAxisSpace != null) {
  91455. this.upAxisSpace = options.upAxisSpace;
  91456. }
  91457. if (options.yawAxis != null || options.pitchAxis != null) {
  91458. var newYawAxis = BABYLON.Axis.Y;
  91459. var newPitchAxis = BABYLON.Axis.X;
  91460. if (options.yawAxis != null) {
  91461. newYawAxis = options.yawAxis.clone();
  91462. newYawAxis.normalize();
  91463. }
  91464. if (options.pitchAxis != null) {
  91465. newPitchAxis = options.pitchAxis.clone();
  91466. newPitchAxis.normalize();
  91467. }
  91468. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  91469. this._transformYawPitch = BABYLON.Matrix.Identity();
  91470. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  91471. this._transformYawPitchInv = this._transformYawPitch.clone();
  91472. this._transformYawPitch.invert();
  91473. }
  91474. }
  91475. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  91476. this.upAxisSpace = BABYLON.Space.LOCAL;
  91477. }
  91478. }
  91479. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  91480. /**
  91481. * Gets or sets the minimum yaw angle that the bone can look to
  91482. */
  91483. get: function () {
  91484. return this._minYaw;
  91485. },
  91486. set: function (value) {
  91487. this._minYaw = value;
  91488. this._minYawSin = Math.sin(value);
  91489. this._minYawCos = Math.cos(value);
  91490. if (this._maxYaw != null) {
  91491. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  91492. this._yawRange = this._maxYaw - this._minYaw;
  91493. }
  91494. },
  91495. enumerable: true,
  91496. configurable: true
  91497. });
  91498. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  91499. /**
  91500. * Gets or sets the maximum yaw angle that the bone can look to
  91501. */
  91502. get: function () {
  91503. return this._maxYaw;
  91504. },
  91505. set: function (value) {
  91506. this._maxYaw = value;
  91507. this._maxYawSin = Math.sin(value);
  91508. this._maxYawCos = Math.cos(value);
  91509. if (this._minYaw != null) {
  91510. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  91511. this._yawRange = this._maxYaw - this._minYaw;
  91512. }
  91513. },
  91514. enumerable: true,
  91515. configurable: true
  91516. });
  91517. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  91518. /**
  91519. * Gets or sets the minimum pitch angle that the bone can look to
  91520. */
  91521. get: function () {
  91522. return this._minPitch;
  91523. },
  91524. set: function (value) {
  91525. this._minPitch = value;
  91526. this._minPitchTan = Math.tan(value);
  91527. },
  91528. enumerable: true,
  91529. configurable: true
  91530. });
  91531. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  91532. /**
  91533. * Gets or sets the maximum pitch angle that the bone can look to
  91534. */
  91535. get: function () {
  91536. return this._maxPitch;
  91537. },
  91538. set: function (value) {
  91539. this._maxPitch = value;
  91540. this._maxPitchTan = Math.tan(value);
  91541. },
  91542. enumerable: true,
  91543. configurable: true
  91544. });
  91545. /**
  91546. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  91547. */
  91548. BoneLookController.prototype.update = function () {
  91549. //skip the first frame when slerping so that the mesh rotation is correct
  91550. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  91551. this._firstFrameSkipped = true;
  91552. return;
  91553. }
  91554. var bone = this.bone;
  91555. var bonePos = BoneLookController._tmpVecs[0];
  91556. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  91557. var target = this.target;
  91558. var _tmpMat1 = BoneLookController._tmpMats[0];
  91559. var _tmpMat2 = BoneLookController._tmpMats[1];
  91560. var mesh = this.mesh;
  91561. var parentBone = bone.getParent();
  91562. var upAxis = BoneLookController._tmpVecs[1];
  91563. upAxis.copyFrom(this.upAxis);
  91564. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  91565. if (this._transformYawPitch) {
  91566. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  91567. }
  91568. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  91569. }
  91570. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  91571. mesh.getDirectionToRef(upAxis, upAxis);
  91572. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  91573. upAxis.normalize();
  91574. }
  91575. }
  91576. var checkYaw = false;
  91577. var checkPitch = false;
  91578. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  91579. checkYaw = true;
  91580. }
  91581. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  91582. checkPitch = true;
  91583. }
  91584. if (checkYaw || checkPitch) {
  91585. var spaceMat = BoneLookController._tmpMats[2];
  91586. var spaceMatInv = BoneLookController._tmpMats[3];
  91587. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  91588. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  91589. }
  91590. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  91591. spaceMat.copyFrom(mesh.getWorldMatrix());
  91592. }
  91593. else {
  91594. var forwardAxis = BoneLookController._tmpVecs[2];
  91595. forwardAxis.copyFrom(this._fowardAxis);
  91596. if (this._transformYawPitch) {
  91597. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  91598. }
  91599. if (parentBone) {
  91600. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  91601. }
  91602. else {
  91603. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  91604. }
  91605. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  91606. rightAxis.normalize();
  91607. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  91608. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  91609. }
  91610. spaceMat.invertToRef(spaceMatInv);
  91611. var xzlen = null;
  91612. if (checkPitch) {
  91613. var localTarget = BoneLookController._tmpVecs[3];
  91614. target.subtractToRef(bonePos, localTarget);
  91615. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  91616. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  91617. var pitch = Math.atan2(localTarget.y, xzlen);
  91618. var newPitch = pitch;
  91619. if (pitch > this._maxPitch) {
  91620. localTarget.y = this._maxPitchTan * xzlen;
  91621. newPitch = this._maxPitch;
  91622. }
  91623. else if (pitch < this._minPitch) {
  91624. localTarget.y = this._minPitchTan * xzlen;
  91625. newPitch = this._minPitch;
  91626. }
  91627. if (pitch != newPitch) {
  91628. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  91629. localTarget.addInPlace(bonePos);
  91630. target = localTarget;
  91631. }
  91632. }
  91633. if (checkYaw) {
  91634. var localTarget = BoneLookController._tmpVecs[4];
  91635. target.subtractToRef(bonePos, localTarget);
  91636. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  91637. var yaw = Math.atan2(localTarget.x, localTarget.z);
  91638. var newYaw = yaw;
  91639. if (yaw > this._maxYaw || yaw < this._minYaw) {
  91640. if (xzlen == null) {
  91641. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  91642. }
  91643. if (this._yawRange > Math.PI) {
  91644. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  91645. localTarget.z = this._maxYawCos * xzlen;
  91646. localTarget.x = this._maxYawSin * xzlen;
  91647. newYaw = this._maxYaw;
  91648. }
  91649. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  91650. localTarget.z = this._minYawCos * xzlen;
  91651. localTarget.x = this._minYawSin * xzlen;
  91652. newYaw = this._minYaw;
  91653. }
  91654. }
  91655. else {
  91656. if (yaw > this._maxYaw) {
  91657. localTarget.z = this._maxYawCos * xzlen;
  91658. localTarget.x = this._maxYawSin * xzlen;
  91659. newYaw = this._maxYaw;
  91660. }
  91661. else if (yaw < this._minYaw) {
  91662. localTarget.z = this._minYawCos * xzlen;
  91663. localTarget.x = this._minYawSin * xzlen;
  91664. newYaw = this._minYaw;
  91665. }
  91666. }
  91667. }
  91668. if (this._slerping && this._yawRange > Math.PI) {
  91669. //are we going to be crossing into the min/max region?
  91670. var boneFwd = BoneLookController._tmpVecs[8];
  91671. boneFwd.copyFrom(BABYLON.Axis.Z);
  91672. if (this._transformYawPitch) {
  91673. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  91674. }
  91675. var boneRotMat = BoneLookController._tmpMats[4];
  91676. this._boneQuat.toRotationMatrix(boneRotMat);
  91677. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  91678. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  91679. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  91680. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  91681. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  91682. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  91683. if (angBtwTar > angBtwMidYaw) {
  91684. if (xzlen == null) {
  91685. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  91686. }
  91687. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  91688. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  91689. if (angBtwMin < angBtwMax) {
  91690. newYaw = boneYaw + Math.PI * .75;
  91691. localTarget.z = Math.cos(newYaw) * xzlen;
  91692. localTarget.x = Math.sin(newYaw) * xzlen;
  91693. }
  91694. else {
  91695. newYaw = boneYaw - Math.PI * .75;
  91696. localTarget.z = Math.cos(newYaw) * xzlen;
  91697. localTarget.x = Math.sin(newYaw) * xzlen;
  91698. }
  91699. }
  91700. }
  91701. if (yaw != newYaw) {
  91702. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  91703. localTarget.addInPlace(bonePos);
  91704. target = localTarget;
  91705. }
  91706. }
  91707. }
  91708. var zaxis = BoneLookController._tmpVecs[5];
  91709. var xaxis = BoneLookController._tmpVecs[6];
  91710. var yaxis = BoneLookController._tmpVecs[7];
  91711. var _tmpQuat = BoneLookController._tmpQuat;
  91712. target.subtractToRef(bonePos, zaxis);
  91713. zaxis.normalize();
  91714. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  91715. xaxis.normalize();
  91716. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  91717. yaxis.normalize();
  91718. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  91719. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  91720. return;
  91721. }
  91722. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  91723. return;
  91724. }
  91725. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  91726. return;
  91727. }
  91728. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  91729. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  91730. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  91731. }
  91732. if (this.slerpAmount < 1) {
  91733. if (!this._slerping) {
  91734. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  91735. }
  91736. if (this._transformYawPitch) {
  91737. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  91738. }
  91739. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  91740. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  91741. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  91742. this._slerping = true;
  91743. }
  91744. else {
  91745. if (this._transformYawPitch) {
  91746. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  91747. }
  91748. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  91749. this._slerping = false;
  91750. }
  91751. };
  91752. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  91753. var angDiff = ang2 - ang1;
  91754. angDiff %= Math.PI * 2;
  91755. if (angDiff > Math.PI) {
  91756. angDiff -= Math.PI * 2;
  91757. }
  91758. else if (angDiff < -Math.PI) {
  91759. angDiff += Math.PI * 2;
  91760. }
  91761. return angDiff;
  91762. };
  91763. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  91764. ang1 %= (2 * Math.PI);
  91765. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  91766. ang2 %= (2 * Math.PI);
  91767. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  91768. var ab = 0;
  91769. if (ang1 < ang2) {
  91770. ab = ang2 - ang1;
  91771. }
  91772. else {
  91773. ab = ang1 - ang2;
  91774. }
  91775. if (ab > Math.PI) {
  91776. ab = Math.PI * 2 - ab;
  91777. }
  91778. return ab;
  91779. };
  91780. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  91781. ang %= (2 * Math.PI);
  91782. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  91783. ang1 %= (2 * Math.PI);
  91784. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  91785. ang2 %= (2 * Math.PI);
  91786. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  91787. if (ang1 < ang2) {
  91788. if (ang > ang1 && ang < ang2) {
  91789. return true;
  91790. }
  91791. }
  91792. else {
  91793. if (ang > ang2 && ang < ang1) {
  91794. return true;
  91795. }
  91796. }
  91797. return false;
  91798. };
  91799. BoneLookController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  91800. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  91801. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  91802. return BoneLookController;
  91803. }());
  91804. BABYLON.BoneLookController = BoneLookController;
  91805. })(BABYLON || (BABYLON = {}));
  91806. //# sourceMappingURL=babylon.boneLookController.js.map
  91807. var BABYLON;
  91808. (function (BABYLON) {
  91809. /**
  91810. * Class used to handle skinning animations
  91811. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  91812. */
  91813. var Skeleton = /** @class */ (function () {
  91814. /**
  91815. * Creates a new skeleton
  91816. * @param name defines the skeleton name
  91817. * @param id defines the skeleton Id
  91818. * @param scene defines the hosting scene
  91819. */
  91820. function Skeleton(
  91821. /** defines the skeleton name */
  91822. name,
  91823. /** defines the skeleton Id */
  91824. id, scene) {
  91825. this.name = name;
  91826. this.id = id;
  91827. /**
  91828. * Gets the list of child bones
  91829. */
  91830. this.bones = new Array();
  91831. /**
  91832. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  91833. */
  91834. this.needInitialSkinMatrix = false;
  91835. this._isDirty = true;
  91836. this._meshesWithPoseMatrix = new Array();
  91837. this._identity = BABYLON.Matrix.Identity();
  91838. this._ranges = {};
  91839. this._lastAbsoluteTransformsUpdateId = -1;
  91840. /**
  91841. * Specifies if the skeleton should be serialized
  91842. */
  91843. this.doNotSerialize = false;
  91844. this._animationPropertiesOverride = null;
  91845. // Events
  91846. /**
  91847. * An observable triggered before computing the skeleton's matrices
  91848. */
  91849. this.onBeforeComputeObservable = new BABYLON.Observable();
  91850. this.bones = [];
  91851. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  91852. scene.skeletons.push(this);
  91853. //make sure it will recalculate the matrix next time prepare is called.
  91854. this._isDirty = true;
  91855. }
  91856. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  91857. /**
  91858. * Gets or sets the animation properties override
  91859. */
  91860. get: function () {
  91861. if (!this._animationPropertiesOverride) {
  91862. return this._scene.animationPropertiesOverride;
  91863. }
  91864. return this._animationPropertiesOverride;
  91865. },
  91866. set: function (value) {
  91867. this._animationPropertiesOverride = value;
  91868. },
  91869. enumerable: true,
  91870. configurable: true
  91871. });
  91872. // Members
  91873. /**
  91874. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  91875. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  91876. * @returns a Float32Array containing matrices data
  91877. */
  91878. Skeleton.prototype.getTransformMatrices = function (mesh) {
  91879. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  91880. return mesh._bonesTransformMatrices;
  91881. }
  91882. if (!this._transformMatrices) {
  91883. this.prepare();
  91884. }
  91885. return this._transformMatrices;
  91886. };
  91887. /**
  91888. * Gets the current hosting scene
  91889. * @returns a scene object
  91890. */
  91891. Skeleton.prototype.getScene = function () {
  91892. return this._scene;
  91893. };
  91894. // Methods
  91895. /**
  91896. * Gets a string representing the current skeleton data
  91897. * @param fullDetails defines a boolean indicating if we want a verbose version
  91898. * @returns a string representing the current skeleton data
  91899. */
  91900. Skeleton.prototype.toString = function (fullDetails) {
  91901. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  91902. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  91903. if (fullDetails) {
  91904. ret += ", Ranges: {";
  91905. var first = true;
  91906. for (var name_1 in this._ranges) {
  91907. if (first) {
  91908. ret += ", ";
  91909. first = false;
  91910. }
  91911. ret += name_1;
  91912. }
  91913. ret += "}";
  91914. }
  91915. return ret;
  91916. };
  91917. /**
  91918. * Get bone's index searching by name
  91919. * @param name defines bone's name to search for
  91920. * @return the indice of the bone. Returns -1 if not found
  91921. */
  91922. Skeleton.prototype.getBoneIndexByName = function (name) {
  91923. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  91924. if (this.bones[boneIndex].name === name) {
  91925. return boneIndex;
  91926. }
  91927. }
  91928. return -1;
  91929. };
  91930. /**
  91931. * Creater a new animation range
  91932. * @param name defines the name of the range
  91933. * @param from defines the start key
  91934. * @param to defines the end key
  91935. */
  91936. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  91937. // check name not already in use
  91938. if (!this._ranges[name]) {
  91939. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  91940. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  91941. if (this.bones[i].animations[0]) {
  91942. this.bones[i].animations[0].createRange(name, from, to);
  91943. }
  91944. }
  91945. }
  91946. };
  91947. /**
  91948. * Delete a specific animation range
  91949. * @param name defines the name of the range
  91950. * @param deleteFrames defines if frames must be removed as well
  91951. */
  91952. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  91953. if (deleteFrames === void 0) { deleteFrames = true; }
  91954. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  91955. if (this.bones[i].animations[0]) {
  91956. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  91957. }
  91958. }
  91959. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  91960. };
  91961. /**
  91962. * Gets a specific animation range
  91963. * @param name defines the name of the range to look for
  91964. * @returns the requested animation range or null if not found
  91965. */
  91966. Skeleton.prototype.getAnimationRange = function (name) {
  91967. return this._ranges[name];
  91968. };
  91969. /**
  91970. * Gets the list of all animation ranges defined on this skeleton
  91971. * @returns an array
  91972. */
  91973. Skeleton.prototype.getAnimationRanges = function () {
  91974. var animationRanges = [];
  91975. var name;
  91976. var i = 0;
  91977. for (name in this._ranges) {
  91978. animationRanges[i] = this._ranges[name];
  91979. i++;
  91980. }
  91981. return animationRanges;
  91982. };
  91983. /**
  91984. * Copy animation range from a source skeleton.
  91985. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  91986. * @param source defines the source skeleton
  91987. * @param name defines the name of the range to copy
  91988. * @param rescaleAsRequired defines if rescaling must be applied if required
  91989. * @returns true if operation was successful
  91990. */
  91991. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  91992. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  91993. if (this._ranges[name] || !source.getAnimationRange(name)) {
  91994. return false;
  91995. }
  91996. var ret = true;
  91997. var frameOffset = this._getHighestAnimationFrame() + 1;
  91998. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  91999. var boneDict = {};
  92000. var sourceBones = source.bones;
  92001. var nBones;
  92002. var i;
  92003. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  92004. boneDict[sourceBones[i].name] = sourceBones[i];
  92005. }
  92006. if (this.bones.length !== sourceBones.length) {
  92007. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  92008. ret = false;
  92009. }
  92010. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  92011. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  92012. var boneName = this.bones[i].name;
  92013. var sourceBone = boneDict[boneName];
  92014. if (sourceBone) {
  92015. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  92016. }
  92017. else {
  92018. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  92019. ret = false;
  92020. }
  92021. }
  92022. // do not call createAnimationRange(), since it also is done to bones, which was already done
  92023. var range = source.getAnimationRange(name);
  92024. if (range) {
  92025. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  92026. }
  92027. return ret;
  92028. };
  92029. /**
  92030. * Forces the skeleton to go to rest pose
  92031. */
  92032. Skeleton.prototype.returnToRest = function () {
  92033. for (var index = 0; index < this.bones.length; index++) {
  92034. this.bones[index].returnToRest();
  92035. }
  92036. };
  92037. Skeleton.prototype._getHighestAnimationFrame = function () {
  92038. var ret = 0;
  92039. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  92040. if (this.bones[i].animations[0]) {
  92041. var highest = this.bones[i].animations[0].getHighestFrame();
  92042. if (ret < highest) {
  92043. ret = highest;
  92044. }
  92045. }
  92046. }
  92047. return ret;
  92048. };
  92049. /**
  92050. * Begin a specific animation range
  92051. * @param name defines the name of the range to start
  92052. * @param loop defines if looping must be turned on (false by default)
  92053. * @param speedRatio defines the speed ratio to apply (1 by default)
  92054. * @param onAnimationEnd defines a callback which will be called when animation will end
  92055. * @returns a new animatable
  92056. */
  92057. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  92058. var range = this.getAnimationRange(name);
  92059. if (!range) {
  92060. return null;
  92061. }
  92062. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  92063. };
  92064. /** @hidden */
  92065. Skeleton.prototype._markAsDirty = function () {
  92066. this._isDirty = true;
  92067. };
  92068. /** @hidden */
  92069. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  92070. this._meshesWithPoseMatrix.push(mesh);
  92071. };
  92072. /** @hidden */
  92073. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  92074. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  92075. if (index > -1) {
  92076. this._meshesWithPoseMatrix.splice(index, 1);
  92077. }
  92078. };
  92079. /** @hidden */
  92080. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  92081. this.onBeforeComputeObservable.notifyObservers(this);
  92082. for (var index = 0; index < this.bones.length; index++) {
  92083. var bone = this.bones[index];
  92084. var parentBone = bone.getParent();
  92085. if (parentBone) {
  92086. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  92087. }
  92088. else {
  92089. if (initialSkinMatrix) {
  92090. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  92091. }
  92092. else {
  92093. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  92094. }
  92095. }
  92096. if (bone._index !== -1) {
  92097. var mappedIndex = bone._index === null ? index : bone._index;
  92098. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  92099. }
  92100. }
  92101. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  92102. };
  92103. /**
  92104. * Build all resources required to render a skeleton
  92105. */
  92106. Skeleton.prototype.prepare = function () {
  92107. if (!this._isDirty) {
  92108. return;
  92109. }
  92110. if (this.needInitialSkinMatrix) {
  92111. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  92112. var mesh = this._meshesWithPoseMatrix[index];
  92113. var poseMatrix = mesh.getPoseMatrix();
  92114. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  92115. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  92116. }
  92117. if (this._synchronizedWithMesh !== mesh) {
  92118. this._synchronizedWithMesh = mesh;
  92119. // Prepare bones
  92120. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  92121. var bone = this.bones[boneIndex];
  92122. if (!bone.getParent()) {
  92123. var matrix = bone.getBaseMatrix();
  92124. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  92125. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  92126. }
  92127. }
  92128. }
  92129. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  92130. }
  92131. }
  92132. else {
  92133. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  92134. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  92135. }
  92136. this._computeTransformMatrices(this._transformMatrices, null);
  92137. }
  92138. this._isDirty = false;
  92139. this._scene._activeBones.addCount(this.bones.length, false);
  92140. };
  92141. /**
  92142. * Gets the list of animatables currently running for this skeleton
  92143. * @returns an array of animatables
  92144. */
  92145. Skeleton.prototype.getAnimatables = function () {
  92146. if (!this._animatables || this._animatables.length !== this.bones.length) {
  92147. this._animatables = [];
  92148. for (var index = 0; index < this.bones.length; index++) {
  92149. this._animatables.push(this.bones[index]);
  92150. }
  92151. }
  92152. return this._animatables;
  92153. };
  92154. /**
  92155. * Clone the current skeleton
  92156. * @param name defines the name of the new skeleton
  92157. * @param id defines the id of the enw skeleton
  92158. * @returns the new skeleton
  92159. */
  92160. Skeleton.prototype.clone = function (name, id) {
  92161. var result = new Skeleton(name, id || name, this._scene);
  92162. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  92163. for (var index = 0; index < this.bones.length; index++) {
  92164. var source = this.bones[index];
  92165. var parentBone = null;
  92166. var parent_1 = source.getParent();
  92167. if (parent_1) {
  92168. var parentIndex = this.bones.indexOf(parent_1);
  92169. parentBone = result.bones[parentIndex];
  92170. }
  92171. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  92172. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  92173. }
  92174. if (this._ranges) {
  92175. result._ranges = {};
  92176. for (var rangeName in this._ranges) {
  92177. var range = this._ranges[rangeName];
  92178. if (range) {
  92179. result._ranges[rangeName] = range.clone();
  92180. }
  92181. }
  92182. }
  92183. this._isDirty = true;
  92184. return result;
  92185. };
  92186. /**
  92187. * Enable animation blending for this skeleton
  92188. * @param blendingSpeed defines the blending speed to apply
  92189. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  92190. */
  92191. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  92192. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  92193. this.bones.forEach(function (bone) {
  92194. bone.animations.forEach(function (animation) {
  92195. animation.enableBlending = true;
  92196. animation.blendingSpeed = blendingSpeed;
  92197. });
  92198. });
  92199. };
  92200. /**
  92201. * Releases all resources associated with the current skeleton
  92202. */
  92203. Skeleton.prototype.dispose = function () {
  92204. this._meshesWithPoseMatrix = [];
  92205. // Animations
  92206. this.getScene().stopAnimation(this);
  92207. // Remove from scene
  92208. this.getScene().removeSkeleton(this);
  92209. };
  92210. /**
  92211. * Serialize the skeleton in a JSON object
  92212. * @returns a JSON object
  92213. */
  92214. Skeleton.prototype.serialize = function () {
  92215. var serializationObject = {};
  92216. serializationObject.name = this.name;
  92217. serializationObject.id = this.id;
  92218. if (this.dimensionsAtRest) {
  92219. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  92220. }
  92221. serializationObject.bones = [];
  92222. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  92223. for (var index = 0; index < this.bones.length; index++) {
  92224. var bone = this.bones[index];
  92225. var parent_2 = bone.getParent();
  92226. var serializedBone = {
  92227. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  92228. name: bone.name,
  92229. matrix: bone.getBaseMatrix().toArray(),
  92230. rest: bone.getRestPose().toArray()
  92231. };
  92232. serializationObject.bones.push(serializedBone);
  92233. if (bone.length) {
  92234. serializedBone.length = bone.length;
  92235. }
  92236. if (bone.metadata) {
  92237. serializedBone.metadata = bone.metadata;
  92238. }
  92239. if (bone.animations && bone.animations.length > 0) {
  92240. serializedBone.animation = bone.animations[0].serialize();
  92241. }
  92242. serializationObject.ranges = [];
  92243. for (var name in this._ranges) {
  92244. var source = this._ranges[name];
  92245. if (!source) {
  92246. continue;
  92247. }
  92248. var range = {};
  92249. range.name = name;
  92250. range.from = source.from;
  92251. range.to = source.to;
  92252. serializationObject.ranges.push(range);
  92253. }
  92254. }
  92255. return serializationObject;
  92256. };
  92257. /**
  92258. * Creates a new skeleton from serialized data
  92259. * @param parsedSkeleton defines the serialized data
  92260. * @param scene defines the hosting scene
  92261. * @returns a new skeleton
  92262. */
  92263. Skeleton.Parse = function (parsedSkeleton, scene) {
  92264. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  92265. if (parsedSkeleton.dimensionsAtRest) {
  92266. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  92267. }
  92268. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  92269. var index;
  92270. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  92271. var parsedBone = parsedSkeleton.bones[index];
  92272. var parentBone = null;
  92273. if (parsedBone.parentBoneIndex > -1) {
  92274. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  92275. }
  92276. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  92277. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  92278. if (parsedBone.id !== undefined && parsedBone.id !== null) {
  92279. bone.id = parsedBone.id;
  92280. }
  92281. if (parsedBone.length) {
  92282. bone.length = parsedBone.length;
  92283. }
  92284. if (parsedBone.metadata) {
  92285. bone.metadata = parsedBone.metadata;
  92286. }
  92287. if (parsedBone.animation) {
  92288. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  92289. }
  92290. }
  92291. // placed after bones, so createAnimationRange can cascade down
  92292. if (parsedSkeleton.ranges) {
  92293. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  92294. var data = parsedSkeleton.ranges[index];
  92295. skeleton.createAnimationRange(data.name, data.from, data.to);
  92296. }
  92297. }
  92298. return skeleton;
  92299. };
  92300. /**
  92301. * Compute all node absolute transforms
  92302. * @param forceUpdate defines if computation must be done even if cache is up to date
  92303. */
  92304. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  92305. if (forceUpdate === void 0) { forceUpdate = false; }
  92306. var renderId = this._scene.getRenderId();
  92307. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  92308. this.bones[0].computeAbsoluteTransforms();
  92309. this._lastAbsoluteTransformsUpdateId = renderId;
  92310. }
  92311. };
  92312. /**
  92313. * Gets the root pose matrix
  92314. * @returns a matrix
  92315. */
  92316. Skeleton.prototype.getPoseMatrix = function () {
  92317. var poseMatrix = null;
  92318. if (this._meshesWithPoseMatrix.length > 0) {
  92319. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  92320. }
  92321. return poseMatrix;
  92322. };
  92323. /**
  92324. * Sorts bones per internal index
  92325. */
  92326. Skeleton.prototype.sortBones = function () {
  92327. var bones = new Array();
  92328. var visited = new Array(this.bones.length);
  92329. for (var index = 0; index < this.bones.length; index++) {
  92330. this._sortBones(index, bones, visited);
  92331. }
  92332. this.bones = bones;
  92333. };
  92334. Skeleton.prototype._sortBones = function (index, bones, visited) {
  92335. if (visited[index]) {
  92336. return;
  92337. }
  92338. visited[index] = true;
  92339. var bone = this.bones[index];
  92340. if (bone._index === undefined) {
  92341. bone._index = index;
  92342. }
  92343. var parentBone = bone.getParent();
  92344. if (parentBone) {
  92345. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  92346. }
  92347. bones.push(bone);
  92348. };
  92349. return Skeleton;
  92350. }());
  92351. BABYLON.Skeleton = Skeleton;
  92352. })(BABYLON || (BABYLON = {}));
  92353. //# sourceMappingURL=babylon.skeleton.js.map
  92354. var BABYLON;
  92355. (function (BABYLON) {
  92356. /**
  92357. * This groups tools to convert HDR texture to native colors array.
  92358. */
  92359. var HDRTools = /** @class */ (function () {
  92360. function HDRTools() {
  92361. }
  92362. HDRTools.Ldexp = function (mantissa, exponent) {
  92363. if (exponent > 1023) {
  92364. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  92365. }
  92366. if (exponent < -1074) {
  92367. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  92368. }
  92369. return mantissa * Math.pow(2, exponent);
  92370. };
  92371. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  92372. if (exponent > 0) { /*nonzero pixel*/
  92373. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  92374. float32array[index + 0] = red * exponent;
  92375. float32array[index + 1] = green * exponent;
  92376. float32array[index + 2] = blue * exponent;
  92377. }
  92378. else {
  92379. float32array[index + 0] = 0;
  92380. float32array[index + 1] = 0;
  92381. float32array[index + 2] = 0;
  92382. }
  92383. };
  92384. HDRTools.readStringLine = function (uint8array, startIndex) {
  92385. var line = "";
  92386. var character = "";
  92387. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  92388. character = String.fromCharCode(uint8array[i]);
  92389. if (character == "\n") {
  92390. break;
  92391. }
  92392. line += character;
  92393. }
  92394. return line;
  92395. };
  92396. /**
  92397. * Reads header information from an RGBE texture stored in a native array.
  92398. * More information on this format are available here:
  92399. * https://en.wikipedia.org/wiki/RGBE_image_format
  92400. *
  92401. * @param uint8array The binary file stored in native array.
  92402. * @return The header information.
  92403. */
  92404. HDRTools.RGBE_ReadHeader = function (uint8array) {
  92405. var height = 0;
  92406. var width = 0;
  92407. var line = this.readStringLine(uint8array, 0);
  92408. if (line[0] != '#' || line[1] != '?') {
  92409. throw "Bad HDR Format.";
  92410. }
  92411. var endOfHeader = false;
  92412. var findFormat = false;
  92413. var lineIndex = 0;
  92414. do {
  92415. lineIndex += (line.length + 1);
  92416. line = this.readStringLine(uint8array, lineIndex);
  92417. if (line == "FORMAT=32-bit_rle_rgbe") {
  92418. findFormat = true;
  92419. }
  92420. else if (line.length == 0) {
  92421. endOfHeader = true;
  92422. }
  92423. } while (!endOfHeader);
  92424. if (!findFormat) {
  92425. throw "HDR Bad header format, unsupported FORMAT";
  92426. }
  92427. lineIndex += (line.length + 1);
  92428. line = this.readStringLine(uint8array, lineIndex);
  92429. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  92430. var match = sizeRegexp.exec(line);
  92431. // TODO. Support +Y and -X if needed.
  92432. if (!match || match.length < 3) {
  92433. throw "HDR Bad header format, no size";
  92434. }
  92435. width = parseInt(match[2]);
  92436. height = parseInt(match[1]);
  92437. if (width < 8 || width > 0x7fff) {
  92438. throw "HDR Bad header format, unsupported size";
  92439. }
  92440. lineIndex += (line.length + 1);
  92441. return {
  92442. height: height,
  92443. width: width,
  92444. dataPosition: lineIndex
  92445. };
  92446. };
  92447. /**
  92448. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  92449. * This RGBE texture needs to store the information as a panorama.
  92450. *
  92451. * More information on this format are available here:
  92452. * https://en.wikipedia.org/wiki/RGBE_image_format
  92453. *
  92454. * @param buffer The binary file stored in an array buffer.
  92455. * @param size The expected size of the extracted cubemap.
  92456. * @return The Cube Map information.
  92457. */
  92458. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  92459. var uint8array = new Uint8Array(buffer);
  92460. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  92461. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  92462. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  92463. return cubeMapData;
  92464. };
  92465. /**
  92466. * Returns the pixels data extracted from an RGBE texture.
  92467. * This pixels will be stored left to right up to down in the R G B order in one array.
  92468. *
  92469. * More information on this format are available here:
  92470. * https://en.wikipedia.org/wiki/RGBE_image_format
  92471. *
  92472. * @param uint8array The binary file stored in an array buffer.
  92473. * @param hdrInfo The header information of the file.
  92474. * @return The pixels data in RGB right to left up to down order.
  92475. */
  92476. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  92477. // Keep for multi format supports.
  92478. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  92479. };
  92480. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  92481. var num_scanlines = hdrInfo.height;
  92482. var scanline_width = hdrInfo.width;
  92483. var a, b, c, d, count;
  92484. var dataIndex = hdrInfo.dataPosition;
  92485. var index = 0, endIndex = 0, i = 0;
  92486. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  92487. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  92488. // 3 channels of 4 bytes per pixel in float.
  92489. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  92490. var resultArray = new Float32Array(resultBuffer);
  92491. // read in each successive scanline
  92492. while (num_scanlines > 0) {
  92493. a = uint8array[dataIndex++];
  92494. b = uint8array[dataIndex++];
  92495. c = uint8array[dataIndex++];
  92496. d = uint8array[dataIndex++];
  92497. if (a != 2 || b != 2 || (c & 0x80)) {
  92498. // this file is not run length encoded
  92499. throw "HDR Bad header format, not RLE";
  92500. }
  92501. if (((c << 8) | d) != scanline_width) {
  92502. throw "HDR Bad header format, wrong scan line width";
  92503. }
  92504. index = 0;
  92505. // read each of the four channels for the scanline into the buffer
  92506. for (i = 0; i < 4; i++) {
  92507. endIndex = (i + 1) * scanline_width;
  92508. while (index < endIndex) {
  92509. a = uint8array[dataIndex++];
  92510. b = uint8array[dataIndex++];
  92511. if (a > 128) {
  92512. // a run of the same value
  92513. count = a - 128;
  92514. if ((count == 0) || (count > endIndex - index)) {
  92515. throw "HDR Bad Format, bad scanline data (run)";
  92516. }
  92517. while (count-- > 0) {
  92518. scanLineArray[index++] = b;
  92519. }
  92520. }
  92521. else {
  92522. // a non-run
  92523. count = a;
  92524. if ((count == 0) || (count > endIndex - index)) {
  92525. throw "HDR Bad Format, bad scanline data (non-run)";
  92526. }
  92527. scanLineArray[index++] = b;
  92528. if (--count > 0) {
  92529. for (var j = 0; j < count; j++) {
  92530. scanLineArray[index++] = uint8array[dataIndex++];
  92531. }
  92532. }
  92533. }
  92534. }
  92535. }
  92536. // now convert data from buffer into floats
  92537. for (i = 0; i < scanline_width; i++) {
  92538. a = scanLineArray[i];
  92539. b = scanLineArray[i + scanline_width];
  92540. c = scanLineArray[i + 2 * scanline_width];
  92541. d = scanLineArray[i + 3 * scanline_width];
  92542. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  92543. }
  92544. num_scanlines--;
  92545. }
  92546. return resultArray;
  92547. };
  92548. return HDRTools;
  92549. }());
  92550. BABYLON.HDRTools = HDRTools;
  92551. })(BABYLON || (BABYLON = {}));
  92552. //# sourceMappingURL=babylon.hdr.js.map
  92553. var BABYLON;
  92554. (function (BABYLON) {
  92555. /**
  92556. * This represents a texture coming from an HDR input.
  92557. *
  92558. * The only supported format is currently panorama picture stored in RGBE format.
  92559. * Example of such files can be found on HDRLib: http://hdrlib.com/
  92560. */
  92561. var HDRCubeTexture = /** @class */ (function (_super) {
  92562. __extends(HDRCubeTexture, _super);
  92563. /**
  92564. * Instantiates an HDRTexture from the following parameters.
  92565. *
  92566. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  92567. * @param scene The scene the texture will be used in
  92568. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  92569. * @param noMipmap Forces to not generate the mipmap if true
  92570. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  92571. * @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)
  92572. * @param reserved Reserved flag for internal use.
  92573. */
  92574. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  92575. if (noMipmap === void 0) { noMipmap = false; }
  92576. if (generateHarmonics === void 0) { generateHarmonics = true; }
  92577. if (gammaSpace === void 0) { gammaSpace = false; }
  92578. if (reserved === void 0) { reserved = false; }
  92579. if (onLoad === void 0) { onLoad = null; }
  92580. if (onError === void 0) { onError = null; }
  92581. var _this = _super.call(this, scene) || this;
  92582. _this._generateHarmonics = true;
  92583. _this._onLoad = null;
  92584. _this._onError = null;
  92585. /**
  92586. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  92587. */
  92588. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  92589. _this._isBlocking = true;
  92590. _this._rotationY = 0;
  92591. /**
  92592. * Gets or sets the center of the bounding box associated with the cube texture
  92593. * It must define where the camera used to render the texture was set
  92594. */
  92595. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  92596. if (!url) {
  92597. return _this;
  92598. }
  92599. _this.name = url;
  92600. _this.url = url;
  92601. _this.hasAlpha = false;
  92602. _this.isCube = true;
  92603. _this._textureMatrix = BABYLON.Matrix.Identity();
  92604. _this._onLoad = onLoad;
  92605. _this._onError = onError;
  92606. _this.gammaSpace = gammaSpace;
  92607. _this._noMipmap = noMipmap;
  92608. _this._size = size;
  92609. _this._texture = _this._getFromCache(url, _this._noMipmap);
  92610. if (!_this._texture) {
  92611. if (!scene.useDelayedTextureLoading) {
  92612. _this.loadTexture();
  92613. }
  92614. else {
  92615. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  92616. }
  92617. }
  92618. return _this;
  92619. }
  92620. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  92621. /**
  92622. * Gets wether or not the texture is blocking during loading.
  92623. */
  92624. get: function () {
  92625. return this._isBlocking;
  92626. },
  92627. /**
  92628. * Sets wether or not the texture is blocking during loading.
  92629. */
  92630. set: function (value) {
  92631. this._isBlocking = value;
  92632. },
  92633. enumerable: true,
  92634. configurable: true
  92635. });
  92636. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  92637. /**
  92638. * Gets texture matrix rotation angle around Y axis radians.
  92639. */
  92640. get: function () {
  92641. return this._rotationY;
  92642. },
  92643. /**
  92644. * Sets texture matrix rotation angle around Y axis in radians.
  92645. */
  92646. set: function (value) {
  92647. this._rotationY = value;
  92648. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  92649. },
  92650. enumerable: true,
  92651. configurable: true
  92652. });
  92653. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  92654. get: function () {
  92655. return this._boundingBoxSize;
  92656. },
  92657. /**
  92658. * Gets or sets the size of the bounding box associated with the cube texture
  92659. * When defined, the cubemap will switch to local mode
  92660. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  92661. * @example https://www.babylonjs-playground.com/#RNASML
  92662. */
  92663. set: function (value) {
  92664. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  92665. return;
  92666. }
  92667. this._boundingBoxSize = value;
  92668. var scene = this.getScene();
  92669. if (scene) {
  92670. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  92671. }
  92672. },
  92673. enumerable: true,
  92674. configurable: true
  92675. });
  92676. /**
  92677. * Occurs when the file is raw .hdr file.
  92678. */
  92679. HDRCubeTexture.prototype.loadTexture = function () {
  92680. var _this = this;
  92681. var callback = function (buffer) {
  92682. _this.lodGenerationOffset = 0.0;
  92683. _this.lodGenerationScale = 0.8;
  92684. var scene = _this.getScene();
  92685. if (!scene) {
  92686. return null;
  92687. }
  92688. // Extract the raw linear data.
  92689. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  92690. // Generate harmonics if needed.
  92691. if (_this._generateHarmonics) {
  92692. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  92693. _this.sphericalPolynomial = sphericalPolynomial;
  92694. }
  92695. var results = [];
  92696. var byteArray = null;
  92697. // Push each faces.
  92698. for (var j = 0; j < 6; j++) {
  92699. // Create uintarray fallback.
  92700. if (!scene.getEngine().getCaps().textureFloat) {
  92701. // 3 channels of 1 bytes per pixel in bytes.
  92702. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  92703. byteArray = new Uint8Array(byteBuffer);
  92704. }
  92705. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  92706. // If special cases.
  92707. if (_this.gammaSpace || byteArray) {
  92708. for (var i = 0; i < _this._size * _this._size; i++) {
  92709. // Put in gamma space if requested.
  92710. if (_this.gammaSpace) {
  92711. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  92712. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  92713. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  92714. }
  92715. // Convert to int texture for fallback.
  92716. if (byteArray) {
  92717. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  92718. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  92719. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  92720. // May use luminance instead if the result is not accurate.
  92721. var max = Math.max(Math.max(r, g), b);
  92722. if (max > 255) {
  92723. var scale = 255 / max;
  92724. r *= scale;
  92725. g *= scale;
  92726. b *= scale;
  92727. }
  92728. byteArray[(i * 3) + 0] = r;
  92729. byteArray[(i * 3) + 1] = g;
  92730. byteArray[(i * 3) + 2] = b;
  92731. }
  92732. }
  92733. }
  92734. if (byteArray) {
  92735. results.push(byteArray);
  92736. }
  92737. else {
  92738. results.push(dataFace);
  92739. }
  92740. }
  92741. return results;
  92742. };
  92743. var scene = this.getScene();
  92744. if (scene) {
  92745. 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);
  92746. }
  92747. };
  92748. HDRCubeTexture.prototype.clone = function () {
  92749. var scene = this.getScene();
  92750. if (!scene) {
  92751. return this;
  92752. }
  92753. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  92754. // Base texture
  92755. newTexture.level = this.level;
  92756. newTexture.wrapU = this.wrapU;
  92757. newTexture.wrapV = this.wrapV;
  92758. newTexture.coordinatesIndex = this.coordinatesIndex;
  92759. newTexture.coordinatesMode = this.coordinatesMode;
  92760. return newTexture;
  92761. };
  92762. // Methods
  92763. HDRCubeTexture.prototype.delayLoad = function () {
  92764. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  92765. return;
  92766. }
  92767. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  92768. this._texture = this._getFromCache(this.url, this._noMipmap);
  92769. if (!this._texture) {
  92770. this.loadTexture();
  92771. }
  92772. };
  92773. /**
  92774. * Get the texture reflection matrix used to rotate/transform the reflection.
  92775. * @returns the reflection matrix
  92776. */
  92777. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  92778. return this._textureMatrix;
  92779. };
  92780. /**
  92781. * Set the texture reflection matrix used to rotate/transform the reflection.
  92782. * @param value Define the reflection matrix to set
  92783. */
  92784. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  92785. this._textureMatrix = value;
  92786. };
  92787. /**
  92788. * Parses a JSON representation of an HDR Texture in order to create the texture
  92789. * @param parsedTexture Define the JSON representation
  92790. * @param scene Define the scene the texture should be created in
  92791. * @param rootUrl Define the root url in case we need to load relative dependencies
  92792. * @returns the newly created texture after parsing
  92793. */
  92794. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  92795. var texture = null;
  92796. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  92797. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  92798. texture.name = parsedTexture.name;
  92799. texture.hasAlpha = parsedTexture.hasAlpha;
  92800. texture.level = parsedTexture.level;
  92801. texture.coordinatesMode = parsedTexture.coordinatesMode;
  92802. texture.isBlocking = parsedTexture.isBlocking;
  92803. }
  92804. if (texture) {
  92805. if (parsedTexture.boundingBoxPosition) {
  92806. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  92807. }
  92808. if (parsedTexture.boundingBoxSize) {
  92809. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  92810. }
  92811. if (parsedTexture.rotationY) {
  92812. texture.rotationY = parsedTexture.rotationY;
  92813. }
  92814. }
  92815. return texture;
  92816. };
  92817. HDRCubeTexture.prototype.serialize = function () {
  92818. if (!this.name) {
  92819. return null;
  92820. }
  92821. var serializationObject = {};
  92822. serializationObject.name = this.name;
  92823. serializationObject.hasAlpha = this.hasAlpha;
  92824. serializationObject.isCube = true;
  92825. serializationObject.level = this.level;
  92826. serializationObject.size = this._size;
  92827. serializationObject.coordinatesMode = this.coordinatesMode;
  92828. serializationObject.useInGammaSpace = this.gammaSpace;
  92829. serializationObject.generateHarmonics = this._generateHarmonics;
  92830. serializationObject.customType = "BABYLON.HDRCubeTexture";
  92831. serializationObject.noMipmap = this._noMipmap;
  92832. serializationObject.isBlocking = this._isBlocking;
  92833. serializationObject.rotationY = this._rotationY;
  92834. return serializationObject;
  92835. };
  92836. HDRCubeTexture._facesMapping = [
  92837. "right",
  92838. "left",
  92839. "up",
  92840. "down",
  92841. "front",
  92842. "back"
  92843. ];
  92844. return HDRCubeTexture;
  92845. }(BABYLON.BaseTexture));
  92846. BABYLON.HDRCubeTexture = HDRCubeTexture;
  92847. })(BABYLON || (BABYLON = {}));
  92848. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  92849. var BABYLON;
  92850. (function (BABYLON) {
  92851. /**
  92852. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  92853. */
  92854. var PanoramaToCubeMapTools = /** @class */ (function () {
  92855. function PanoramaToCubeMapTools() {
  92856. }
  92857. /**
  92858. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  92859. *
  92860. * @param float32Array The source data.
  92861. * @param inputWidth The width of the input panorama.
  92862. * @param inputHeight The height of the input panorama.
  92863. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  92864. * @return The cubemap data
  92865. */
  92866. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  92867. if (!float32Array) {
  92868. throw "ConvertPanoramaToCubemap: input cannot be null";
  92869. }
  92870. if (float32Array.length != inputWidth * inputHeight * 3) {
  92871. throw "ConvertPanoramaToCubemap: input size is wrong";
  92872. }
  92873. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  92874. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  92875. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  92876. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  92877. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  92878. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  92879. return {
  92880. front: textureFront,
  92881. back: textureBack,
  92882. left: textureLeft,
  92883. right: textureRight,
  92884. up: textureUp,
  92885. down: textureDown,
  92886. size: size,
  92887. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  92888. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  92889. gammaSpace: false,
  92890. };
  92891. };
  92892. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  92893. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  92894. var textureArray = new Float32Array(buffer);
  92895. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  92896. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  92897. var dy = 1 / texSize;
  92898. var fy = 0;
  92899. for (var y = 0; y < texSize; y++) {
  92900. var xv1 = faceData[0];
  92901. var xv2 = faceData[2];
  92902. for (var x = 0; x < texSize; x++) {
  92903. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  92904. v.normalize();
  92905. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  92906. // 3 channels per pixels
  92907. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  92908. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  92909. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  92910. xv1 = xv1.add(rotDX1);
  92911. xv2 = xv2.add(rotDX2);
  92912. }
  92913. fy += dy;
  92914. }
  92915. return textureArray;
  92916. };
  92917. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  92918. var theta = Math.atan2(vDir.z, vDir.x);
  92919. var phi = Math.acos(vDir.y);
  92920. while (theta < -Math.PI) {
  92921. theta += 2 * Math.PI;
  92922. }
  92923. while (theta > Math.PI) {
  92924. theta -= 2 * Math.PI;
  92925. }
  92926. var dx = theta / Math.PI;
  92927. var dy = phi / Math.PI;
  92928. // recenter.
  92929. dx = dx * 0.5 + 0.5;
  92930. var px = Math.round(dx * inputWidth);
  92931. if (px < 0) {
  92932. px = 0;
  92933. }
  92934. else if (px >= inputWidth) {
  92935. px = inputWidth - 1;
  92936. }
  92937. var py = Math.round(dy * inputHeight);
  92938. if (py < 0) {
  92939. py = 0;
  92940. }
  92941. else if (py >= inputHeight) {
  92942. py = inputHeight - 1;
  92943. }
  92944. var inputY = (inputHeight - py - 1);
  92945. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  92946. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  92947. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  92948. return {
  92949. r: r,
  92950. g: g,
  92951. b: b
  92952. };
  92953. };
  92954. PanoramaToCubeMapTools.FACE_FRONT = [
  92955. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  92956. new BABYLON.Vector3(1.0, -1.0, -1.0),
  92957. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  92958. new BABYLON.Vector3(1.0, 1.0, -1.0)
  92959. ];
  92960. PanoramaToCubeMapTools.FACE_BACK = [
  92961. new BABYLON.Vector3(1.0, -1.0, 1.0),
  92962. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  92963. new BABYLON.Vector3(1.0, 1.0, 1.0),
  92964. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  92965. ];
  92966. PanoramaToCubeMapTools.FACE_RIGHT = [
  92967. new BABYLON.Vector3(1.0, -1.0, -1.0),
  92968. new BABYLON.Vector3(1.0, -1.0, 1.0),
  92969. new BABYLON.Vector3(1.0, 1.0, -1.0),
  92970. new BABYLON.Vector3(1.0, 1.0, 1.0)
  92971. ];
  92972. PanoramaToCubeMapTools.FACE_LEFT = [
  92973. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  92974. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  92975. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  92976. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  92977. ];
  92978. PanoramaToCubeMapTools.FACE_DOWN = [
  92979. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  92980. new BABYLON.Vector3(1.0, 1.0, -1.0),
  92981. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  92982. new BABYLON.Vector3(1.0, 1.0, 1.0)
  92983. ];
  92984. PanoramaToCubeMapTools.FACE_UP = [
  92985. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  92986. new BABYLON.Vector3(1.0, -1.0, 1.0),
  92987. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  92988. new BABYLON.Vector3(1.0, -1.0, -1.0)
  92989. ];
  92990. return PanoramaToCubeMapTools;
  92991. }());
  92992. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  92993. })(BABYLON || (BABYLON = {}));
  92994. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  92995. var BABYLON;
  92996. (function (BABYLON) {
  92997. /**
  92998. * Vector2 wth index property
  92999. */
  93000. var IndexedVector2 = /** @class */ (function (_super) {
  93001. __extends(IndexedVector2, _super);
  93002. function IndexedVector2(original,
  93003. /** Index of the vector2 */
  93004. index) {
  93005. var _this = _super.call(this, original.x, original.y) || this;
  93006. _this.index = index;
  93007. return _this;
  93008. }
  93009. return IndexedVector2;
  93010. }(BABYLON.Vector2));
  93011. /**
  93012. * Defines points to create a polygon
  93013. */
  93014. var PolygonPoints = /** @class */ (function () {
  93015. function PolygonPoints() {
  93016. this.elements = new Array();
  93017. }
  93018. PolygonPoints.prototype.add = function (originalPoints) {
  93019. var _this = this;
  93020. var result = new Array();
  93021. originalPoints.forEach(function (point) {
  93022. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  93023. var newPoint = new IndexedVector2(point, _this.elements.length);
  93024. result.push(newPoint);
  93025. _this.elements.push(newPoint);
  93026. }
  93027. });
  93028. return result;
  93029. };
  93030. PolygonPoints.prototype.computeBounds = function () {
  93031. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  93032. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  93033. this.elements.forEach(function (point) {
  93034. // x
  93035. if (point.x < lmin.x) {
  93036. lmin.x = point.x;
  93037. }
  93038. else if (point.x > lmax.x) {
  93039. lmax.x = point.x;
  93040. }
  93041. // y
  93042. if (point.y < lmin.y) {
  93043. lmin.y = point.y;
  93044. }
  93045. else if (point.y > lmax.y) {
  93046. lmax.y = point.y;
  93047. }
  93048. });
  93049. return {
  93050. min: lmin,
  93051. max: lmax,
  93052. width: lmax.x - lmin.x,
  93053. height: lmax.y - lmin.y
  93054. };
  93055. };
  93056. return PolygonPoints;
  93057. }());
  93058. /**
  93059. * Polygon
  93060. * @see https://doc.babylonjs.com/how_to/parametric_shapes#non-regular-polygon
  93061. */
  93062. var Polygon = /** @class */ (function () {
  93063. function Polygon() {
  93064. }
  93065. /**
  93066. * Creates a rectangle
  93067. * @param xmin bottom X coord
  93068. * @param ymin bottom Y coord
  93069. * @param xmax top X coord
  93070. * @param ymax top Y coord
  93071. * @returns points that make the resulting rectation
  93072. */
  93073. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  93074. return [
  93075. new BABYLON.Vector2(xmin, ymin),
  93076. new BABYLON.Vector2(xmax, ymin),
  93077. new BABYLON.Vector2(xmax, ymax),
  93078. new BABYLON.Vector2(xmin, ymax)
  93079. ];
  93080. };
  93081. /**
  93082. * Creates a circle
  93083. * @param radius radius of circle
  93084. * @param cx scale in x
  93085. * @param cy scale in y
  93086. * @param numberOfSides number of sides that make up the circle
  93087. * @returns points that make the resulting circle
  93088. */
  93089. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  93090. if (cx === void 0) { cx = 0; }
  93091. if (cy === void 0) { cy = 0; }
  93092. if (numberOfSides === void 0) { numberOfSides = 32; }
  93093. var result = new Array();
  93094. var angle = 0;
  93095. var increment = (Math.PI * 2) / numberOfSides;
  93096. for (var i = 0; i < numberOfSides; i++) {
  93097. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  93098. angle -= increment;
  93099. }
  93100. return result;
  93101. };
  93102. /**
  93103. * Creates a polygon from input string
  93104. * @param input Input polygon data
  93105. * @returns the parsed points
  93106. */
  93107. Polygon.Parse = function (input) {
  93108. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  93109. var i, result = [];
  93110. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  93111. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  93112. }
  93113. return result;
  93114. };
  93115. /**
  93116. * Starts building a polygon from x and y coordinates
  93117. * @param x x coordinate
  93118. * @param y y coordinate
  93119. * @returns the started path2
  93120. */
  93121. Polygon.StartingAt = function (x, y) {
  93122. return BABYLON.Path2.StartingAt(x, y);
  93123. };
  93124. return Polygon;
  93125. }());
  93126. BABYLON.Polygon = Polygon;
  93127. /**
  93128. * Builds a polygon
  93129. * @see https://doc.babylonjs.com/how_to/polygonmeshbuilder
  93130. */
  93131. var PolygonMeshBuilder = /** @class */ (function () {
  93132. /**
  93133. * Creates a PolygonMeshBuilder
  93134. * @param name name of the builder
  93135. * @param contours Path of the polygon
  93136. * @param scene scene to add to
  93137. */
  93138. function PolygonMeshBuilder(name, contours, scene) {
  93139. this._points = new PolygonPoints();
  93140. this._outlinepoints = new PolygonPoints();
  93141. this._holes = new Array();
  93142. this._epoints = new Array();
  93143. this._eholes = new Array();
  93144. this._name = name;
  93145. this._scene = scene;
  93146. var points;
  93147. if (contours instanceof BABYLON.Path2) {
  93148. points = contours.getPoints();
  93149. }
  93150. else {
  93151. points = contours;
  93152. }
  93153. this._addToepoint(points);
  93154. this._points.add(points);
  93155. this._outlinepoints.add(points);
  93156. if (typeof earcut === 'undefined') {
  93157. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  93158. }
  93159. }
  93160. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  93161. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  93162. var p = points_1[_i];
  93163. this._epoints.push(p.x, p.y);
  93164. }
  93165. };
  93166. /**
  93167. * Adds a whole within the polygon
  93168. * @param hole Array of points defining the hole
  93169. * @returns this
  93170. */
  93171. PolygonMeshBuilder.prototype.addHole = function (hole) {
  93172. this._points.add(hole);
  93173. var holepoints = new PolygonPoints();
  93174. holepoints.add(hole);
  93175. this._holes.push(holepoints);
  93176. this._eholes.push(this._epoints.length / 2);
  93177. this._addToepoint(hole);
  93178. return this;
  93179. };
  93180. /**
  93181. * Creates the polygon
  93182. * @param updatable If the mesh should be updatable
  93183. * @param depth The depth of the mesh created
  93184. * @returns the created mesh
  93185. */
  93186. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  93187. var _this = this;
  93188. if (updatable === void 0) { updatable = false; }
  93189. if (depth === void 0) { depth = 0; }
  93190. var result = new BABYLON.Mesh(this._name, this._scene);
  93191. var normals = new Array();
  93192. var positions = new Array();
  93193. var uvs = new Array();
  93194. var bounds = this._points.computeBounds();
  93195. this._points.elements.forEach(function (p) {
  93196. normals.push(0, 1.0, 0);
  93197. positions.push(p.x, 0, p.y);
  93198. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  93199. });
  93200. var indices = new Array();
  93201. var res = earcut(this._epoints, this._eholes, 2);
  93202. for (var i = 0; i < res.length; i++) {
  93203. indices.push(res[i]);
  93204. }
  93205. if (depth > 0) {
  93206. var positionscount = (positions.length / 3); //get the current pointcount
  93207. this._points.elements.forEach(function (p) {
  93208. normals.push(0, -1.0, 0);
  93209. positions.push(p.x, -depth, p.y);
  93210. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  93211. });
  93212. var totalCount = indices.length;
  93213. for (var i = 0; i < totalCount; i += 3) {
  93214. var i0 = indices[i + 0];
  93215. var i1 = indices[i + 1];
  93216. var i2 = indices[i + 2];
  93217. indices.push(i2 + positionscount);
  93218. indices.push(i1 + positionscount);
  93219. indices.push(i0 + positionscount);
  93220. }
  93221. //Add the sides
  93222. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  93223. this._holes.forEach(function (hole) {
  93224. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  93225. });
  93226. }
  93227. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  93228. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  93229. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  93230. result.setIndices(indices);
  93231. return result;
  93232. };
  93233. /**
  93234. * Adds a side to the polygon
  93235. * @param positions points that make the polygon
  93236. * @param normals normals of the polygon
  93237. * @param uvs uvs of the polygon
  93238. * @param indices indices of the polygon
  93239. * @param bounds bounds of the polygon
  93240. * @param points points of the polygon
  93241. * @param depth depth of the polygon
  93242. * @param flip flip of the polygon
  93243. */
  93244. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  93245. var StartIndex = positions.length / 3;
  93246. var ulength = 0;
  93247. for (var i = 0; i < points.elements.length; i++) {
  93248. var p = points.elements[i];
  93249. var p1;
  93250. if ((i + 1) > points.elements.length - 1) {
  93251. p1 = points.elements[0];
  93252. }
  93253. else {
  93254. p1 = points.elements[i + 1];
  93255. }
  93256. positions.push(p.x, 0, p.y);
  93257. positions.push(p.x, -depth, p.y);
  93258. positions.push(p1.x, 0, p1.y);
  93259. positions.push(p1.x, -depth, p1.y);
  93260. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  93261. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  93262. var v3 = v2.subtract(v1);
  93263. var v4 = new BABYLON.Vector3(0, 1, 0);
  93264. var vn = BABYLON.Vector3.Cross(v3, v4);
  93265. vn = vn.normalize();
  93266. uvs.push(ulength / bounds.width, 0);
  93267. uvs.push(ulength / bounds.width, 1);
  93268. ulength += v3.length();
  93269. uvs.push((ulength / bounds.width), 0);
  93270. uvs.push((ulength / bounds.width), 1);
  93271. if (!flip) {
  93272. normals.push(-vn.x, -vn.y, -vn.z);
  93273. normals.push(-vn.x, -vn.y, -vn.z);
  93274. normals.push(-vn.x, -vn.y, -vn.z);
  93275. normals.push(-vn.x, -vn.y, -vn.z);
  93276. indices.push(StartIndex);
  93277. indices.push(StartIndex + 1);
  93278. indices.push(StartIndex + 2);
  93279. indices.push(StartIndex + 1);
  93280. indices.push(StartIndex + 3);
  93281. indices.push(StartIndex + 2);
  93282. }
  93283. else {
  93284. normals.push(vn.x, vn.y, vn.z);
  93285. normals.push(vn.x, vn.y, vn.z);
  93286. normals.push(vn.x, vn.y, vn.z);
  93287. normals.push(vn.x, vn.y, vn.z);
  93288. indices.push(StartIndex);
  93289. indices.push(StartIndex + 2);
  93290. indices.push(StartIndex + 1);
  93291. indices.push(StartIndex + 1);
  93292. indices.push(StartIndex + 2);
  93293. indices.push(StartIndex + 3);
  93294. }
  93295. StartIndex += 4;
  93296. }
  93297. };
  93298. return PolygonMeshBuilder;
  93299. }());
  93300. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  93301. })(BABYLON || (BABYLON = {}));
  93302. //# sourceMappingURL=babylon.polygonMesh.js.map
  93303. var BABYLON;
  93304. (function (BABYLON) {
  93305. /**
  93306. * Unique ID when we import meshes from Babylon to CSG
  93307. */
  93308. var currentCSGMeshId = 0;
  93309. /**
  93310. * Represents a vertex of a polygon. Use your own vertex class instead of this
  93311. * one to provide additional features like texture coordinates and vertex
  93312. * colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  93313. * `flip()`, and `interpolate()` methods that behave analogous to the ones
  93314. * defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  93315. * functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  93316. * is not used anywhere else.
  93317. * Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  93318. */
  93319. var Vertex = /** @class */ (function () {
  93320. /**
  93321. * Initializes the vertex
  93322. * @param pos The position of the vertex
  93323. * @param normal The normal of the vertex
  93324. * @param uv The texture coordinate of the vertex
  93325. */
  93326. function Vertex(
  93327. /**
  93328. * The position of the vertex
  93329. */
  93330. pos,
  93331. /**
  93332. * The normal of the vertex
  93333. */
  93334. normal,
  93335. /**
  93336. * The texture coordinate of the vertex
  93337. */
  93338. uv) {
  93339. this.pos = pos;
  93340. this.normal = normal;
  93341. this.uv = uv;
  93342. }
  93343. /**
  93344. * Make a clone, or deep copy, of the vertex
  93345. * @returns A new Vertex
  93346. */
  93347. Vertex.prototype.clone = function () {
  93348. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  93349. };
  93350. /**
  93351. * Invert all orientation-specific data (e.g. vertex normal). Called when the
  93352. * orientation of a polygon is flipped.
  93353. */
  93354. Vertex.prototype.flip = function () {
  93355. this.normal = this.normal.scale(-1);
  93356. };
  93357. /**
  93358. * Create a new vertex between this vertex and `other` by linearly
  93359. * interpolating all properties using a parameter of `t`. Subclasses should
  93360. * override this to interpolate additional properties.
  93361. * @param other the vertex to interpolate against
  93362. * @param t The factor used to linearly interpolate between the vertices
  93363. */
  93364. Vertex.prototype.interpolate = function (other, t) {
  93365. 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));
  93366. };
  93367. return Vertex;
  93368. }());
  93369. /**
  93370. * Represents a plane in 3D space.
  93371. */
  93372. var Plane = /** @class */ (function () {
  93373. /**
  93374. * Initializes the plane
  93375. * @param normal The normal for the plane
  93376. * @param w
  93377. */
  93378. function Plane(normal, w) {
  93379. this.normal = normal;
  93380. this.w = w;
  93381. }
  93382. /**
  93383. * Construct a plane from three points
  93384. * @param a Point a
  93385. * @param b Point b
  93386. * @param c Point c
  93387. */
  93388. Plane.FromPoints = function (a, b, c) {
  93389. var v0 = c.subtract(a);
  93390. var v1 = b.subtract(a);
  93391. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  93392. return null;
  93393. }
  93394. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  93395. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  93396. };
  93397. /**
  93398. * Clone, or make a deep copy of the plane
  93399. * @returns a new Plane
  93400. */
  93401. Plane.prototype.clone = function () {
  93402. return new Plane(this.normal.clone(), this.w);
  93403. };
  93404. /**
  93405. * Flip the face of the plane
  93406. */
  93407. Plane.prototype.flip = function () {
  93408. this.normal.scaleInPlace(-1);
  93409. this.w = -this.w;
  93410. };
  93411. /**
  93412. * Split `polygon` by this plane if needed, then put the polygon or polygon
  93413. * fragments in the appropriate lists. Coplanar polygons go into either
  93414. `* coplanarFront` or `coplanarBack` depending on their orientation with
  93415. * respect to this plane. Polygons in front or in back of this plane go into
  93416. * either `front` or `back`
  93417. * @param polygon The polygon to be split
  93418. * @param coplanarFront Will contain polygons coplanar with the plane that are oriented to the front of the plane
  93419. * @param coplanarBack Will contain polygons coplanar with the plane that are oriented to the back of the plane
  93420. * @param front Will contain the polygons in front of the plane
  93421. * @param back Will contain the polygons begind the plane
  93422. */
  93423. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  93424. var COPLANAR = 0;
  93425. var FRONT = 1;
  93426. var BACK = 2;
  93427. var SPANNING = 3;
  93428. // Classify each point as well as the entire polygon into one of the above
  93429. // four classes.
  93430. var polygonType = 0;
  93431. var types = [];
  93432. var i;
  93433. var t;
  93434. for (i = 0; i < polygon.vertices.length; i++) {
  93435. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  93436. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  93437. polygonType |= type;
  93438. types.push(type);
  93439. }
  93440. // Put the polygon in the correct list, splitting it when necessary
  93441. switch (polygonType) {
  93442. case COPLANAR:
  93443. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  93444. break;
  93445. case FRONT:
  93446. front.push(polygon);
  93447. break;
  93448. case BACK:
  93449. back.push(polygon);
  93450. break;
  93451. case SPANNING:
  93452. var f = [], b = [];
  93453. for (i = 0; i < polygon.vertices.length; i++) {
  93454. var j = (i + 1) % polygon.vertices.length;
  93455. var ti = types[i], tj = types[j];
  93456. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  93457. if (ti !== BACK) {
  93458. f.push(vi);
  93459. }
  93460. if (ti !== FRONT) {
  93461. b.push(ti !== BACK ? vi.clone() : vi);
  93462. }
  93463. if ((ti | tj) === SPANNING) {
  93464. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  93465. var v = vi.interpolate(vj, t);
  93466. f.push(v);
  93467. b.push(v.clone());
  93468. }
  93469. }
  93470. var poly;
  93471. if (f.length >= 3) {
  93472. poly = new Polygon(f, polygon.shared);
  93473. if (poly.plane) {
  93474. front.push(poly);
  93475. }
  93476. }
  93477. if (b.length >= 3) {
  93478. poly = new Polygon(b, polygon.shared);
  93479. if (poly.plane) {
  93480. back.push(poly);
  93481. }
  93482. }
  93483. break;
  93484. }
  93485. };
  93486. /**
  93487. * `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  93488. * point is on the plane
  93489. */
  93490. Plane.EPSILON = 1e-5;
  93491. return Plane;
  93492. }());
  93493. /**
  93494. * Represents a convex polygon. The vertices used to initialize a polygon must
  93495. * be coplanar and form a convex loop.
  93496. *
  93497. * Each convex polygon has a `shared` property, which is shared between all
  93498. * polygons that are clones of each other or were split from the same polygon.
  93499. * This can be used to define per-polygon properties (such as surface color)
  93500. */
  93501. var Polygon = /** @class */ (function () {
  93502. /**
  93503. * Initializes the polygon
  93504. * @param vertices The vertices of the polygon
  93505. * @param shared The properties shared across all polygons
  93506. */
  93507. function Polygon(vertices, shared) {
  93508. this.vertices = vertices;
  93509. this.shared = shared;
  93510. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  93511. }
  93512. /**
  93513. * Clones, or makes a deep copy, or the polygon
  93514. */
  93515. Polygon.prototype.clone = function () {
  93516. var vertices = this.vertices.map(function (v) { return v.clone(); });
  93517. return new Polygon(vertices, this.shared);
  93518. };
  93519. /**
  93520. * Flips the faces of the polygon
  93521. */
  93522. Polygon.prototype.flip = function () {
  93523. this.vertices.reverse().map(function (v) { v.flip(); });
  93524. this.plane.flip();
  93525. };
  93526. return Polygon;
  93527. }());
  93528. /**
  93529. * Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  93530. * by picking a polygon to split along. That polygon (and all other coplanar
  93531. * polygons) are added directly to that node and the other polygons are added to
  93532. * the front and/or back subtrees. This is not a leafy BSP tree since there is
  93533. * no distinction between internal and leaf nodes
  93534. */
  93535. var Node = /** @class */ (function () {
  93536. /**
  93537. * Initializes the node
  93538. * @param polygons A collection of polygons held in the node
  93539. */
  93540. function Node(polygons) {
  93541. this.plane = null;
  93542. this.front = null;
  93543. this.back = null;
  93544. this.polygons = new Array();
  93545. if (polygons) {
  93546. this.build(polygons);
  93547. }
  93548. }
  93549. /**
  93550. * Clones, or makes a deep copy, of the node
  93551. * @returns The cloned node
  93552. */
  93553. Node.prototype.clone = function () {
  93554. var node = new Node();
  93555. node.plane = this.plane && this.plane.clone();
  93556. node.front = this.front && this.front.clone();
  93557. node.back = this.back && this.back.clone();
  93558. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  93559. return node;
  93560. };
  93561. /**
  93562. * Convert solid space to empty space and empty space to solid space
  93563. */
  93564. Node.prototype.invert = function () {
  93565. for (var i = 0; i < this.polygons.length; i++) {
  93566. this.polygons[i].flip();
  93567. }
  93568. if (this.plane) {
  93569. this.plane.flip();
  93570. }
  93571. if (this.front) {
  93572. this.front.invert();
  93573. }
  93574. if (this.back) {
  93575. this.back.invert();
  93576. }
  93577. var temp = this.front;
  93578. this.front = this.back;
  93579. this.back = temp;
  93580. };
  93581. /**
  93582. * Recursively remove all polygons in `polygons` that are inside this BSP
  93583. * tree.
  93584. * @param polygons Polygons to remove from the BSP
  93585. * @returns Polygons clipped from the BSP
  93586. */
  93587. Node.prototype.clipPolygons = function (polygons) {
  93588. if (!this.plane) {
  93589. return polygons.slice();
  93590. }
  93591. var front = new Array(), back = new Array();
  93592. for (var i = 0; i < polygons.length; i++) {
  93593. this.plane.splitPolygon(polygons[i], front, back, front, back);
  93594. }
  93595. if (this.front) {
  93596. front = this.front.clipPolygons(front);
  93597. }
  93598. if (this.back) {
  93599. back = this.back.clipPolygons(back);
  93600. }
  93601. else {
  93602. back = [];
  93603. }
  93604. return front.concat(back);
  93605. };
  93606. /**
  93607. * Remove all polygons in this BSP tree that are inside the other BSP tree
  93608. * `bsp`.
  93609. * @param bsp BSP containing polygons to remove from this BSP
  93610. */
  93611. Node.prototype.clipTo = function (bsp) {
  93612. this.polygons = bsp.clipPolygons(this.polygons);
  93613. if (this.front) {
  93614. this.front.clipTo(bsp);
  93615. }
  93616. if (this.back) {
  93617. this.back.clipTo(bsp);
  93618. }
  93619. };
  93620. /**
  93621. * Return a list of all polygons in this BSP tree
  93622. * @returns List of all polygons in this BSP tree
  93623. */
  93624. Node.prototype.allPolygons = function () {
  93625. var polygons = this.polygons.slice();
  93626. if (this.front) {
  93627. polygons = polygons.concat(this.front.allPolygons());
  93628. }
  93629. if (this.back) {
  93630. polygons = polygons.concat(this.back.allPolygons());
  93631. }
  93632. return polygons;
  93633. };
  93634. /**
  93635. * Build a BSP tree out of `polygons`. When called on an existing tree, the
  93636. * new polygons are filtered down to the bottom of the tree and become new
  93637. * nodes there. Each set of polygons is partitioned using the first polygon
  93638. * (no heuristic is used to pick a good split)
  93639. * @param polygons Polygons used to construct the BSP tree
  93640. */
  93641. Node.prototype.build = function (polygons) {
  93642. if (!polygons.length) {
  93643. return;
  93644. }
  93645. if (!this.plane) {
  93646. this.plane = polygons[0].plane.clone();
  93647. }
  93648. var front = new Array(), back = new Array();
  93649. for (var i = 0; i < polygons.length; i++) {
  93650. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  93651. }
  93652. if (front.length) {
  93653. if (!this.front) {
  93654. this.front = new Node();
  93655. }
  93656. this.front.build(front);
  93657. }
  93658. if (back.length) {
  93659. if (!this.back) {
  93660. this.back = new Node();
  93661. }
  93662. this.back.build(back);
  93663. }
  93664. };
  93665. return Node;
  93666. }());
  93667. /**
  93668. * Class for building Constructive Solid Geometry
  93669. */
  93670. var CSG = /** @class */ (function () {
  93671. function CSG() {
  93672. this.polygons = new Array();
  93673. }
  93674. /**
  93675. * Convert the BABYLON.Mesh to BABYLON.CSG
  93676. * @param mesh The BABYLON.Mesh to convert to BABYLON.CSG
  93677. * @returns A new BABYLON.CSG from the BABYLON.Mesh
  93678. */
  93679. CSG.FromMesh = function (mesh) {
  93680. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  93681. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  93682. if (mesh instanceof BABYLON.Mesh) {
  93683. mesh.computeWorldMatrix(true);
  93684. matrix = mesh.getWorldMatrix();
  93685. meshPosition = mesh.position.clone();
  93686. meshRotation = mesh.rotation.clone();
  93687. if (mesh.rotationQuaternion) {
  93688. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  93689. }
  93690. meshScaling = mesh.scaling.clone();
  93691. }
  93692. else {
  93693. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  93694. }
  93695. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  93696. var subMeshes = mesh.subMeshes;
  93697. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  93698. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  93699. vertices = [];
  93700. for (var j = 0; j < 3; j++) {
  93701. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  93702. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  93703. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  93704. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  93705. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  93706. vertex = new Vertex(position, normal, uv);
  93707. vertices.push(vertex);
  93708. }
  93709. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  93710. // To handle the case of degenerated triangle
  93711. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  93712. if (polygon.plane) {
  93713. polygons.push(polygon);
  93714. }
  93715. }
  93716. }
  93717. var csg = CSG.FromPolygons(polygons);
  93718. csg.matrix = matrix;
  93719. csg.position = meshPosition;
  93720. csg.rotation = meshRotation;
  93721. csg.scaling = meshScaling;
  93722. csg.rotationQuaternion = meshRotationQuaternion;
  93723. currentCSGMeshId++;
  93724. return csg;
  93725. };
  93726. /**
  93727. * Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  93728. * @param polygons Polygons used to construct a BABYLON.CSG solid
  93729. */
  93730. CSG.FromPolygons = function (polygons) {
  93731. var csg = new CSG();
  93732. csg.polygons = polygons;
  93733. return csg;
  93734. };
  93735. /**
  93736. * Clones, or makes a deep copy, of the BABYLON.CSG
  93737. * @returns A new BABYLON.CSG
  93738. */
  93739. CSG.prototype.clone = function () {
  93740. var csg = new CSG();
  93741. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  93742. csg.copyTransformAttributes(this);
  93743. return csg;
  93744. };
  93745. /**
  93746. * Unions this CSG with another CSG
  93747. * @param csg The CSG to union against this CSG
  93748. * @returns The unioned CSG
  93749. */
  93750. CSG.prototype.union = function (csg) {
  93751. var a = new Node(this.clone().polygons);
  93752. var b = new Node(csg.clone().polygons);
  93753. a.clipTo(b);
  93754. b.clipTo(a);
  93755. b.invert();
  93756. b.clipTo(a);
  93757. b.invert();
  93758. a.build(b.allPolygons());
  93759. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  93760. };
  93761. /**
  93762. * Unions this CSG with another CSG in place
  93763. * @param csg The CSG to union against this CSG
  93764. */
  93765. CSG.prototype.unionInPlace = function (csg) {
  93766. var a = new Node(this.polygons);
  93767. var b = new Node(csg.polygons);
  93768. a.clipTo(b);
  93769. b.clipTo(a);
  93770. b.invert();
  93771. b.clipTo(a);
  93772. b.invert();
  93773. a.build(b.allPolygons());
  93774. this.polygons = a.allPolygons();
  93775. };
  93776. /**
  93777. * Subtracts this CSG with another CSG
  93778. * @param csg The CSG to subtract against this CSG
  93779. * @returns A new BABYLON.CSG
  93780. */
  93781. CSG.prototype.subtract = function (csg) {
  93782. var a = new Node(this.clone().polygons);
  93783. var b = new Node(csg.clone().polygons);
  93784. a.invert();
  93785. a.clipTo(b);
  93786. b.clipTo(a);
  93787. b.invert();
  93788. b.clipTo(a);
  93789. b.invert();
  93790. a.build(b.allPolygons());
  93791. a.invert();
  93792. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  93793. };
  93794. /**
  93795. * Subtracts this CSG with another CSG in place
  93796. * @param csg The CSG to subtact against this CSG
  93797. */
  93798. CSG.prototype.subtractInPlace = function (csg) {
  93799. var a = new Node(this.polygons);
  93800. var b = new Node(csg.polygons);
  93801. a.invert();
  93802. a.clipTo(b);
  93803. b.clipTo(a);
  93804. b.invert();
  93805. b.clipTo(a);
  93806. b.invert();
  93807. a.build(b.allPolygons());
  93808. a.invert();
  93809. this.polygons = a.allPolygons();
  93810. };
  93811. /**
  93812. * Intersect this CSG with another CSG
  93813. * @param csg The CSG to intersect against this CSG
  93814. * @returns A new BABYLON.CSG
  93815. */
  93816. CSG.prototype.intersect = function (csg) {
  93817. var a = new Node(this.clone().polygons);
  93818. var b = new Node(csg.clone().polygons);
  93819. a.invert();
  93820. b.clipTo(a);
  93821. b.invert();
  93822. a.clipTo(b);
  93823. b.clipTo(a);
  93824. a.build(b.allPolygons());
  93825. a.invert();
  93826. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  93827. };
  93828. /**
  93829. * Intersects this CSG with another CSG in place
  93830. * @param csg The CSG to intersect against this CSG
  93831. */
  93832. CSG.prototype.intersectInPlace = function (csg) {
  93833. var a = new Node(this.polygons);
  93834. var b = new Node(csg.polygons);
  93835. a.invert();
  93836. b.clipTo(a);
  93837. b.invert();
  93838. a.clipTo(b);
  93839. b.clipTo(a);
  93840. a.build(b.allPolygons());
  93841. a.invert();
  93842. this.polygons = a.allPolygons();
  93843. };
  93844. /**
  93845. * Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  93846. * not modified.
  93847. * @returns A new BABYLON.CSG solid with solid and empty space switched
  93848. */
  93849. CSG.prototype.inverse = function () {
  93850. var csg = this.clone();
  93851. csg.inverseInPlace();
  93852. return csg;
  93853. };
  93854. /**
  93855. * Inverses the BABYLON.CSG in place
  93856. */
  93857. CSG.prototype.inverseInPlace = function () {
  93858. this.polygons.map(function (p) { p.flip(); });
  93859. };
  93860. /**
  93861. * This is used to keep meshes transformations so they can be restored
  93862. * when we build back a Babylon Mesh
  93863. * NB : All CSG operations are performed in world coordinates
  93864. * @param csg The BABYLON.CSG to copy the transform attributes from
  93865. * @returns This BABYLON.CSG
  93866. */
  93867. CSG.prototype.copyTransformAttributes = function (csg) {
  93868. this.matrix = csg.matrix;
  93869. this.position = csg.position;
  93870. this.rotation = csg.rotation;
  93871. this.scaling = csg.scaling;
  93872. this.rotationQuaternion = csg.rotationQuaternion;
  93873. return this;
  93874. };
  93875. /**
  93876. * Build Raw mesh from CSG
  93877. * Coordinates here are in world space
  93878. * @param name The name of the mesh geometry
  93879. * @param scene The BABYLON.Scene
  93880. * @param keepSubMeshes Specifies if the submeshes should be kept
  93881. * @returns A new BABYLON.Mesh
  93882. */
  93883. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  93884. var matrix = this.matrix.clone();
  93885. matrix.invert();
  93886. 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;
  93887. if (keepSubMeshes) {
  93888. // Sort Polygons, since subMeshes are indices range
  93889. polygons.sort(function (a, b) {
  93890. if (a.shared.meshId === b.shared.meshId) {
  93891. return a.shared.subMeshId - b.shared.subMeshId;
  93892. }
  93893. else {
  93894. return a.shared.meshId - b.shared.meshId;
  93895. }
  93896. });
  93897. }
  93898. for (var i = 0, il = polygons.length; i < il; i++) {
  93899. polygon = polygons[i];
  93900. // Building SubMeshes
  93901. if (!subMesh_dict[polygon.shared.meshId]) {
  93902. subMesh_dict[polygon.shared.meshId] = {};
  93903. }
  93904. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  93905. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  93906. indexStart: +Infinity,
  93907. indexEnd: -Infinity,
  93908. materialIndex: polygon.shared.materialIndex
  93909. };
  93910. }
  93911. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  93912. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  93913. polygonIndices[0] = 0;
  93914. polygonIndices[1] = j - 1;
  93915. polygonIndices[2] = j;
  93916. for (var k = 0; k < 3; k++) {
  93917. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  93918. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  93919. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  93920. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  93921. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  93922. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  93923. // Check if 2 points can be merged
  93924. if (!(typeof vertex_idx !== 'undefined' &&
  93925. normals[vertex_idx * 3] === localNormal.x &&
  93926. normals[vertex_idx * 3 + 1] === localNormal.y &&
  93927. normals[vertex_idx * 3 + 2] === localNormal.z &&
  93928. uvs[vertex_idx * 2] === uv.x &&
  93929. uvs[vertex_idx * 2 + 1] === uv.y)) {
  93930. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  93931. uvs.push(uv.x, uv.y);
  93932. normals.push(normal.x, normal.y, normal.z);
  93933. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  93934. }
  93935. indices.push(vertex_idx);
  93936. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  93937. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  93938. currentIndex++;
  93939. }
  93940. }
  93941. }
  93942. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  93943. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  93944. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  93945. mesh.setIndices(indices, null);
  93946. if (keepSubMeshes) {
  93947. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  93948. var materialIndexOffset = 0, materialMaxIndex;
  93949. mesh.subMeshes = new Array();
  93950. for (var m in subMesh_dict) {
  93951. materialMaxIndex = -1;
  93952. for (var sm in subMesh_dict[m]) {
  93953. subMesh_obj = subMesh_dict[m][sm];
  93954. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  93955. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  93956. }
  93957. materialIndexOffset += ++materialMaxIndex;
  93958. }
  93959. }
  93960. return mesh;
  93961. };
  93962. /**
  93963. * Build Mesh from CSG taking material and transforms into account
  93964. * @param name The name of the BABYLON.Mesh
  93965. * @param material The material of the BABYLON.Mesh
  93966. * @param scene The BABYLON.Scene
  93967. * @param keepSubMeshes Specifies if submeshes should be kept
  93968. * @returns The new BABYLON.Mesh
  93969. */
  93970. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  93971. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  93972. mesh.material = material;
  93973. mesh.position.copyFrom(this.position);
  93974. mesh.rotation.copyFrom(this.rotation);
  93975. if (this.rotationQuaternion) {
  93976. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  93977. }
  93978. mesh.scaling.copyFrom(this.scaling);
  93979. mesh.computeWorldMatrix(true);
  93980. return mesh;
  93981. };
  93982. return CSG;
  93983. }());
  93984. BABYLON.CSG = CSG;
  93985. })(BABYLON || (BABYLON = {}));
  93986. //# sourceMappingURL=babylon.csg.js.map
  93987. var BABYLON;
  93988. (function (BABYLON) {
  93989. /**
  93990. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  93991. * It controls one of the indiviual texture used in the effect.
  93992. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  93993. */
  93994. var LensFlare = /** @class */ (function () {
  93995. /**
  93996. * Instantiates a new Lens Flare.
  93997. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  93998. * It controls one of the indiviual texture used in the effect.
  93999. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  94000. * @param size Define the size of the lens flare in the system (a floating value between 0 and 1)
  94001. * @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.
  94002. * @param color Define the lens color
  94003. * @param imgUrl Define the lens texture url
  94004. * @param system Define the `lensFlareSystem` this flare is part of
  94005. */
  94006. function LensFlare(
  94007. /**
  94008. * Define the size of the lens flare in the system (a floating value between 0 and 1)
  94009. */
  94010. size,
  94011. /**
  94012. * 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.
  94013. */
  94014. position, color, imgUrl, system) {
  94015. this.size = size;
  94016. this.position = position;
  94017. /**
  94018. * Define the alpha mode to render this particular lens.
  94019. */
  94020. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  94021. this.color = color || new BABYLON.Color3(1, 1, 1);
  94022. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  94023. this._system = system;
  94024. system.lensFlares.push(this);
  94025. }
  94026. /**
  94027. * Creates a new Lens Flare.
  94028. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  94029. * It controls one of the indiviual texture used in the effect.
  94030. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  94031. * @param size Define the size of the lens flare (a floating value between 0 and 1)
  94032. * @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.
  94033. * @param color Define the lens color
  94034. * @param imgUrl Define the lens texture url
  94035. * @param system Define the `lensFlareSystem` this flare is part of
  94036. * @returns The newly created Lens Flare
  94037. */
  94038. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  94039. return new LensFlare(size, position, color, imgUrl, system);
  94040. };
  94041. /**
  94042. * Dispose and release the lens flare with its associated resources.
  94043. */
  94044. LensFlare.prototype.dispose = function () {
  94045. if (this.texture) {
  94046. this.texture.dispose();
  94047. }
  94048. // Remove from scene
  94049. var index = this._system.lensFlares.indexOf(this);
  94050. this._system.lensFlares.splice(index, 1);
  94051. };
  94052. return LensFlare;
  94053. }());
  94054. BABYLON.LensFlare = LensFlare;
  94055. })(BABYLON || (BABYLON = {}));
  94056. //# sourceMappingURL=babylon.lensFlare.js.map
  94057. var BABYLON;
  94058. (function (BABYLON) {
  94059. // Adds the parser to the scene parsers.
  94060. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  94061. // Lens flares
  94062. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  94063. if (!container.lensFlareSystems) {
  94064. container.lensFlareSystems = new Array();
  94065. }
  94066. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  94067. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  94068. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  94069. container.lensFlareSystems.push(lf);
  94070. }
  94071. }
  94072. });
  94073. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  94074. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  94075. if (this.lensFlareSystems[index].name === name) {
  94076. return this.lensFlareSystems[index];
  94077. }
  94078. }
  94079. return null;
  94080. };
  94081. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  94082. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  94083. if (this.lensFlareSystems[index].id === id) {
  94084. return this.lensFlareSystems[index];
  94085. }
  94086. }
  94087. return null;
  94088. };
  94089. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  94090. var index = this.lensFlareSystems.indexOf(toRemove);
  94091. if (index !== -1) {
  94092. this.lensFlareSystems.splice(index, 1);
  94093. }
  94094. return index;
  94095. };
  94096. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  94097. this.lensFlareSystems.push(newLensFlareSystem);
  94098. };
  94099. /**
  94100. * Defines the lens flare scene component responsible to manage any lens flares
  94101. * in a given scene.
  94102. */
  94103. var LensFlareSystemSceneComponent = /** @class */ (function () {
  94104. /**
  94105. * Creates a new instance of the component for the given scene
  94106. * @param scene Defines the scene to register the component in
  94107. */
  94108. function LensFlareSystemSceneComponent(scene) {
  94109. /**
  94110. * The component name helpfull to identify the component in the list of scene components.
  94111. */
  94112. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  94113. this.scene = scene;
  94114. scene.lensFlareSystems = new Array();
  94115. }
  94116. /**
  94117. * Registers the component in a given scene
  94118. */
  94119. LensFlareSystemSceneComponent.prototype.register = function () {
  94120. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  94121. };
  94122. /**
  94123. * Rebuilds the elements related to this component in case of
  94124. * context lost for instance.
  94125. */
  94126. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  94127. // Nothing to do for lens flare
  94128. };
  94129. /**
  94130. * Adds all the element from the container to the scene
  94131. * @param container the container holding the elements
  94132. */
  94133. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  94134. var _this = this;
  94135. if (!container.lensFlareSystems) {
  94136. return;
  94137. }
  94138. container.lensFlareSystems.forEach(function (o) {
  94139. _this.scene.addLensFlareSystem(o);
  94140. });
  94141. };
  94142. /**
  94143. * Removes all the elements in the container from the scene
  94144. * @param container contains the elements to remove
  94145. */
  94146. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  94147. var _this = this;
  94148. if (!container.lensFlareSystems) {
  94149. return;
  94150. }
  94151. container.lensFlareSystems.forEach(function (o) {
  94152. _this.scene.removeLensFlareSystem(o);
  94153. });
  94154. };
  94155. /**
  94156. * Serializes the component data to the specified json object
  94157. * @param serializationObject The object to serialize to
  94158. */
  94159. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  94160. // Lens flares
  94161. serializationObject.lensFlareSystems = [];
  94162. var lensFlareSystems = this.scene.lensFlareSystems;
  94163. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  94164. var lensFlareSystem = lensFlareSystems_1[_i];
  94165. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  94166. }
  94167. };
  94168. /**
  94169. * Disposes the component and the associated ressources.
  94170. */
  94171. LensFlareSystemSceneComponent.prototype.dispose = function () {
  94172. var lensFlareSystems = this.scene.lensFlareSystems;
  94173. while (lensFlareSystems.length) {
  94174. lensFlareSystems[0].dispose();
  94175. }
  94176. };
  94177. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  94178. // Lens flares
  94179. if (this.scene.lensFlaresEnabled) {
  94180. var lensFlareSystems = this.scene.lensFlareSystems;
  94181. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  94182. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  94183. var lensFlareSystem = lensFlareSystems_2[_i];
  94184. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  94185. lensFlareSystem.render();
  94186. }
  94187. }
  94188. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  94189. }
  94190. };
  94191. return LensFlareSystemSceneComponent;
  94192. }());
  94193. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  94194. })(BABYLON || (BABYLON = {}));
  94195. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  94196. var BABYLON;
  94197. (function (BABYLON) {
  94198. /**
  94199. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  94200. * It is usually composed of several `BABYLON.lensFlare`.
  94201. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  94202. */
  94203. var LensFlareSystem = /** @class */ (function () {
  94204. /**
  94205. * Instantiates a lens flare system.
  94206. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  94207. * It is usually composed of several `BABYLON.lensFlare`.
  94208. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  94209. * @param name Define the name of the lens flare system in the scene
  94210. * @param emitter Define the source (the emitter) of the lens flares (it can be a camera, a light or a mesh).
  94211. * @param scene Define the scene the lens flare system belongs to
  94212. */
  94213. function LensFlareSystem(
  94214. /**
  94215. * Define the name of the lens flare system
  94216. */
  94217. name, emitter, scene) {
  94218. this.name = name;
  94219. /**
  94220. * List of lens flares used in this system.
  94221. */
  94222. this.lensFlares = new Array();
  94223. /**
  94224. * Define a limit from the border the lens flare can be visible.
  94225. */
  94226. this.borderLimit = 300;
  94227. /**
  94228. * Define a viewport border we do not want to see the lens flare in.
  94229. */
  94230. this.viewportBorder = 0;
  94231. /**
  94232. * Restricts the rendering of the effect to only the camera rendering this layer mask.
  94233. */
  94234. this.layerMask = 0x0FFFFFFF;
  94235. this._vertexBuffers = {};
  94236. this._isEnabled = true;
  94237. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  94238. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  94239. if (!component) {
  94240. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  94241. scene._addComponent(component);
  94242. }
  94243. this._emitter = emitter;
  94244. this.id = name;
  94245. scene.lensFlareSystems.push(this);
  94246. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  94247. var engine = scene.getEngine();
  94248. // VBO
  94249. var vertices = [];
  94250. vertices.push(1, 1);
  94251. vertices.push(-1, 1);
  94252. vertices.push(-1, -1);
  94253. vertices.push(1, -1);
  94254. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  94255. // Indices
  94256. var indices = [];
  94257. indices.push(0);
  94258. indices.push(1);
  94259. indices.push(2);
  94260. indices.push(0);
  94261. indices.push(2);
  94262. indices.push(3);
  94263. this._indexBuffer = engine.createIndexBuffer(indices);
  94264. // Effects
  94265. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  94266. }
  94267. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  94268. /**
  94269. * Define if the lens flare system is enabled.
  94270. */
  94271. get: function () {
  94272. return this._isEnabled;
  94273. },
  94274. set: function (value) {
  94275. this._isEnabled = value;
  94276. },
  94277. enumerable: true,
  94278. configurable: true
  94279. });
  94280. /**
  94281. * Get the scene the effects belongs to.
  94282. * @returns the scene holding the lens flare system
  94283. */
  94284. LensFlareSystem.prototype.getScene = function () {
  94285. return this._scene;
  94286. };
  94287. /**
  94288. * Get the emitter of the lens flare system.
  94289. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  94290. * @returns the emitter of the lens flare system
  94291. */
  94292. LensFlareSystem.prototype.getEmitter = function () {
  94293. return this._emitter;
  94294. };
  94295. /**
  94296. * Set the emitter of the lens flare system.
  94297. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  94298. * @param newEmitter Define the new emitter of the system
  94299. */
  94300. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  94301. this._emitter = newEmitter;
  94302. };
  94303. /**
  94304. * Get the lens flare system emitter position.
  94305. * The emitter defines the source of the lens flares (it can be a camera, a light or a mesh).
  94306. * @returns the position
  94307. */
  94308. LensFlareSystem.prototype.getEmitterPosition = function () {
  94309. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  94310. };
  94311. /**
  94312. * @hidden
  94313. */
  94314. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  94315. var position = this.getEmitterPosition();
  94316. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  94317. this._positionX = position.x;
  94318. this._positionY = position.y;
  94319. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  94320. if (this.viewportBorder > 0) {
  94321. globalViewport.x -= this.viewportBorder;
  94322. globalViewport.y -= this.viewportBorder;
  94323. globalViewport.width += this.viewportBorder * 2;
  94324. globalViewport.height += this.viewportBorder * 2;
  94325. position.x += this.viewportBorder;
  94326. position.y += this.viewportBorder;
  94327. this._positionX += this.viewportBorder;
  94328. this._positionY += this.viewportBorder;
  94329. }
  94330. if (position.z > 0) {
  94331. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  94332. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height)) {
  94333. return true;
  94334. }
  94335. }
  94336. return true;
  94337. }
  94338. return false;
  94339. };
  94340. /** @hidden */
  94341. LensFlareSystem.prototype._isVisible = function () {
  94342. if (!this._isEnabled || !this._scene.activeCamera) {
  94343. return false;
  94344. }
  94345. var emitterPosition = this.getEmitterPosition();
  94346. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  94347. var distance = direction.length();
  94348. direction.normalize();
  94349. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  94350. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  94351. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  94352. };
  94353. /**
  94354. * @hidden
  94355. */
  94356. LensFlareSystem.prototype.render = function () {
  94357. if (!this._effect.isReady() || !this._scene.activeCamera) {
  94358. return false;
  94359. }
  94360. var engine = this._scene.getEngine();
  94361. var viewport = this._scene.activeCamera.viewport;
  94362. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  94363. // Position
  94364. if (!this.computeEffectivePosition(globalViewport)) {
  94365. return false;
  94366. }
  94367. // Visibility
  94368. if (!this._isVisible()) {
  94369. return false;
  94370. }
  94371. // Intensity
  94372. var awayX;
  94373. var awayY;
  94374. if (this._positionX < this.borderLimit + globalViewport.x) {
  94375. awayX = this.borderLimit + globalViewport.x - this._positionX;
  94376. }
  94377. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  94378. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  94379. }
  94380. else {
  94381. awayX = 0;
  94382. }
  94383. if (this._positionY < this.borderLimit + globalViewport.y) {
  94384. awayY = this.borderLimit + globalViewport.y - this._positionY;
  94385. }
  94386. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  94387. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  94388. }
  94389. else {
  94390. awayY = 0;
  94391. }
  94392. var away = (awayX > awayY) ? awayX : awayY;
  94393. away -= this.viewportBorder;
  94394. if (away > this.borderLimit) {
  94395. away = this.borderLimit;
  94396. }
  94397. var intensity = 1.0 - BABYLON.Scalar.Clamp(away / this.borderLimit, 0, 1);
  94398. if (intensity < 0) {
  94399. return false;
  94400. }
  94401. if (intensity > 1.0) {
  94402. intensity = 1.0;
  94403. }
  94404. if (this.viewportBorder > 0) {
  94405. globalViewport.x += this.viewportBorder;
  94406. globalViewport.y += this.viewportBorder;
  94407. globalViewport.width -= this.viewportBorder * 2;
  94408. globalViewport.height -= this.viewportBorder * 2;
  94409. this._positionX -= this.viewportBorder;
  94410. this._positionY -= this.viewportBorder;
  94411. }
  94412. // Position
  94413. var centerX = globalViewport.x + globalViewport.width / 2;
  94414. var centerY = globalViewport.y + globalViewport.height / 2;
  94415. var distX = centerX - this._positionX;
  94416. var distY = centerY - this._positionY;
  94417. // Effects
  94418. engine.enableEffect(this._effect);
  94419. engine.setState(false);
  94420. engine.setDepthBuffer(false);
  94421. // VBOs
  94422. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  94423. // Flares
  94424. for (var index = 0; index < this.lensFlares.length; index++) {
  94425. var flare = this.lensFlares[index];
  94426. engine.setAlphaMode(flare.alphaMode);
  94427. var x = centerX - (distX * flare.position);
  94428. var y = centerY - (distY * flare.position);
  94429. var cw = flare.size;
  94430. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  94431. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  94432. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  94433. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  94434. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  94435. // Texture
  94436. this._effect.setTexture("textureSampler", flare.texture);
  94437. // Color
  94438. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  94439. // Draw order
  94440. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94441. }
  94442. engine.setDepthBuffer(true);
  94443. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  94444. return true;
  94445. };
  94446. /**
  94447. * Dispose and release the lens flare with its associated resources.
  94448. */
  94449. LensFlareSystem.prototype.dispose = function () {
  94450. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  94451. if (vertexBuffer) {
  94452. vertexBuffer.dispose();
  94453. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  94454. }
  94455. if (this._indexBuffer) {
  94456. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  94457. this._indexBuffer = null;
  94458. }
  94459. while (this.lensFlares.length) {
  94460. this.lensFlares[0].dispose();
  94461. }
  94462. // Remove from scene
  94463. var index = this._scene.lensFlareSystems.indexOf(this);
  94464. this._scene.lensFlareSystems.splice(index, 1);
  94465. };
  94466. /**
  94467. * Parse a lens flare system from a JSON repressentation
  94468. * @param parsedLensFlareSystem Define the JSON to parse
  94469. * @param scene Define the scene the parsed system should be instantiated in
  94470. * @param rootUrl Define the rootUrl of the load sequence to easily find a load relative dependencies such as textures
  94471. * @returns the parsed system
  94472. */
  94473. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  94474. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  94475. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  94476. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  94477. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  94478. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  94479. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  94480. var parsedFlare = parsedLensFlareSystem.flares[index];
  94481. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  94482. }
  94483. return lensFlareSystem;
  94484. };
  94485. /**
  94486. * Serialize the current Lens Flare System into a JSON representation.
  94487. * @returns the serialized JSON
  94488. */
  94489. LensFlareSystem.prototype.serialize = function () {
  94490. var serializationObject = {};
  94491. serializationObject.id = this.id;
  94492. serializationObject.name = this.name;
  94493. serializationObject.emitterId = this.getEmitter().id;
  94494. serializationObject.borderLimit = this.borderLimit;
  94495. serializationObject.flares = [];
  94496. for (var index = 0; index < this.lensFlares.length; index++) {
  94497. var flare = this.lensFlares[index];
  94498. serializationObject.flares.push({
  94499. size: flare.size,
  94500. position: flare.position,
  94501. color: flare.color.asArray(),
  94502. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  94503. });
  94504. }
  94505. return serializationObject;
  94506. };
  94507. return LensFlareSystem;
  94508. }());
  94509. BABYLON.LensFlareSystem = LensFlareSystem;
  94510. })(BABYLON || (BABYLON = {}));
  94511. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  94512. var BABYLON;
  94513. (function (BABYLON) {
  94514. /**
  94515. * This is a holder class for the physics joint created by the physics plugin
  94516. * It holds a set of functions to control the underlying joint
  94517. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  94518. */
  94519. var PhysicsJoint = /** @class */ (function () {
  94520. /**
  94521. * Initializes the physics joint
  94522. * @param type The type of the physics joint
  94523. * @param jointData The data for the physics joint
  94524. */
  94525. function PhysicsJoint(
  94526. /**
  94527. * The type of the physics joint
  94528. */
  94529. type,
  94530. /**
  94531. * The data for the physics joint
  94532. */
  94533. jointData) {
  94534. this.type = type;
  94535. this.jointData = jointData;
  94536. jointData.nativeParams = jointData.nativeParams || {};
  94537. }
  94538. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  94539. /**
  94540. * Gets the physics joint
  94541. */
  94542. get: function () {
  94543. return this._physicsJoint;
  94544. },
  94545. /**
  94546. * Sets the physics joint
  94547. */
  94548. set: function (newJoint) {
  94549. if (this._physicsJoint) {
  94550. //remove from the wolrd
  94551. }
  94552. this._physicsJoint = newJoint;
  94553. },
  94554. enumerable: true,
  94555. configurable: true
  94556. });
  94557. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  94558. /**
  94559. * Sets the physics plugin
  94560. */
  94561. set: function (physicsPlugin) {
  94562. this._physicsPlugin = physicsPlugin;
  94563. },
  94564. enumerable: true,
  94565. configurable: true
  94566. });
  94567. /**
  94568. * Execute a function that is physics-plugin specific.
  94569. * @param {Function} func the function that will be executed.
  94570. * It accepts two parameters: the physics world and the physics joint
  94571. */
  94572. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  94573. func(this._physicsPlugin.world, this._physicsJoint);
  94574. };
  94575. //TODO check if the native joints are the same
  94576. //Joint Types
  94577. /**
  94578. * Distance-Joint type
  94579. */
  94580. PhysicsJoint.DistanceJoint = 0;
  94581. /**
  94582. * Hinge-Joint type
  94583. */
  94584. PhysicsJoint.HingeJoint = 1;
  94585. /**
  94586. * Ball-and-Socket joint type
  94587. */
  94588. PhysicsJoint.BallAndSocketJoint = 2;
  94589. /**
  94590. * Wheel-Joint type
  94591. */
  94592. PhysicsJoint.WheelJoint = 3;
  94593. /**
  94594. * Slider-Joint type
  94595. */
  94596. PhysicsJoint.SliderJoint = 4;
  94597. //OIMO
  94598. /**
  94599. * Prismatic-Joint type
  94600. */
  94601. PhysicsJoint.PrismaticJoint = 5;
  94602. //
  94603. /**
  94604. * Universal-Joint type
  94605. * ENERGY FTW! (compare with this - @see http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  94606. */
  94607. PhysicsJoint.UniversalJoint = 6;
  94608. /**
  94609. * Hinge-Joint 2 type
  94610. */
  94611. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  94612. //Cannon
  94613. /**
  94614. * Point to Point Joint type. Similar to a Ball-Joint. Different in parameters
  94615. */
  94616. PhysicsJoint.PointToPointJoint = 8;
  94617. //Cannon only at the moment
  94618. /**
  94619. * Spring-Joint type
  94620. */
  94621. PhysicsJoint.SpringJoint = 9;
  94622. /**
  94623. * Lock-Joint type
  94624. */
  94625. PhysicsJoint.LockJoint = 10;
  94626. return PhysicsJoint;
  94627. }());
  94628. BABYLON.PhysicsJoint = PhysicsJoint;
  94629. /**
  94630. * A class representing a physics distance joint
  94631. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  94632. */
  94633. var DistanceJoint = /** @class */ (function (_super) {
  94634. __extends(DistanceJoint, _super);
  94635. /**
  94636. *
  94637. * @param jointData The data for the Distance-Joint
  94638. */
  94639. function DistanceJoint(jointData) {
  94640. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  94641. }
  94642. /**
  94643. * Update the predefined distance.
  94644. * @param maxDistance The maximum preferred distance
  94645. * @param minDistance The minimum preferred distance
  94646. */
  94647. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  94648. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  94649. };
  94650. return DistanceJoint;
  94651. }(PhysicsJoint));
  94652. BABYLON.DistanceJoint = DistanceJoint;
  94653. /**
  94654. * Represents a Motor-Enabled Joint
  94655. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  94656. */
  94657. var MotorEnabledJoint = /** @class */ (function (_super) {
  94658. __extends(MotorEnabledJoint, _super);
  94659. /**
  94660. * Initializes the Motor-Enabled Joint
  94661. * @param type The type of the joint
  94662. * @param jointData The physica joint data for the joint
  94663. */
  94664. function MotorEnabledJoint(type, jointData) {
  94665. return _super.call(this, type, jointData) || this;
  94666. }
  94667. /**
  94668. * Set the motor values.
  94669. * Attention, this function is plugin specific. Engines won't react 100% the same.
  94670. * @param force the force to apply
  94671. * @param maxForce max force for this motor.
  94672. */
  94673. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  94674. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  94675. };
  94676. /**
  94677. * Set the motor's limits.
  94678. * Attention, this function is plugin specific. Engines won't react 100% the same.
  94679. * @param upperLimit The upper limit of the motor
  94680. * @param lowerLimit The lower limit of the motor
  94681. */
  94682. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  94683. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  94684. };
  94685. return MotorEnabledJoint;
  94686. }(PhysicsJoint));
  94687. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  94688. /**
  94689. * This class represents a single physics Hinge-Joint
  94690. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  94691. */
  94692. var HingeJoint = /** @class */ (function (_super) {
  94693. __extends(HingeJoint, _super);
  94694. /**
  94695. * Initializes the Hinge-Joint
  94696. * @param jointData The joint data for the Hinge-Joint
  94697. */
  94698. function HingeJoint(jointData) {
  94699. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  94700. }
  94701. /**
  94702. * Set the motor values.
  94703. * Attention, this function is plugin specific. Engines won't react 100% the same.
  94704. * @param {number} force the force to apply
  94705. * @param {number} maxForce max force for this motor.
  94706. */
  94707. HingeJoint.prototype.setMotor = function (force, maxForce) {
  94708. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  94709. };
  94710. /**
  94711. * Set the motor's limits.
  94712. * Attention, this function is plugin specific. Engines won't react 100% the same.
  94713. * @param upperLimit The upper limit of the motor
  94714. * @param lowerLimit The lower limit of the motor
  94715. */
  94716. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  94717. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  94718. };
  94719. return HingeJoint;
  94720. }(MotorEnabledJoint));
  94721. BABYLON.HingeJoint = HingeJoint;
  94722. /**
  94723. * This class represents a dual hinge physics joint (same as wheel joint)
  94724. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  94725. */
  94726. var Hinge2Joint = /** @class */ (function (_super) {
  94727. __extends(Hinge2Joint, _super);
  94728. /**
  94729. * Initializes the Hinge2-Joint
  94730. * @param jointData The joint data for the Hinge2-Joint
  94731. */
  94732. function Hinge2Joint(jointData) {
  94733. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  94734. }
  94735. /**
  94736. * Set the motor values.
  94737. * Attention, this function is plugin specific. Engines won't react 100% the same.
  94738. * @param {number} force the force to apply
  94739. * @param {number} maxForce max force for this motor.
  94740. * @param {motorIndex} the motor's index, 0 or 1.
  94741. */
  94742. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  94743. if (motorIndex === void 0) { motorIndex = 0; }
  94744. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  94745. };
  94746. /**
  94747. * Set the motor limits.
  94748. * Attention, this function is plugin specific. Engines won't react 100% the same.
  94749. * @param {number} upperLimit the upper limit
  94750. * @param {number} lowerLimit lower limit
  94751. * @param {motorIndex} the motor's index, 0 or 1.
  94752. */
  94753. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  94754. if (motorIndex === void 0) { motorIndex = 0; }
  94755. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  94756. };
  94757. return Hinge2Joint;
  94758. }(MotorEnabledJoint));
  94759. BABYLON.Hinge2Joint = Hinge2Joint;
  94760. })(BABYLON || (BABYLON = {}));
  94761. //# sourceMappingURL=babylon.physicsJoint.js.map
  94762. var BABYLON;
  94763. (function (BABYLON) {
  94764. /**
  94765. * Represents a physics imposter
  94766. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  94767. */
  94768. var PhysicsImpostor = /** @class */ (function () {
  94769. /**
  94770. * Initializes the physics imposter
  94771. * @param object The physics-enabled object used as the physics imposter
  94772. * @param type The type of the physics imposter
  94773. * @param _options The options for the physics imposter
  94774. * @param _scene The Babylon scene
  94775. */
  94776. function PhysicsImpostor(
  94777. /**
  94778. * The physics-enabled object used as the physics imposter
  94779. */
  94780. object,
  94781. /**
  94782. * The type of the physics imposter
  94783. */
  94784. type, _options, _scene) {
  94785. if (_options === void 0) { _options = { mass: 0 }; }
  94786. var _this = this;
  94787. this.object = object;
  94788. this.type = type;
  94789. this._options = _options;
  94790. this._scene = _scene;
  94791. this._bodyUpdateRequired = false;
  94792. this._onBeforePhysicsStepCallbacks = new Array();
  94793. this._onAfterPhysicsStepCallbacks = new Array();
  94794. this._onPhysicsCollideCallbacks = [];
  94795. this._deltaPosition = BABYLON.Vector3.Zero();
  94796. this._isDisposed = false;
  94797. //temp variables for parent rotation calculations
  94798. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  94799. this._tmpQuat = new BABYLON.Quaternion();
  94800. this._tmpQuat2 = new BABYLON.Quaternion();
  94801. /**
  94802. * this function is executed by the physics engine.
  94803. */
  94804. this.beforeStep = function () {
  94805. if (!_this._physicsEngine) {
  94806. return;
  94807. }
  94808. _this.object.translate(_this._deltaPosition, -1);
  94809. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  94810. _this.object.computeWorldMatrix(false);
  94811. if (_this.object.parent && _this.object.rotationQuaternion) {
  94812. _this.getParentsRotation();
  94813. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  94814. }
  94815. else {
  94816. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  94817. }
  94818. if (!_this._options.disableBidirectionalTransformation) {
  94819. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  94820. }
  94821. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  94822. func(_this);
  94823. });
  94824. };
  94825. /**
  94826. * this function is executed by the physics engine
  94827. */
  94828. this.afterStep = function () {
  94829. if (!_this._physicsEngine) {
  94830. return;
  94831. }
  94832. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  94833. func(_this);
  94834. });
  94835. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  94836. // object has now its world rotation. needs to be converted to local.
  94837. if (_this.object.parent && _this.object.rotationQuaternion) {
  94838. _this.getParentsRotation();
  94839. _this._tmpQuat.conjugateInPlace();
  94840. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  94841. }
  94842. // take the position set and make it the absolute position of this object.
  94843. _this.object.setAbsolutePosition(_this.object.position);
  94844. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  94845. _this.object.translate(_this._deltaPosition, 1);
  94846. };
  94847. /**
  94848. * Legacy collision detection event support
  94849. */
  94850. this.onCollideEvent = null;
  94851. /**
  94852. * event and body object due to cannon's event-based architecture.
  94853. */
  94854. this.onCollide = function (e) {
  94855. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  94856. return;
  94857. }
  94858. if (!_this._physicsEngine) {
  94859. return;
  94860. }
  94861. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  94862. if (otherImpostor) {
  94863. // Legacy collision detection event support
  94864. if (_this.onCollideEvent) {
  94865. _this.onCollideEvent(_this, otherImpostor);
  94866. }
  94867. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  94868. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  94869. }).forEach(function (obj) {
  94870. obj.callback(_this, otherImpostor);
  94871. });
  94872. }
  94873. };
  94874. //sanity check!
  94875. if (!this.object) {
  94876. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  94877. return;
  94878. }
  94879. //legacy support for old syntax.
  94880. if (!this._scene && object.getScene) {
  94881. this._scene = object.getScene();
  94882. }
  94883. if (!this._scene) {
  94884. return;
  94885. }
  94886. this._physicsEngine = this._scene.getPhysicsEngine();
  94887. if (!this._physicsEngine) {
  94888. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  94889. }
  94890. else {
  94891. //set the object's quaternion, if not set
  94892. if (!this.object.rotationQuaternion) {
  94893. if (this.object.rotation) {
  94894. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  94895. }
  94896. else {
  94897. this.object.rotationQuaternion = new BABYLON.Quaternion();
  94898. }
  94899. }
  94900. //default options params
  94901. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  94902. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  94903. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  94904. this._joints = [];
  94905. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  94906. if (!this.object.parent || this._options.ignoreParent) {
  94907. this._init();
  94908. }
  94909. else if (this.object.parent.physicsImpostor) {
  94910. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  94911. }
  94912. }
  94913. }
  94914. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  94915. /**
  94916. * Specifies if the physics imposter is disposed
  94917. */
  94918. get: function () {
  94919. return this._isDisposed;
  94920. },
  94921. enumerable: true,
  94922. configurable: true
  94923. });
  94924. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  94925. /**
  94926. * Gets the mass of the physics imposter
  94927. */
  94928. get: function () {
  94929. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  94930. },
  94931. set: function (value) {
  94932. this.setMass(value);
  94933. },
  94934. enumerable: true,
  94935. configurable: true
  94936. });
  94937. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  94938. /**
  94939. * Gets the coefficient of friction
  94940. */
  94941. get: function () {
  94942. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  94943. },
  94944. /**
  94945. * Sets the coefficient of friction
  94946. */
  94947. set: function (value) {
  94948. if (!this._physicsEngine) {
  94949. return;
  94950. }
  94951. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  94952. },
  94953. enumerable: true,
  94954. configurable: true
  94955. });
  94956. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  94957. /**
  94958. * Gets the coefficient of restitution
  94959. */
  94960. get: function () {
  94961. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  94962. },
  94963. /**
  94964. * Sets the coefficient of restitution
  94965. */
  94966. set: function (value) {
  94967. if (!this._physicsEngine) {
  94968. return;
  94969. }
  94970. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  94971. },
  94972. enumerable: true,
  94973. configurable: true
  94974. });
  94975. /**
  94976. * This function will completly initialize this impostor.
  94977. * It will create a new body - but only if this mesh has no parent.
  94978. * If it has, this impostor will not be used other than to define the impostor
  94979. * of the child mesh.
  94980. * @hidden
  94981. */
  94982. PhysicsImpostor.prototype._init = function () {
  94983. if (!this._physicsEngine) {
  94984. return;
  94985. }
  94986. this._physicsEngine.removeImpostor(this);
  94987. this.physicsBody = null;
  94988. this._parent = this._parent || this._getPhysicsParent();
  94989. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  94990. this._physicsEngine.addImpostor(this);
  94991. }
  94992. };
  94993. PhysicsImpostor.prototype._getPhysicsParent = function () {
  94994. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  94995. var parentMesh = this.object.parent;
  94996. return parentMesh.physicsImpostor;
  94997. }
  94998. return null;
  94999. };
  95000. /**
  95001. * Should a new body be generated.
  95002. * @returns boolean specifying if body initialization is required
  95003. */
  95004. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  95005. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  95006. };
  95007. /**
  95008. * Sets the updated scaling
  95009. * @param updated Specifies if the scaling is updated
  95010. */
  95011. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  95012. this.forceUpdate();
  95013. };
  95014. /**
  95015. * Force a regeneration of this or the parent's impostor's body.
  95016. * Use under cautious - This will remove all joints already implemented.
  95017. */
  95018. PhysicsImpostor.prototype.forceUpdate = function () {
  95019. this._init();
  95020. if (this.parent && !this._options.ignoreParent) {
  95021. this.parent.forceUpdate();
  95022. }
  95023. };
  95024. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  95025. /*public get mesh(): AbstractMesh {
  95026. return this._mesh;
  95027. }*/
  95028. /**
  95029. * Gets the body that holds this impostor. Either its own, or its parent.
  95030. */
  95031. get: function () {
  95032. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  95033. },
  95034. /**
  95035. * Set the physics body. Used mainly by the physics engine/plugin
  95036. */
  95037. set: function (physicsBody) {
  95038. if (this._physicsBody && this._physicsEngine) {
  95039. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  95040. }
  95041. this._physicsBody = physicsBody;
  95042. this.resetUpdateFlags();
  95043. },
  95044. enumerable: true,
  95045. configurable: true
  95046. });
  95047. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  95048. /**
  95049. * Get the parent of the physics imposter
  95050. * @returns Physics imposter or null
  95051. */
  95052. get: function () {
  95053. return !this._options.ignoreParent && this._parent ? this._parent : null;
  95054. },
  95055. /**
  95056. * Sets the parent of the physics imposter
  95057. */
  95058. set: function (value) {
  95059. this._parent = value;
  95060. },
  95061. enumerable: true,
  95062. configurable: true
  95063. });
  95064. /**
  95065. * Resets the update flags
  95066. */
  95067. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  95068. this._bodyUpdateRequired = false;
  95069. };
  95070. /**
  95071. * Gets the object extend size
  95072. * @returns the object extend size
  95073. */
  95074. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  95075. if (this.object.getBoundingInfo) {
  95076. var q = this.object.rotationQuaternion;
  95077. //reset rotation
  95078. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  95079. //calculate the world matrix with no rotation
  95080. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  95081. var boundingInfo = this.object.getBoundingInfo();
  95082. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  95083. //bring back the rotation
  95084. this.object.rotationQuaternion = q;
  95085. //calculate the world matrix with the new rotation
  95086. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  95087. return size;
  95088. }
  95089. else {
  95090. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  95091. }
  95092. };
  95093. /**
  95094. * Gets the object center
  95095. * @returns The object center
  95096. */
  95097. PhysicsImpostor.prototype.getObjectCenter = function () {
  95098. if (this.object.getBoundingInfo) {
  95099. var boundingInfo = this.object.getBoundingInfo();
  95100. return boundingInfo.boundingBox.centerWorld;
  95101. }
  95102. else {
  95103. return this.object.position;
  95104. }
  95105. };
  95106. /**
  95107. * Get a specific parametes from the options parameter
  95108. * @param paramName The object parameter name
  95109. * @returns The object parameter
  95110. */
  95111. PhysicsImpostor.prototype.getParam = function (paramName) {
  95112. return this._options[paramName];
  95113. };
  95114. /**
  95115. * Sets a specific parameter in the options given to the physics plugin
  95116. * @param paramName The parameter name
  95117. * @param value The value of the parameter
  95118. */
  95119. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  95120. this._options[paramName] = value;
  95121. this._bodyUpdateRequired = true;
  95122. };
  95123. /**
  95124. * Specifically change the body's mass option. Won't recreate the physics body object
  95125. * @param mass The mass of the physics imposter
  95126. */
  95127. PhysicsImpostor.prototype.setMass = function (mass) {
  95128. if (this.getParam("mass") !== mass) {
  95129. this.setParam("mass", mass);
  95130. }
  95131. if (this._physicsEngine) {
  95132. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  95133. }
  95134. };
  95135. /**
  95136. * Gets the linear velocity
  95137. * @returns linear velocity or null
  95138. */
  95139. PhysicsImpostor.prototype.getLinearVelocity = function () {
  95140. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  95141. };
  95142. /**
  95143. * Sets the linear velocity
  95144. * @param velocity linear velocity or null
  95145. */
  95146. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  95147. if (this._physicsEngine) {
  95148. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  95149. }
  95150. };
  95151. /**
  95152. * Gets the angular velocity
  95153. * @returns angular velocity or null
  95154. */
  95155. PhysicsImpostor.prototype.getAngularVelocity = function () {
  95156. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  95157. };
  95158. /**
  95159. * Sets the angular velocity
  95160. * @param velocity The velocity or null
  95161. */
  95162. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  95163. if (this._physicsEngine) {
  95164. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  95165. }
  95166. };
  95167. /**
  95168. * Execute a function with the physics plugin native code
  95169. * Provide a function the will have two variables - the world object and the physics body object
  95170. * @param func The function to execute with the physics plugin native code
  95171. */
  95172. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  95173. if (this._physicsEngine) {
  95174. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  95175. }
  95176. };
  95177. /**
  95178. * Register a function that will be executed before the physics world is stepping forward
  95179. * @param func The function to execute before the physics world is stepped forward
  95180. */
  95181. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  95182. this._onBeforePhysicsStepCallbacks.push(func);
  95183. };
  95184. /**
  95185. * Unregister a function that will be executed before the physics world is stepping forward
  95186. * @param func The function to execute before the physics world is stepped forward
  95187. */
  95188. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  95189. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  95190. if (index > -1) {
  95191. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  95192. }
  95193. else {
  95194. BABYLON.Tools.Warn("Function to remove was not found");
  95195. }
  95196. };
  95197. /**
  95198. * Register a function that will be executed after the physics step
  95199. * @param func The function to execute after physics step
  95200. */
  95201. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  95202. this._onAfterPhysicsStepCallbacks.push(func);
  95203. };
  95204. /**
  95205. * Unregisters a function that will be executed after the physics step
  95206. * @param func The function to execute after physics step
  95207. */
  95208. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  95209. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  95210. if (index > -1) {
  95211. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  95212. }
  95213. else {
  95214. BABYLON.Tools.Warn("Function to remove was not found");
  95215. }
  95216. };
  95217. /**
  95218. * register a function that will be executed when this impostor collides against a different body
  95219. * @param collideAgainst Physics imposter, or array of physics imposters to collide against
  95220. * @param func Callback that is executed on collision
  95221. */
  95222. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  95223. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  95224. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  95225. };
  95226. /**
  95227. * Unregisters the physics imposter on contact
  95228. * @param collideAgainst The physics object to collide against
  95229. * @param func Callback to execute on collision
  95230. */
  95231. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  95232. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  95233. var index = -1;
  95234. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  95235. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  95236. // chcek the arrays match
  95237. var sameList = cbDef.otherImpostors.every(function (impostor) {
  95238. return collidedAgainstList.indexOf(impostor) > -1;
  95239. });
  95240. if (sameList) {
  95241. index = idx;
  95242. }
  95243. return sameList;
  95244. }
  95245. return false;
  95246. });
  95247. if (found) {
  95248. this._onPhysicsCollideCallbacks.splice(index, 1);
  95249. }
  95250. else {
  95251. BABYLON.Tools.Warn("Function to remove was not found");
  95252. }
  95253. };
  95254. /**
  95255. * Get the parent rotation
  95256. * @returns The parent rotation
  95257. */
  95258. PhysicsImpostor.prototype.getParentsRotation = function () {
  95259. var parent = this.object.parent;
  95260. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  95261. while (parent) {
  95262. if (parent.rotationQuaternion) {
  95263. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  95264. }
  95265. else {
  95266. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  95267. }
  95268. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  95269. parent = parent.parent;
  95270. }
  95271. return this._tmpQuat;
  95272. };
  95273. /**
  95274. * Apply a force
  95275. * @param force The force to apply
  95276. * @param contactPoint The contact point for the force
  95277. * @returns The physics imposter
  95278. */
  95279. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  95280. if (this._physicsEngine) {
  95281. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  95282. }
  95283. return this;
  95284. };
  95285. /**
  95286. * Apply an impulse
  95287. * @param force The impulse force
  95288. * @param contactPoint The contact point for the impulse force
  95289. * @returns The physics imposter
  95290. */
  95291. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  95292. if (this._physicsEngine) {
  95293. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  95294. }
  95295. return this;
  95296. };
  95297. /**
  95298. * A help function to create a joint
  95299. * @param otherImpostor A physics imposter used to create a joint
  95300. * @param jointType The type of joint
  95301. * @param jointData The data for the joint
  95302. * @returns The physics imposter
  95303. */
  95304. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  95305. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  95306. this.addJoint(otherImpostor, joint);
  95307. return this;
  95308. };
  95309. /**
  95310. * Add a joint to this impostor with a different impostor
  95311. * @param otherImpostor A physics imposter used to add a joint
  95312. * @param joint The joint to add
  95313. * @returns The physics imposter
  95314. */
  95315. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  95316. this._joints.push({
  95317. otherImpostor: otherImpostor,
  95318. joint: joint
  95319. });
  95320. if (this._physicsEngine) {
  95321. this._physicsEngine.addJoint(this, otherImpostor, joint);
  95322. }
  95323. return this;
  95324. };
  95325. /**
  95326. * Will keep this body still, in a sleep mode.
  95327. * @returns the physics imposter
  95328. */
  95329. PhysicsImpostor.prototype.sleep = function () {
  95330. if (this._physicsEngine) {
  95331. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  95332. }
  95333. return this;
  95334. };
  95335. /**
  95336. * Wake the body up.
  95337. * @returns The physics imposter
  95338. */
  95339. PhysicsImpostor.prototype.wakeUp = function () {
  95340. if (this._physicsEngine) {
  95341. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  95342. }
  95343. return this;
  95344. };
  95345. /**
  95346. * Clones the physics imposter
  95347. * @param newObject The physics imposter clones to this physics-enabled object
  95348. * @returns A nullable physics imposter
  95349. */
  95350. PhysicsImpostor.prototype.clone = function (newObject) {
  95351. if (!newObject) {
  95352. return null;
  95353. }
  95354. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  95355. };
  95356. /**
  95357. * Disposes the physics imposter
  95358. */
  95359. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  95360. var _this = this;
  95361. //no dispose if no physics engine is available.
  95362. if (!this._physicsEngine) {
  95363. return;
  95364. }
  95365. this._joints.forEach(function (j) {
  95366. if (_this._physicsEngine) {
  95367. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  95368. }
  95369. });
  95370. //dispose the physics body
  95371. this._physicsEngine.removeImpostor(this);
  95372. if (this.parent) {
  95373. this.parent.forceUpdate();
  95374. }
  95375. else {
  95376. /*this._object.getChildMeshes().forEach(function(mesh) {
  95377. if (mesh.physicsImpostor) {
  95378. if (disposeChildren) {
  95379. mesh.physicsImpostor.dispose();
  95380. mesh.physicsImpostor = null;
  95381. }
  95382. }
  95383. })*/
  95384. }
  95385. this._isDisposed = true;
  95386. };
  95387. /**
  95388. * Sets the delta position
  95389. * @param position The delta position amount
  95390. */
  95391. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  95392. this._deltaPosition.copyFrom(position);
  95393. };
  95394. /**
  95395. * Sets the delta rotation
  95396. * @param rotation The delta rotation amount
  95397. */
  95398. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  95399. if (!this._deltaRotation) {
  95400. this._deltaRotation = new BABYLON.Quaternion();
  95401. }
  95402. this._deltaRotation.copyFrom(rotation);
  95403. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  95404. };
  95405. /**
  95406. * Gets the box size of the physics imposter and stores the result in the input parameter
  95407. * @param result Stores the box size
  95408. * @returns The physics imposter
  95409. */
  95410. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  95411. if (this._physicsEngine) {
  95412. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  95413. }
  95414. return this;
  95415. };
  95416. /**
  95417. * Gets the radius of the physics imposter
  95418. * @returns Radius of the physics imposter
  95419. */
  95420. PhysicsImpostor.prototype.getRadius = function () {
  95421. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  95422. };
  95423. /**
  95424. * Sync a bone with this impostor
  95425. * @param bone The bone to sync to the impostor.
  95426. * @param boneMesh The mesh that the bone is influencing.
  95427. * @param jointPivot The pivot of the joint / bone in local space.
  95428. * @param distToJoint Optional distance from the impostor to the joint.
  95429. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  95430. */
  95431. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  95432. var tempVec = PhysicsImpostor._tmpVecs[0];
  95433. var mesh = this.object;
  95434. if (mesh.rotationQuaternion) {
  95435. if (adjustRotation) {
  95436. var tempQuat = PhysicsImpostor._tmpQuat;
  95437. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  95438. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  95439. }
  95440. else {
  95441. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  95442. }
  95443. }
  95444. tempVec.x = 0;
  95445. tempVec.y = 0;
  95446. tempVec.z = 0;
  95447. if (jointPivot) {
  95448. tempVec.x = jointPivot.x;
  95449. tempVec.y = jointPivot.y;
  95450. tempVec.z = jointPivot.z;
  95451. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  95452. if (distToJoint === undefined || distToJoint === null) {
  95453. distToJoint = jointPivot.length();
  95454. }
  95455. tempVec.x *= distToJoint;
  95456. tempVec.y *= distToJoint;
  95457. tempVec.z *= distToJoint;
  95458. }
  95459. if (bone.getParent()) {
  95460. tempVec.addInPlace(mesh.getAbsolutePosition());
  95461. bone.setAbsolutePosition(tempVec, boneMesh);
  95462. }
  95463. else {
  95464. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  95465. boneMesh.position.x -= tempVec.x;
  95466. boneMesh.position.y -= tempVec.y;
  95467. boneMesh.position.z -= tempVec.z;
  95468. }
  95469. };
  95470. /**
  95471. * Sync impostor to a bone
  95472. * @param bone The bone that the impostor will be synced to.
  95473. * @param boneMesh The mesh that the bone is influencing.
  95474. * @param jointPivot The pivot of the joint / bone in local space.
  95475. * @param distToJoint Optional distance from the impostor to the joint.
  95476. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  95477. * @param boneAxis Optional vector3 axis the bone is aligned with
  95478. */
  95479. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  95480. var mesh = this.object;
  95481. if (mesh.rotationQuaternion) {
  95482. if (adjustRotation) {
  95483. var tempQuat = PhysicsImpostor._tmpQuat;
  95484. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  95485. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  95486. }
  95487. else {
  95488. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  95489. }
  95490. }
  95491. var pos = PhysicsImpostor._tmpVecs[0];
  95492. var boneDir = PhysicsImpostor._tmpVecs[1];
  95493. if (!boneAxis) {
  95494. boneAxis = PhysicsImpostor._tmpVecs[2];
  95495. boneAxis.x = 0;
  95496. boneAxis.y = 1;
  95497. boneAxis.z = 0;
  95498. }
  95499. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  95500. bone.getAbsolutePositionToRef(boneMesh, pos);
  95501. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  95502. distToJoint = jointPivot.length();
  95503. }
  95504. if (distToJoint !== undefined && distToJoint !== null) {
  95505. pos.x += boneDir.x * distToJoint;
  95506. pos.y += boneDir.y * distToJoint;
  95507. pos.z += boneDir.z * distToJoint;
  95508. }
  95509. mesh.setAbsolutePosition(pos);
  95510. };
  95511. /**
  95512. * The default object size of the imposter
  95513. */
  95514. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  95515. /**
  95516. * The identity quaternion of the imposter
  95517. */
  95518. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  95519. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  95520. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  95521. //Impostor types
  95522. /**
  95523. * No-Imposter type
  95524. */
  95525. PhysicsImpostor.NoImpostor = 0;
  95526. /**
  95527. * Sphere-Imposter type
  95528. */
  95529. PhysicsImpostor.SphereImpostor = 1;
  95530. /**
  95531. * Box-Imposter type
  95532. */
  95533. PhysicsImpostor.BoxImpostor = 2;
  95534. /**
  95535. * Plane-Imposter type
  95536. */
  95537. PhysicsImpostor.PlaneImpostor = 3;
  95538. /**
  95539. * Mesh-imposter type
  95540. */
  95541. PhysicsImpostor.MeshImpostor = 4;
  95542. /**
  95543. * Cylinder-Imposter type
  95544. */
  95545. PhysicsImpostor.CylinderImpostor = 7;
  95546. /**
  95547. * Particle-Imposter type
  95548. */
  95549. PhysicsImpostor.ParticleImpostor = 8;
  95550. /**
  95551. * Heightmap-Imposter type
  95552. */
  95553. PhysicsImpostor.HeightmapImpostor = 9;
  95554. return PhysicsImpostor;
  95555. }());
  95556. BABYLON.PhysicsImpostor = PhysicsImpostor;
  95557. })(BABYLON || (BABYLON = {}));
  95558. //# sourceMappingURL=babylon.physicsImpostor.js.map
  95559. var BABYLON;
  95560. (function (BABYLON) {
  95561. /**
  95562. * Class used to control physics engine
  95563. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  95564. */
  95565. var PhysicsEngine = /** @class */ (function () {
  95566. /**
  95567. * Creates a new Physics Engine
  95568. * @param gravity defines the gravity vector used by the simulation
  95569. * @param _physicsPlugin defines the plugin to use (CannonJS by default)
  95570. */
  95571. function PhysicsEngine(gravity, _physicsPlugin) {
  95572. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  95573. this._physicsPlugin = _physicsPlugin;
  95574. this._impostors = [];
  95575. this._joints = [];
  95576. if (!this._physicsPlugin.isSupported()) {
  95577. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  95578. + "Please make sure it is included.");
  95579. }
  95580. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  95581. this.setGravity(gravity);
  95582. this.setTimeStep();
  95583. }
  95584. /**
  95585. * Sets the gravity vector used by the simulation
  95586. * @param gravity defines the gravity vector to use
  95587. */
  95588. PhysicsEngine.prototype.setGravity = function (gravity) {
  95589. this.gravity = gravity;
  95590. this._physicsPlugin.setGravity(this.gravity);
  95591. };
  95592. /**
  95593. * Set the time step of the physics engine.
  95594. * Default is 1/60.
  95595. * To slow it down, enter 1/600 for example.
  95596. * To speed it up, 1/30
  95597. * @param newTimeStep defines the new timestep to apply to this world.
  95598. */
  95599. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  95600. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  95601. this._physicsPlugin.setTimeStep(newTimeStep);
  95602. };
  95603. /**
  95604. * Get the time step of the physics engine.
  95605. * @returns the current time step
  95606. */
  95607. PhysicsEngine.prototype.getTimeStep = function () {
  95608. return this._physicsPlugin.getTimeStep();
  95609. };
  95610. /**
  95611. * Release all resources
  95612. */
  95613. PhysicsEngine.prototype.dispose = function () {
  95614. this._impostors.forEach(function (impostor) {
  95615. impostor.dispose();
  95616. });
  95617. this._physicsPlugin.dispose();
  95618. };
  95619. /**
  95620. * Gets the name of the current physics plugin
  95621. * @returns the name of the plugin
  95622. */
  95623. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  95624. return this._physicsPlugin.name;
  95625. };
  95626. /**
  95627. * Adding a new impostor for the impostor tracking.
  95628. * This will be done by the impostor itself.
  95629. * @param impostor the impostor to add
  95630. */
  95631. PhysicsEngine.prototype.addImpostor = function (impostor) {
  95632. impostor.uniqueId = this._impostors.push(impostor);
  95633. //if no parent, generate the body
  95634. if (!impostor.parent) {
  95635. this._physicsPlugin.generatePhysicsBody(impostor);
  95636. }
  95637. };
  95638. /**
  95639. * Remove an impostor from the engine.
  95640. * This impostor and its mesh will not longer be updated by the physics engine.
  95641. * @param impostor the impostor to remove
  95642. */
  95643. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  95644. var index = this._impostors.indexOf(impostor);
  95645. if (index > -1) {
  95646. var removed = this._impostors.splice(index, 1);
  95647. //Is it needed?
  95648. if (removed.length) {
  95649. //this will also remove it from the world.
  95650. removed[0].physicsBody = null;
  95651. }
  95652. }
  95653. };
  95654. /**
  95655. * Add a joint to the physics engine
  95656. * @param mainImpostor defines the main impostor to which the joint is added.
  95657. * @param connectedImpostor defines the impostor that is connected to the main impostor using this joint
  95658. * @param joint defines the joint that will connect both impostors.
  95659. */
  95660. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  95661. var impostorJoint = {
  95662. mainImpostor: mainImpostor,
  95663. connectedImpostor: connectedImpostor,
  95664. joint: joint
  95665. };
  95666. joint.physicsPlugin = this._physicsPlugin;
  95667. this._joints.push(impostorJoint);
  95668. this._physicsPlugin.generateJoint(impostorJoint);
  95669. };
  95670. /**
  95671. * Removes a joint from the simulation
  95672. * @param mainImpostor defines the impostor used with the joint
  95673. * @param connectedImpostor defines the other impostor connected to the main one by the joint
  95674. * @param joint defines the joint to remove
  95675. */
  95676. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  95677. var matchingJoints = this._joints.filter(function (impostorJoint) {
  95678. return (impostorJoint.connectedImpostor === connectedImpostor
  95679. && impostorJoint.joint === joint
  95680. && impostorJoint.mainImpostor === mainImpostor);
  95681. });
  95682. if (matchingJoints.length) {
  95683. this._physicsPlugin.removeJoint(matchingJoints[0]);
  95684. //TODO remove it from the list as well
  95685. }
  95686. };
  95687. /**
  95688. * Called by the scene. No need to call it.
  95689. * @param delta defines the timespam between frames
  95690. */
  95691. PhysicsEngine.prototype._step = function (delta) {
  95692. var _this = this;
  95693. //check if any mesh has no body / requires an update
  95694. this._impostors.forEach(function (impostor) {
  95695. if (impostor.isBodyInitRequired()) {
  95696. _this._physicsPlugin.generatePhysicsBody(impostor);
  95697. }
  95698. });
  95699. if (delta > 0.1) {
  95700. delta = 0.1;
  95701. }
  95702. else if (delta <= 0) {
  95703. delta = 1.0 / 60.0;
  95704. }
  95705. this._physicsPlugin.executeStep(delta, this._impostors);
  95706. };
  95707. /**
  95708. * Gets the current plugin used to run the simulation
  95709. * @returns current plugin
  95710. */
  95711. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  95712. return this._physicsPlugin;
  95713. };
  95714. /**
  95715. * Gets the list of physic impostors
  95716. * @returns an array of PhysicsImpostor
  95717. */
  95718. PhysicsEngine.prototype.getImpostors = function () {
  95719. return this._impostors;
  95720. };
  95721. /**
  95722. * Gets the impostor for a physics enabled object
  95723. * @param object defines the object impersonated by the impostor
  95724. * @returns the PhysicsImpostor or null if not found
  95725. */
  95726. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  95727. for (var i = 0; i < this._impostors.length; ++i) {
  95728. if (this._impostors[i].object === object) {
  95729. return this._impostors[i];
  95730. }
  95731. }
  95732. return null;
  95733. };
  95734. /**
  95735. * Gets the impostor for a physics body object
  95736. * @param body defines physics body used by the impostor
  95737. * @returns the PhysicsImpostor or null if not found
  95738. */
  95739. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  95740. for (var i = 0; i < this._impostors.length; ++i) {
  95741. if (this._impostors[i].physicsBody === body) {
  95742. return this._impostors[i];
  95743. }
  95744. }
  95745. return null;
  95746. };
  95747. /**
  95748. * Global value used to control the smallest number supported by the simulation
  95749. */
  95750. PhysicsEngine.Epsilon = 0.001;
  95751. return PhysicsEngine;
  95752. }());
  95753. BABYLON.PhysicsEngine = PhysicsEngine;
  95754. })(BABYLON || (BABYLON = {}));
  95755. //# sourceMappingURL=babylon.physicsEngine.js.map
  95756. var BABYLON;
  95757. (function (BABYLON) {
  95758. /**
  95759. * A helper for physics simulations
  95760. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  95761. */
  95762. var PhysicsHelper = /** @class */ (function () {
  95763. /**
  95764. * Initializes the Physics helper
  95765. * @param scene Babylon.js scene
  95766. */
  95767. function PhysicsHelper(scene) {
  95768. this._scene = scene;
  95769. this._physicsEngine = this._scene.getPhysicsEngine();
  95770. if (!this._physicsEngine) {
  95771. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  95772. }
  95773. }
  95774. /**
  95775. * Applies a radial explosion impulse
  95776. * @param origin the origin of the explosion
  95777. * @param radius the explosion radius
  95778. * @param strength the explosion strength
  95779. * @param falloff possible options: Constant & Linear. Defaults to Constant
  95780. * @returns A physics radial explosion event, or null
  95781. */
  95782. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  95783. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  95784. if (!this._physicsEngine) {
  95785. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  95786. return null;
  95787. }
  95788. var impostors = this._physicsEngine.getImpostors();
  95789. if (impostors.length === 0) {
  95790. return null;
  95791. }
  95792. var event = new PhysicsRadialExplosionEvent(this._scene);
  95793. impostors.forEach(function (impostor) {
  95794. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  95795. if (!impostorForceAndContactPoint) {
  95796. return;
  95797. }
  95798. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  95799. });
  95800. event.dispose(false);
  95801. return event;
  95802. };
  95803. /**
  95804. * Applies a radial explosion force
  95805. * @param origin the origin of the explosion
  95806. * @param radius the explosion radius
  95807. * @param strength the explosion strength
  95808. * @param falloff possible options: Constant & Linear. Defaults to Constant
  95809. * @returns A physics radial explosion event, or null
  95810. */
  95811. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  95812. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  95813. if (!this._physicsEngine) {
  95814. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  95815. return null;
  95816. }
  95817. var impostors = this._physicsEngine.getImpostors();
  95818. if (impostors.length === 0) {
  95819. return null;
  95820. }
  95821. var event = new PhysicsRadialExplosionEvent(this._scene);
  95822. impostors.forEach(function (impostor) {
  95823. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  95824. if (!impostorForceAndContactPoint) {
  95825. return;
  95826. }
  95827. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  95828. });
  95829. event.dispose(false);
  95830. return event;
  95831. };
  95832. /**
  95833. * Creates a gravitational field
  95834. * @param origin the origin of the explosion
  95835. * @param radius the explosion radius
  95836. * @param strength the explosion strength
  95837. * @param falloff possible options: Constant & Linear. Defaults to Constant
  95838. * @returns A physics gravitational field event, or null
  95839. */
  95840. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  95841. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  95842. if (!this._physicsEngine) {
  95843. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  95844. return null;
  95845. }
  95846. var impostors = this._physicsEngine.getImpostors();
  95847. if (impostors.length === 0) {
  95848. return null;
  95849. }
  95850. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  95851. event.dispose(false);
  95852. return event;
  95853. };
  95854. /**
  95855. * Creates a physics updraft event
  95856. * @param origin the origin of the updraft
  95857. * @param radius the radius of the updraft
  95858. * @param strength the strength of the updraft
  95859. * @param height the height of the updraft
  95860. * @param updraftMode possible options: Center & Perpendicular. Defaults to Center
  95861. * @returns A physics updraft event, or null
  95862. */
  95863. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  95864. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  95865. if (!this._physicsEngine) {
  95866. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  95867. return null;
  95868. }
  95869. if (this._physicsEngine.getImpostors().length === 0) {
  95870. return null;
  95871. }
  95872. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  95873. event.dispose(false);
  95874. return event;
  95875. };
  95876. /**
  95877. * Creates a physics vortex event
  95878. * @param origin the of the vortex
  95879. * @param radius the radius of the vortex
  95880. * @param strength the strength of the vortex
  95881. * @param height the height of the vortex
  95882. * @returns a Physics vortex event, or null
  95883. * A physics vortex event or null
  95884. */
  95885. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  95886. if (!this._physicsEngine) {
  95887. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  95888. return null;
  95889. }
  95890. if (this._physicsEngine.getImpostors().length === 0) {
  95891. return null;
  95892. }
  95893. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  95894. event.dispose(false);
  95895. return event;
  95896. };
  95897. return PhysicsHelper;
  95898. }());
  95899. BABYLON.PhysicsHelper = PhysicsHelper;
  95900. /**
  95901. * Represents a physics radial explosion event
  95902. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  95903. */
  95904. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  95905. /**
  95906. * Initializes a radial explosioin event
  95907. * @param scene BabylonJS scene
  95908. */
  95909. function PhysicsRadialExplosionEvent(scene) {
  95910. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  95911. this._rays = [];
  95912. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  95913. this._scene = scene;
  95914. }
  95915. /**
  95916. * Returns the data related to the radial explosion event (sphere & rays).
  95917. * @returns The radial explosion event data
  95918. */
  95919. PhysicsRadialExplosionEvent.prototype.getData = function () {
  95920. this._dataFetched = true;
  95921. return {
  95922. sphere: this._sphere,
  95923. rays: this._rays,
  95924. };
  95925. };
  95926. /**
  95927. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  95928. * @param impostor A physics imposter
  95929. * @param origin the origin of the explosion
  95930. * @param radius the explosion radius
  95931. * @param strength the explosion strength
  95932. * @param falloff possible options: Constant & Linear
  95933. * @returns {Nullable<PhysicsForceAndContactPoint>} A physics force and contact point, or null
  95934. */
  95935. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  95936. if (impostor.mass === 0) {
  95937. return null;
  95938. }
  95939. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  95940. return null;
  95941. }
  95942. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  95943. return null;
  95944. }
  95945. var impostorObjectCenter = impostor.getObjectCenter();
  95946. var direction = impostorObjectCenter.subtract(origin);
  95947. var ray = new BABYLON.Ray(origin, direction, radius);
  95948. this._rays.push(ray);
  95949. var hit = ray.intersectsMesh(impostor.object);
  95950. var contactPoint = hit.pickedPoint;
  95951. if (!contactPoint) {
  95952. return null;
  95953. }
  95954. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  95955. if (distanceFromOrigin > radius) {
  95956. return null;
  95957. }
  95958. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  95959. ? strength
  95960. : strength * (1 - (distanceFromOrigin / radius));
  95961. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  95962. return { force: force, contactPoint: contactPoint };
  95963. };
  95964. /**
  95965. * Disposes the sphere.
  95966. * @param force Specifies if the sphere should be disposed by force
  95967. */
  95968. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  95969. var _this = this;
  95970. if (force === void 0) { force = true; }
  95971. if (force) {
  95972. this._sphere.dispose();
  95973. }
  95974. else {
  95975. setTimeout(function () {
  95976. if (!_this._dataFetched) {
  95977. _this._sphere.dispose();
  95978. }
  95979. }, 0);
  95980. }
  95981. };
  95982. /*** Helpers ***/
  95983. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  95984. if (!this._sphere) {
  95985. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  95986. this._sphere.isVisible = false;
  95987. }
  95988. };
  95989. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  95990. var impostorObject = impostor.object;
  95991. this._prepareSphere();
  95992. this._sphere.position = origin;
  95993. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  95994. this._sphere._updateBoundingInfo();
  95995. this._sphere.computeWorldMatrix(true);
  95996. return this._sphere.intersectsMesh(impostorObject, true);
  95997. };
  95998. return PhysicsRadialExplosionEvent;
  95999. }());
  96000. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  96001. /**
  96002. * Represents a gravitational field event
  96003. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  96004. */
  96005. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  96006. /**
  96007. * Initializes the physics gravitational field event
  96008. * @param physicsHelper A physics helper
  96009. * @param scene BabylonJS scene
  96010. * @param origin The origin position of the gravitational field event
  96011. * @param radius The radius of the gravitational field event
  96012. * @param strength The strength of the gravitational field event
  96013. * @param falloff The falloff for the gravitational field event
  96014. */
  96015. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  96016. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  96017. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  96018. this._physicsHelper = physicsHelper;
  96019. this._scene = scene;
  96020. this._origin = origin;
  96021. this._radius = radius;
  96022. this._strength = strength;
  96023. this._falloff = falloff;
  96024. this._tickCallback = this._tick.bind(this);
  96025. }
  96026. /**
  96027. * Returns the data related to the gravitational field event (sphere).
  96028. * @returns A gravitational field event
  96029. */
  96030. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  96031. this._dataFetched = true;
  96032. return {
  96033. sphere: this._sphere,
  96034. };
  96035. };
  96036. /**
  96037. * Enables the gravitational field.
  96038. */
  96039. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  96040. this._tickCallback.call(this);
  96041. this._scene.registerBeforeRender(this._tickCallback);
  96042. };
  96043. /**
  96044. * Disables the gravitational field.
  96045. */
  96046. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  96047. this._scene.unregisterBeforeRender(this._tickCallback);
  96048. };
  96049. /**
  96050. * Disposes the sphere.
  96051. * @param force The force to dispose from the gravitational field event
  96052. */
  96053. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  96054. var _this = this;
  96055. if (force === void 0) { force = true; }
  96056. if (force) {
  96057. this._sphere.dispose();
  96058. }
  96059. else {
  96060. setTimeout(function () {
  96061. if (!_this._dataFetched) {
  96062. _this._sphere.dispose();
  96063. }
  96064. }, 0);
  96065. }
  96066. };
  96067. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  96068. // Since the params won't change, we fetch the event only once
  96069. if (this._sphere) {
  96070. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  96071. }
  96072. else {
  96073. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  96074. if (radialExplosionEvent) {
  96075. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  96076. }
  96077. }
  96078. };
  96079. return PhysicsGravitationalFieldEvent;
  96080. }());
  96081. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  96082. /**
  96083. * Represents a physics updraft event
  96084. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  96085. */
  96086. var PhysicsUpdraftEvent = /** @class */ (function () {
  96087. /**
  96088. * Initializes the physics updraft event
  96089. * @param _scene BabylonJS scene
  96090. * @param _origin The origin position of the updraft
  96091. * @param _radius The radius of the updraft
  96092. * @param _strength The strength of the updraft
  96093. * @param _height The height of the updraft
  96094. * @param _updraftMode The mode of the updraft
  96095. */
  96096. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  96097. this._scene = _scene;
  96098. this._origin = _origin;
  96099. this._radius = _radius;
  96100. this._strength = _strength;
  96101. this._height = _height;
  96102. this._updraftMode = _updraftMode;
  96103. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  96104. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  96105. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  96106. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  96107. this._physicsEngine = this._scene.getPhysicsEngine();
  96108. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  96109. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  96110. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  96111. this._originDirection = this._origin.subtract(this._originTop).normalize();
  96112. }
  96113. this._tickCallback = this._tick.bind(this);
  96114. }
  96115. /**
  96116. * Returns the data related to the updraft event (cylinder).
  96117. * @returns A physics updraft event
  96118. */
  96119. PhysicsUpdraftEvent.prototype.getData = function () {
  96120. this._dataFetched = true;
  96121. return {
  96122. cylinder: this._cylinder,
  96123. };
  96124. };
  96125. /**
  96126. * Enables the updraft.
  96127. */
  96128. PhysicsUpdraftEvent.prototype.enable = function () {
  96129. this._tickCallback.call(this);
  96130. this._scene.registerBeforeRender(this._tickCallback);
  96131. };
  96132. /**
  96133. * Disables the cortex.
  96134. */
  96135. PhysicsUpdraftEvent.prototype.disable = function () {
  96136. this._scene.unregisterBeforeRender(this._tickCallback);
  96137. };
  96138. /**
  96139. * Disposes the sphere.
  96140. * @param force Specifies if the updraft should be disposed by force
  96141. */
  96142. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  96143. var _this = this;
  96144. if (force === void 0) { force = true; }
  96145. if (force) {
  96146. this._cylinder.dispose();
  96147. }
  96148. else {
  96149. setTimeout(function () {
  96150. if (!_this._dataFetched) {
  96151. _this._cylinder.dispose();
  96152. }
  96153. }, 0);
  96154. }
  96155. };
  96156. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  96157. if (impostor.mass === 0) {
  96158. return null;
  96159. }
  96160. if (!this._intersectsWithCylinder(impostor)) {
  96161. return null;
  96162. }
  96163. var impostorObjectCenter = impostor.getObjectCenter();
  96164. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  96165. var direction = this._originDirection;
  96166. }
  96167. else {
  96168. var direction = impostorObjectCenter.subtract(this._originTop);
  96169. }
  96170. var multiplier = this._strength * -1;
  96171. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  96172. return { force: force, contactPoint: impostorObjectCenter };
  96173. };
  96174. PhysicsUpdraftEvent.prototype._tick = function () {
  96175. var _this = this;
  96176. this._physicsEngine.getImpostors().forEach(function (impostor) {
  96177. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  96178. if (!impostorForceAndContactPoint) {
  96179. return;
  96180. }
  96181. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  96182. });
  96183. };
  96184. /*** Helpers ***/
  96185. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  96186. if (!this._cylinder) {
  96187. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  96188. height: this._height,
  96189. diameter: this._radius * 2,
  96190. }, this._scene);
  96191. this._cylinder.isVisible = false;
  96192. }
  96193. };
  96194. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  96195. var impostorObject = impostor.object;
  96196. this._prepareCylinder();
  96197. this._cylinder.position = this._cylinderPosition;
  96198. return this._cylinder.intersectsMesh(impostorObject, true);
  96199. };
  96200. return PhysicsUpdraftEvent;
  96201. }());
  96202. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  96203. /**
  96204. * Represents a physics vortex event
  96205. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  96206. */
  96207. var PhysicsVortexEvent = /** @class */ (function () {
  96208. /**
  96209. * Initializes the physics vortex event
  96210. * @param _scene The BabylonJS scene
  96211. * @param _origin The origin position of the vortex
  96212. * @param _radius The radius of the vortex
  96213. * @param _strength The strength of the vortex
  96214. * @param _height The height of the vortex
  96215. */
  96216. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  96217. this._scene = _scene;
  96218. this._origin = _origin;
  96219. this._radius = _radius;
  96220. this._strength = _strength;
  96221. this._height = _height;
  96222. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  96223. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  96224. this._updraftMultiplier = 0.02;
  96225. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  96226. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  96227. this._physicsEngine = this._scene.getPhysicsEngine();
  96228. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  96229. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  96230. this._tickCallback = this._tick.bind(this);
  96231. }
  96232. /**
  96233. * Returns the data related to the vortex event (cylinder).
  96234. * @returns The physics vortex event data
  96235. */
  96236. PhysicsVortexEvent.prototype.getData = function () {
  96237. this._dataFetched = true;
  96238. return {
  96239. cylinder: this._cylinder,
  96240. };
  96241. };
  96242. /**
  96243. * Enables the vortex.
  96244. */
  96245. PhysicsVortexEvent.prototype.enable = function () {
  96246. this._tickCallback.call(this);
  96247. this._scene.registerBeforeRender(this._tickCallback);
  96248. };
  96249. /**
  96250. * Disables the cortex.
  96251. */
  96252. PhysicsVortexEvent.prototype.disable = function () {
  96253. this._scene.unregisterBeforeRender(this._tickCallback);
  96254. };
  96255. /**
  96256. * Disposes the sphere.
  96257. * @param force
  96258. */
  96259. PhysicsVortexEvent.prototype.dispose = function (force) {
  96260. var _this = this;
  96261. if (force === void 0) { force = true; }
  96262. if (force) {
  96263. this._cylinder.dispose();
  96264. }
  96265. else {
  96266. setTimeout(function () {
  96267. if (!_this._dataFetched) {
  96268. _this._cylinder.dispose();
  96269. }
  96270. }, 0);
  96271. }
  96272. };
  96273. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  96274. if (impostor.mass === 0) {
  96275. return null;
  96276. }
  96277. if (!this._intersectsWithCylinder(impostor)) {
  96278. return null;
  96279. }
  96280. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  96281. return null;
  96282. }
  96283. var impostorObjectCenter = impostor.getObjectCenter();
  96284. 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)
  96285. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  96286. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  96287. var hit = ray.intersectsMesh(impostor.object);
  96288. var contactPoint = hit.pickedPoint;
  96289. if (!contactPoint) {
  96290. return null;
  96291. }
  96292. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  96293. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  96294. var directionToOrigin = contactPoint.normalize();
  96295. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  96296. directionToOrigin = directionToOrigin.negate();
  96297. }
  96298. // TODO: find a more physically based solution
  96299. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  96300. var forceX = directionToOrigin.x * this._strength / 8;
  96301. var forceY = directionToOrigin.y * this._updraftMultiplier;
  96302. var forceZ = directionToOrigin.z * this._strength / 8;
  96303. }
  96304. else {
  96305. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  96306. var forceY = this._originTop.y * this._updraftMultiplier;
  96307. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  96308. }
  96309. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  96310. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  96311. return { force: force, contactPoint: impostorObjectCenter };
  96312. };
  96313. PhysicsVortexEvent.prototype._tick = function () {
  96314. var _this = this;
  96315. this._physicsEngine.getImpostors().forEach(function (impostor) {
  96316. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  96317. if (!impostorForceAndContactPoint) {
  96318. return;
  96319. }
  96320. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  96321. });
  96322. };
  96323. /*** Helpers ***/
  96324. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  96325. if (!this._cylinder) {
  96326. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  96327. height: this._height,
  96328. diameter: this._radius * 2,
  96329. }, this._scene);
  96330. this._cylinder.isVisible = false;
  96331. }
  96332. };
  96333. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  96334. var impostorObject = impostor.object;
  96335. this._prepareCylinder();
  96336. this._cylinder.position = this._cylinderPosition;
  96337. return this._cylinder.intersectsMesh(impostorObject, true);
  96338. };
  96339. return PhysicsVortexEvent;
  96340. }());
  96341. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  96342. /**
  96343. * The strenght of the force in correspondence to the distance of the affected object
  96344. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  96345. */
  96346. var PhysicsRadialImpulseFalloff;
  96347. (function (PhysicsRadialImpulseFalloff) {
  96348. /** Defines that impulse is constant in strength across it's whole radius */
  96349. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  96350. /** DEfines that impulse gets weaker if it's further from the origin */
  96351. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  96352. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  96353. /**
  96354. * The strength of the force in correspondence to the distance of the affected object
  96355. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  96356. */
  96357. var PhysicsUpdraftMode;
  96358. (function (PhysicsUpdraftMode) {
  96359. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  96360. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  96361. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  96362. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  96363. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  96364. })(BABYLON || (BABYLON = {}));
  96365. //# sourceMappingURL=babylon.physicsHelper.js.map
  96366. var BABYLON;
  96367. (function (BABYLON) {
  96368. /** @hidden */
  96369. var CannonJSPlugin = /** @class */ (function () {
  96370. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  96371. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  96372. if (iterations === void 0) { iterations = 10; }
  96373. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  96374. this.name = "CannonJSPlugin";
  96375. this._physicsMaterials = new Array();
  96376. this._fixedTimeStep = 1 / 60;
  96377. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  96378. this.BJSCANNON = CANNON;
  96379. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  96380. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  96381. this._tmpPosition = BABYLON.Vector3.Zero();
  96382. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  96383. this._tmpUnityRotation = new BABYLON.Quaternion();
  96384. if (!this.isSupported()) {
  96385. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  96386. return;
  96387. }
  96388. this._extendNamespace();
  96389. this.world = new this.BJSCANNON.World();
  96390. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  96391. this.world.solver.iterations = iterations;
  96392. }
  96393. CannonJSPlugin.prototype.setGravity = function (gravity) {
  96394. this.world.gravity.copy(gravity);
  96395. };
  96396. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  96397. this._fixedTimeStep = timeStep;
  96398. };
  96399. CannonJSPlugin.prototype.getTimeStep = function () {
  96400. return this._fixedTimeStep;
  96401. };
  96402. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  96403. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  96404. };
  96405. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  96406. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  96407. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  96408. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  96409. };
  96410. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  96411. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  96412. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  96413. impostor.physicsBody.applyForce(impulse, worldPoint);
  96414. };
  96415. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  96416. //parent-child relationship. Does this impostor has a parent impostor?
  96417. if (impostor.parent) {
  96418. if (impostor.physicsBody) {
  96419. this.removePhysicsBody(impostor);
  96420. //TODO is that needed?
  96421. impostor.forceUpdate();
  96422. }
  96423. return;
  96424. }
  96425. //should a new body be created for this impostor?
  96426. if (impostor.isBodyInitRequired()) {
  96427. var shape = this._createShape(impostor);
  96428. //unregister events, if body is being changed
  96429. var oldBody = impostor.physicsBody;
  96430. if (oldBody) {
  96431. this.removePhysicsBody(impostor);
  96432. }
  96433. //create the body and material
  96434. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  96435. var bodyCreationObject = {
  96436. mass: impostor.getParam("mass"),
  96437. material: material
  96438. };
  96439. // A simple extend, in case native options were used.
  96440. var nativeOptions = impostor.getParam("nativeOptions");
  96441. for (var key in nativeOptions) {
  96442. if (nativeOptions.hasOwnProperty(key)) {
  96443. bodyCreationObject[key] = nativeOptions[key];
  96444. }
  96445. }
  96446. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  96447. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  96448. this.world.addEventListener("preStep", impostor.beforeStep);
  96449. this.world.addEventListener("postStep", impostor.afterStep);
  96450. impostor.physicsBody.addShape(shape);
  96451. this.world.add(impostor.physicsBody);
  96452. //try to keep the body moving in the right direction by taking old properties.
  96453. //Should be tested!
  96454. if (oldBody) {
  96455. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  96456. impostor.physicsBody[param].copy(oldBody[param]);
  96457. });
  96458. }
  96459. this._processChildMeshes(impostor);
  96460. }
  96461. //now update the body's transformation
  96462. this._updatePhysicsBodyTransformation(impostor);
  96463. };
  96464. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  96465. var _this = this;
  96466. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  96467. var currentRotation = mainImpostor.object.rotationQuaternion;
  96468. if (meshChildren.length) {
  96469. var processMesh = function (localPosition, mesh) {
  96470. if (!currentRotation || !mesh.rotationQuaternion) {
  96471. return;
  96472. }
  96473. var childImpostor = mesh.getPhysicsImpostor();
  96474. if (childImpostor) {
  96475. var parent = childImpostor.parent;
  96476. if (parent !== mainImpostor) {
  96477. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  96478. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  96479. if (childImpostor.physicsBody) {
  96480. _this.removePhysicsBody(childImpostor);
  96481. childImpostor.physicsBody = null;
  96482. }
  96483. childImpostor.parent = mainImpostor;
  96484. childImpostor.resetUpdateFlags();
  96485. 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));
  96486. //Add the mass of the children.
  96487. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  96488. }
  96489. }
  96490. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  96491. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  96492. };
  96493. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  96494. }
  96495. };
  96496. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  96497. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  96498. this.world.removeEventListener("preStep", impostor.beforeStep);
  96499. this.world.removeEventListener("postStep", impostor.afterStep);
  96500. this.world.remove(impostor.physicsBody);
  96501. };
  96502. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  96503. var mainBody = impostorJoint.mainImpostor.physicsBody;
  96504. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  96505. if (!mainBody || !connectedBody) {
  96506. return;
  96507. }
  96508. var constraint;
  96509. var jointData = impostorJoint.joint.jointData;
  96510. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  96511. var constraintData = {
  96512. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  96513. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  96514. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  96515. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  96516. maxForce: jointData.nativeParams.maxForce,
  96517. collideConnected: !!jointData.collision
  96518. };
  96519. switch (impostorJoint.joint.type) {
  96520. case BABYLON.PhysicsJoint.HingeJoint:
  96521. case BABYLON.PhysicsJoint.Hinge2Joint:
  96522. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  96523. break;
  96524. case BABYLON.PhysicsJoint.DistanceJoint:
  96525. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  96526. break;
  96527. case BABYLON.PhysicsJoint.SpringJoint:
  96528. var springData = jointData;
  96529. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  96530. restLength: springData.length,
  96531. stiffness: springData.stiffness,
  96532. damping: springData.damping,
  96533. localAnchorA: constraintData.pivotA,
  96534. localAnchorB: constraintData.pivotB
  96535. });
  96536. break;
  96537. case BABYLON.PhysicsJoint.LockJoint:
  96538. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  96539. break;
  96540. case BABYLON.PhysicsJoint.PointToPointJoint:
  96541. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  96542. default:
  96543. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  96544. break;
  96545. }
  96546. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  96547. constraint.collideConnected = !!jointData.collision;
  96548. impostorJoint.joint.physicsJoint = constraint;
  96549. //don't add spring as constraint, as it is not one.
  96550. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  96551. this.world.addConstraint(constraint);
  96552. }
  96553. else {
  96554. impostorJoint.joint.jointData.forceApplicationCallback = impostorJoint.joint.jointData.forceApplicationCallback || function () {
  96555. constraint.applyForce();
  96556. };
  96557. impostorJoint.mainImpostor.registerAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  96558. }
  96559. };
  96560. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  96561. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  96562. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  96563. }
  96564. else {
  96565. impostorJoint.mainImpostor.unregisterAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  96566. }
  96567. };
  96568. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  96569. var index;
  96570. var mat;
  96571. for (index = 0; index < this._physicsMaterials.length; index++) {
  96572. mat = this._physicsMaterials[index];
  96573. if (mat.friction === friction && mat.restitution === restitution) {
  96574. return mat;
  96575. }
  96576. }
  96577. var currentMat = new this.BJSCANNON.Material(name);
  96578. currentMat.friction = friction;
  96579. currentMat.restitution = restitution;
  96580. this._physicsMaterials.push(currentMat);
  96581. return currentMat;
  96582. };
  96583. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  96584. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  96585. };
  96586. CannonJSPlugin.prototype._createShape = function (impostor) {
  96587. var object = impostor.object;
  96588. var returnValue;
  96589. var extendSize = impostor.getObjectExtendSize();
  96590. switch (impostor.type) {
  96591. case BABYLON.PhysicsImpostor.SphereImpostor:
  96592. var radiusX = extendSize.x;
  96593. var radiusY = extendSize.y;
  96594. var radiusZ = extendSize.z;
  96595. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  96596. break;
  96597. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  96598. case BABYLON.PhysicsImpostor.CylinderImpostor:
  96599. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  96600. break;
  96601. case BABYLON.PhysicsImpostor.BoxImpostor:
  96602. var box = extendSize.scale(0.5);
  96603. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  96604. break;
  96605. case BABYLON.PhysicsImpostor.PlaneImpostor:
  96606. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  96607. returnValue = new this.BJSCANNON.Plane();
  96608. break;
  96609. case BABYLON.PhysicsImpostor.MeshImpostor:
  96610. // should transform the vertex data to world coordinates!!
  96611. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  96612. var rawFaces = object.getIndices ? object.getIndices() : [];
  96613. if (!rawVerts) {
  96614. return;
  96615. }
  96616. // get only scale! so the object could transform correctly.
  96617. var oldPosition = object.position.clone();
  96618. var oldRotation = object.rotation && object.rotation.clone();
  96619. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  96620. object.position.copyFromFloats(0, 0, 0);
  96621. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  96622. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  96623. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  96624. var transform = object.computeWorldMatrix(true);
  96625. // convert rawVerts to object space
  96626. var temp = new Array();
  96627. var index;
  96628. for (index = 0; index < rawVerts.length; index += 3) {
  96629. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  96630. }
  96631. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  96632. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  96633. //now set back the transformation!
  96634. object.position.copyFrom(oldPosition);
  96635. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  96636. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  96637. break;
  96638. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  96639. var oldPosition2 = object.position.clone();
  96640. var oldRotation2 = object.rotation && object.rotation.clone();
  96641. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  96642. object.position.copyFromFloats(0, 0, 0);
  96643. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  96644. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  96645. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  96646. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  96647. returnValue = this._createHeightmap(object);
  96648. object.position.copyFrom(oldPosition2);
  96649. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  96650. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  96651. object.computeWorldMatrix(true);
  96652. break;
  96653. case BABYLON.PhysicsImpostor.ParticleImpostor:
  96654. returnValue = new this.BJSCANNON.Particle();
  96655. break;
  96656. }
  96657. return returnValue;
  96658. };
  96659. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  96660. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  96661. var transform = object.computeWorldMatrix(true);
  96662. // convert rawVerts to object space
  96663. var temp = new Array();
  96664. var index;
  96665. for (index = 0; index < pos.length; index += 3) {
  96666. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  96667. }
  96668. pos = temp;
  96669. var matrix = new Array();
  96670. //For now pointDepth will not be used and will be automatically calculated.
  96671. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  96672. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  96673. var boundingInfo = object.getBoundingInfo();
  96674. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  96675. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  96676. var elementSize = dim * 2 / arraySize;
  96677. for (var i = 0; i < pos.length; i = i + 3) {
  96678. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  96679. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  96680. var y = -pos[i + 2] + minY;
  96681. if (!matrix[x]) {
  96682. matrix[x] = [];
  96683. }
  96684. if (!matrix[x][z]) {
  96685. matrix[x][z] = y;
  96686. }
  96687. matrix[x][z] = Math.max(y, matrix[x][z]);
  96688. }
  96689. for (var x = 0; x <= arraySize; ++x) {
  96690. if (!matrix[x]) {
  96691. var loc = 1;
  96692. while (!matrix[(x + loc) % arraySize]) {
  96693. loc++;
  96694. }
  96695. matrix[x] = matrix[(x + loc) % arraySize].slice();
  96696. //console.log("missing x", x);
  96697. }
  96698. for (var z = 0; z <= arraySize; ++z) {
  96699. if (!matrix[x][z]) {
  96700. var loc = 1;
  96701. var newValue;
  96702. while (newValue === undefined) {
  96703. newValue = matrix[x][(z + loc++) % arraySize];
  96704. }
  96705. matrix[x][z] = newValue;
  96706. }
  96707. }
  96708. }
  96709. var shape = new this.BJSCANNON.Heightfield(matrix, {
  96710. elementSize: elementSize
  96711. });
  96712. //For future reference, needed for body transformation
  96713. shape.minY = minY;
  96714. return shape;
  96715. };
  96716. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  96717. var object = impostor.object;
  96718. //make sure it is updated...
  96719. object.computeWorldMatrix && object.computeWorldMatrix(true);
  96720. // The delta between the mesh position and the mesh bounding box center
  96721. var bInfo = object.getBoundingInfo();
  96722. if (!bInfo) {
  96723. return;
  96724. }
  96725. var center = impostor.getObjectCenter();
  96726. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  96727. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  96728. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  96729. this._tmpPosition.copyFrom(center);
  96730. var quaternion = object.rotationQuaternion;
  96731. if (!quaternion) {
  96732. return;
  96733. }
  96734. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  96735. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  96736. //-90 DEG in X, precalculated
  96737. quaternion = quaternion.multiply(this._minus90X);
  96738. //Invert! (Precalculated, 90 deg in X)
  96739. //No need to clone. this will never change.
  96740. impostor.setDeltaRotation(this._plus90X);
  96741. }
  96742. //If it is a heightfield, if should be centered.
  96743. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  96744. var mesh = object;
  96745. var boundingInfo = mesh.getBoundingInfo();
  96746. //calculate the correct body position:
  96747. var rotationQuaternion = mesh.rotationQuaternion;
  96748. mesh.rotationQuaternion = this._tmpUnityRotation;
  96749. mesh.computeWorldMatrix(true);
  96750. //get original center with no rotation
  96751. var c = center.clone();
  96752. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  96753. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  96754. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  96755. mesh.setPreTransformMatrix(p);
  96756. mesh.computeWorldMatrix(true);
  96757. //calculate the translation
  96758. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  96759. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  96760. //add it inverted to the delta
  96761. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  96762. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  96763. //rotation is back
  96764. mesh.rotationQuaternion = rotationQuaternion;
  96765. mesh.setPreTransformMatrix(oldPivot);
  96766. mesh.computeWorldMatrix(true);
  96767. }
  96768. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  96769. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  96770. //this._tmpPosition.copyFrom(object.position);
  96771. }
  96772. impostor.setDeltaPosition(this._tmpDeltaPosition);
  96773. //Now update the impostor object
  96774. impostor.physicsBody.position.copy(this._tmpPosition);
  96775. impostor.physicsBody.quaternion.copy(quaternion);
  96776. };
  96777. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  96778. impostor.object.position.copyFrom(impostor.physicsBody.position);
  96779. if (impostor.object.rotationQuaternion) {
  96780. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  96781. }
  96782. };
  96783. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  96784. impostor.physicsBody.position.copy(newPosition);
  96785. impostor.physicsBody.quaternion.copy(newRotation);
  96786. };
  96787. CannonJSPlugin.prototype.isSupported = function () {
  96788. return this.BJSCANNON !== undefined;
  96789. };
  96790. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  96791. impostor.physicsBody.velocity.copy(velocity);
  96792. };
  96793. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  96794. impostor.physicsBody.angularVelocity.copy(velocity);
  96795. };
  96796. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  96797. var v = impostor.physicsBody.velocity;
  96798. if (!v) {
  96799. return null;
  96800. }
  96801. return new BABYLON.Vector3(v.x, v.y, v.z);
  96802. };
  96803. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  96804. var v = impostor.physicsBody.angularVelocity;
  96805. if (!v) {
  96806. return null;
  96807. }
  96808. return new BABYLON.Vector3(v.x, v.y, v.z);
  96809. };
  96810. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  96811. impostor.physicsBody.mass = mass;
  96812. impostor.physicsBody.updateMassProperties();
  96813. };
  96814. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  96815. return impostor.physicsBody.mass;
  96816. };
  96817. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  96818. return impostor.physicsBody.material.friction;
  96819. };
  96820. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  96821. impostor.physicsBody.material.friction = friction;
  96822. };
  96823. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  96824. return impostor.physicsBody.material.restitution;
  96825. };
  96826. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  96827. impostor.physicsBody.material.restitution = restitution;
  96828. };
  96829. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  96830. impostor.physicsBody.sleep();
  96831. };
  96832. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  96833. impostor.physicsBody.wakeUp();
  96834. };
  96835. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  96836. joint.physicsJoint.distance = maxDistance;
  96837. };
  96838. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  96839. // if (!motorIndex) {
  96840. // joint.physicsJoint.enableMotor();
  96841. // }
  96842. // }
  96843. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  96844. // if (!motorIndex) {
  96845. // joint.physicsJoint.disableMotor();
  96846. // }
  96847. // }
  96848. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  96849. if (!motorIndex) {
  96850. joint.physicsJoint.enableMotor();
  96851. joint.physicsJoint.setMotorSpeed(speed);
  96852. if (maxForce) {
  96853. this.setLimit(joint, maxForce);
  96854. }
  96855. }
  96856. };
  96857. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  96858. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  96859. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  96860. };
  96861. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  96862. var body = impostor.physicsBody;
  96863. mesh.position.x = body.position.x;
  96864. mesh.position.y = body.position.y;
  96865. mesh.position.z = body.position.z;
  96866. if (mesh.rotationQuaternion) {
  96867. mesh.rotationQuaternion.x = body.quaternion.x;
  96868. mesh.rotationQuaternion.y = body.quaternion.y;
  96869. mesh.rotationQuaternion.z = body.quaternion.z;
  96870. mesh.rotationQuaternion.w = body.quaternion.w;
  96871. }
  96872. };
  96873. CannonJSPlugin.prototype.getRadius = function (impostor) {
  96874. var shape = impostor.physicsBody.shapes[0];
  96875. return shape.boundingSphereRadius;
  96876. };
  96877. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  96878. var shape = impostor.physicsBody.shapes[0];
  96879. result.x = shape.halfExtents.x * 2;
  96880. result.y = shape.halfExtents.y * 2;
  96881. result.z = shape.halfExtents.z * 2;
  96882. };
  96883. CannonJSPlugin.prototype.dispose = function () {
  96884. };
  96885. CannonJSPlugin.prototype._extendNamespace = function () {
  96886. //this will force cannon to execute at least one step when using interpolation
  96887. var step_tmp1 = new this.BJSCANNON.Vec3();
  96888. var Engine = this.BJSCANNON;
  96889. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  96890. maxSubSteps = maxSubSteps || 10;
  96891. timeSinceLastCalled = timeSinceLastCalled || 0;
  96892. if (timeSinceLastCalled === 0) {
  96893. this.internalStep(dt);
  96894. this.time += dt;
  96895. }
  96896. else {
  96897. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  96898. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  96899. var t0 = performance.now();
  96900. for (var i = 0; i !== internalSteps; i++) {
  96901. this.internalStep(dt);
  96902. if (performance.now() - t0 > dt * 1000) {
  96903. break;
  96904. }
  96905. }
  96906. this.time += timeSinceLastCalled;
  96907. var h = this.time % dt;
  96908. var h_div_dt = h / dt;
  96909. var interpvelo = step_tmp1;
  96910. var bodies = this.bodies;
  96911. for (var j = 0; j !== bodies.length; j++) {
  96912. var b = bodies[j];
  96913. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  96914. b.position.vsub(b.previousPosition, interpvelo);
  96915. interpvelo.scale(h_div_dt, interpvelo);
  96916. b.position.vadd(interpvelo, b.interpolatedPosition);
  96917. }
  96918. else {
  96919. b.interpolatedPosition.copy(b.position);
  96920. b.interpolatedQuaternion.copy(b.quaternion);
  96921. }
  96922. }
  96923. }
  96924. };
  96925. };
  96926. return CannonJSPlugin;
  96927. }());
  96928. BABYLON.CannonJSPlugin = CannonJSPlugin;
  96929. })(BABYLON || (BABYLON = {}));
  96930. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  96931. var BABYLON;
  96932. (function (BABYLON) {
  96933. /** @hidden */
  96934. var OimoJSPlugin = /** @class */ (function () {
  96935. function OimoJSPlugin(iterations) {
  96936. this.name = "OimoJSPlugin";
  96937. this._tmpImpostorsArray = [];
  96938. this._tmpPositionVector = BABYLON.Vector3.Zero();
  96939. this.BJSOIMO = OIMO;
  96940. this.world = new this.BJSOIMO.World({
  96941. iterations: iterations
  96942. });
  96943. this.world.clear();
  96944. }
  96945. OimoJSPlugin.prototype.setGravity = function (gravity) {
  96946. this.world.gravity.copy(gravity);
  96947. };
  96948. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  96949. this.world.timeStep = timeStep;
  96950. };
  96951. OimoJSPlugin.prototype.getTimeStep = function () {
  96952. return this.world.timeStep;
  96953. };
  96954. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  96955. var _this = this;
  96956. impostors.forEach(function (impostor) {
  96957. impostor.beforeStep();
  96958. });
  96959. this.world.step();
  96960. impostors.forEach(function (impostor) {
  96961. impostor.afterStep();
  96962. //update the ordered impostors array
  96963. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  96964. });
  96965. //check for collisions
  96966. var contact = this.world.contacts;
  96967. while (contact !== null) {
  96968. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  96969. contact = contact.next;
  96970. continue;
  96971. }
  96972. //is this body colliding with any other? get the impostor
  96973. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  96974. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  96975. if (!mainImpostor || !collidingImpostor) {
  96976. contact = contact.next;
  96977. continue;
  96978. }
  96979. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  96980. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  96981. contact = contact.next;
  96982. }
  96983. };
  96984. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  96985. var mass = impostor.physicsBody.mass;
  96986. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  96987. };
  96988. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  96989. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  96990. this.applyImpulse(impostor, force, contactPoint);
  96991. };
  96992. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  96993. var _this = this;
  96994. //parent-child relationship. Does this impostor has a parent impostor?
  96995. if (impostor.parent) {
  96996. if (impostor.physicsBody) {
  96997. this.removePhysicsBody(impostor);
  96998. //TODO is that needed?
  96999. impostor.forceUpdate();
  97000. }
  97001. return;
  97002. }
  97003. if (impostor.isBodyInitRequired()) {
  97004. var bodyConfig = {
  97005. name: impostor.uniqueId,
  97006. //Oimo must have mass, also for static objects.
  97007. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  97008. size: [],
  97009. type: [],
  97010. pos: [],
  97011. posShape: [],
  97012. rot: [],
  97013. rotShape: [],
  97014. move: impostor.getParam("mass") !== 0,
  97015. density: impostor.getParam("mass"),
  97016. friction: impostor.getParam("friction"),
  97017. restitution: impostor.getParam("restitution"),
  97018. //Supporting older versions of Oimo
  97019. world: this.world
  97020. };
  97021. var impostors = [impostor];
  97022. var addToArray = function (parent) {
  97023. if (!parent.getChildMeshes) {
  97024. return;
  97025. }
  97026. parent.getChildMeshes().forEach(function (m) {
  97027. if (m.physicsImpostor) {
  97028. impostors.push(m.physicsImpostor);
  97029. //m.physicsImpostor._init();
  97030. }
  97031. });
  97032. };
  97033. addToArray(impostor.object);
  97034. var checkWithEpsilon_1 = function (value) {
  97035. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  97036. };
  97037. var globalQuaternion_1 = new BABYLON.Quaternion();
  97038. impostors.forEach(function (i) {
  97039. if (!i.object.rotationQuaternion) {
  97040. return;
  97041. }
  97042. //get the correct bounding box
  97043. var oldQuaternion = i.object.rotationQuaternion;
  97044. globalQuaternion_1 = oldQuaternion.clone();
  97045. var rot = oldQuaternion.toEulerAngles();
  97046. var extendSize = i.getObjectExtendSize();
  97047. var radToDeg = 57.295779513082320876;
  97048. if (i === impostor) {
  97049. var center = impostor.getObjectCenter();
  97050. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  97051. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  97052. //Can also use Array.prototype.push.apply
  97053. bodyConfig.pos.push(center.x);
  97054. bodyConfig.pos.push(center.y);
  97055. bodyConfig.pos.push(center.z);
  97056. bodyConfig.posShape.push(0, 0, 0);
  97057. //tmp solution
  97058. bodyConfig.rot.push(0);
  97059. bodyConfig.rot.push(0);
  97060. bodyConfig.rot.push(0);
  97061. bodyConfig.rotShape.push(0, 0, 0);
  97062. }
  97063. else {
  97064. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  97065. bodyConfig.posShape.push(localPosition.x);
  97066. bodyConfig.posShape.push(localPosition.y);
  97067. bodyConfig.posShape.push(localPosition.z);
  97068. bodyConfig.pos.push(0, 0, 0);
  97069. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  97070. bodyConfig.rot.push(0);
  97071. bodyConfig.rot.push(0);
  97072. bodyConfig.rot.push(0);
  97073. bodyConfig.rotShape.push(rot.x * radToDeg);
  97074. bodyConfig.rotShape.push(rot.y * radToDeg);
  97075. bodyConfig.rotShape.push(rot.z * radToDeg);
  97076. }
  97077. // register mesh
  97078. switch (i.type) {
  97079. case BABYLON.PhysicsImpostor.ParticleImpostor:
  97080. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  97081. case BABYLON.PhysicsImpostor.SphereImpostor:
  97082. var radiusX = extendSize.x;
  97083. var radiusY = extendSize.y;
  97084. var radiusZ = extendSize.z;
  97085. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  97086. bodyConfig.type.push('sphere');
  97087. //due to the way oimo works with compounds, add 3 times
  97088. bodyConfig.size.push(size);
  97089. bodyConfig.size.push(size);
  97090. bodyConfig.size.push(size);
  97091. break;
  97092. case BABYLON.PhysicsImpostor.CylinderImpostor:
  97093. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  97094. var sizeY = checkWithEpsilon_1(extendSize.y);
  97095. bodyConfig.type.push('cylinder');
  97096. bodyConfig.size.push(sizeX);
  97097. bodyConfig.size.push(sizeY);
  97098. //due to the way oimo works with compounds, add one more value.
  97099. bodyConfig.size.push(sizeY);
  97100. break;
  97101. case BABYLON.PhysicsImpostor.PlaneImpostor:
  97102. case BABYLON.PhysicsImpostor.BoxImpostor:
  97103. default:
  97104. var sizeX = checkWithEpsilon_1(extendSize.x);
  97105. var sizeY = checkWithEpsilon_1(extendSize.y);
  97106. var sizeZ = checkWithEpsilon_1(extendSize.z);
  97107. bodyConfig.type.push('box');
  97108. //if (i === impostor) {
  97109. bodyConfig.size.push(sizeX);
  97110. bodyConfig.size.push(sizeY);
  97111. bodyConfig.size.push(sizeZ);
  97112. //} else {
  97113. // bodyConfig.size.push(0,0,0);
  97114. //}
  97115. break;
  97116. }
  97117. //actually not needed, but hey...
  97118. i.object.rotationQuaternion = oldQuaternion;
  97119. });
  97120. impostor.physicsBody = this.world.add(bodyConfig);
  97121. // set the quaternion, ignoring the previously defined (euler) rotation
  97122. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  97123. // update with delta 0, so the body will reveive the new rotation.
  97124. impostor.physicsBody.updatePosition(0);
  97125. }
  97126. else {
  97127. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  97128. }
  97129. impostor.setDeltaPosition(this._tmpPositionVector);
  97130. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  97131. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  97132. };
  97133. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  97134. //impostor.physicsBody.dispose();
  97135. //Same as : (older oimo versions)
  97136. this.world.removeRigidBody(impostor.physicsBody);
  97137. };
  97138. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  97139. var mainBody = impostorJoint.mainImpostor.physicsBody;
  97140. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  97141. if (!mainBody || !connectedBody) {
  97142. return;
  97143. }
  97144. var jointData = impostorJoint.joint.jointData;
  97145. var options = jointData.nativeParams || {};
  97146. var type;
  97147. var nativeJointData = {
  97148. body1: mainBody,
  97149. body2: connectedBody,
  97150. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  97151. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  97152. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  97153. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  97154. min: options.min,
  97155. max: options.max,
  97156. collision: options.collision || jointData.collision,
  97157. spring: options.spring,
  97158. //supporting older version of Oimo
  97159. world: this.world
  97160. };
  97161. switch (impostorJoint.joint.type) {
  97162. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  97163. type = "jointBall";
  97164. break;
  97165. case BABYLON.PhysicsJoint.SpringJoint:
  97166. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  97167. var springData = jointData;
  97168. nativeJointData.min = springData.length || nativeJointData.min;
  97169. //Max should also be set, just make sure it is at least min
  97170. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  97171. case BABYLON.PhysicsJoint.DistanceJoint:
  97172. type = "jointDistance";
  97173. nativeJointData.max = jointData.maxDistance;
  97174. break;
  97175. case BABYLON.PhysicsJoint.PrismaticJoint:
  97176. type = "jointPrisme";
  97177. break;
  97178. case BABYLON.PhysicsJoint.SliderJoint:
  97179. type = "jointSlide";
  97180. break;
  97181. case BABYLON.PhysicsJoint.WheelJoint:
  97182. type = "jointWheel";
  97183. break;
  97184. case BABYLON.PhysicsJoint.HingeJoint:
  97185. default:
  97186. type = "jointHinge";
  97187. break;
  97188. }
  97189. nativeJointData.type = type;
  97190. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  97191. };
  97192. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  97193. //Bug in Oimo prevents us from disposing a joint in the playground
  97194. //joint.joint.physicsJoint.dispose();
  97195. //So we will bruteforce it!
  97196. try {
  97197. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  97198. }
  97199. catch (e) {
  97200. BABYLON.Tools.Warn(e);
  97201. }
  97202. };
  97203. OimoJSPlugin.prototype.isSupported = function () {
  97204. return this.BJSOIMO !== undefined;
  97205. };
  97206. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  97207. if (!impostor.physicsBody.sleeping) {
  97208. //TODO check that
  97209. /*if (impostor.physicsBody.shapes.next) {
  97210. var parentShape = this._getLastShape(impostor.physicsBody);
  97211. impostor.object.position.copyFrom(parentShape.position);
  97212. console.log(parentShape.position);
  97213. } else {*/
  97214. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  97215. //}
  97216. if (impostor.object.rotationQuaternion) {
  97217. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  97218. }
  97219. }
  97220. };
  97221. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  97222. var body = impostor.physicsBody;
  97223. body.position.copy(newPosition);
  97224. body.orientation.copy(newRotation);
  97225. body.syncShapes();
  97226. body.awake();
  97227. };
  97228. /*private _getLastShape(body: any): any {
  97229. var lastShape = body.shapes;
  97230. while (lastShape.next) {
  97231. lastShape = lastShape.next;
  97232. }
  97233. return lastShape;
  97234. }*/
  97235. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  97236. impostor.physicsBody.linearVelocity.copy(velocity);
  97237. };
  97238. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  97239. impostor.physicsBody.angularVelocity.copy(velocity);
  97240. };
  97241. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  97242. var v = impostor.physicsBody.linearVelocity;
  97243. if (!v) {
  97244. return null;
  97245. }
  97246. return new BABYLON.Vector3(v.x, v.y, v.z);
  97247. };
  97248. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  97249. var v = impostor.physicsBody.angularVelocity;
  97250. if (!v) {
  97251. return null;
  97252. }
  97253. return new BABYLON.Vector3(v.x, v.y, v.z);
  97254. };
  97255. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  97256. var staticBody = mass === 0;
  97257. //this will actually set the body's density and not its mass.
  97258. //But this is how oimo treats the mass variable.
  97259. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  97260. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  97261. };
  97262. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  97263. return impostor.physicsBody.shapes.density;
  97264. };
  97265. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  97266. return impostor.physicsBody.shapes.friction;
  97267. };
  97268. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  97269. impostor.physicsBody.shapes.friction = friction;
  97270. };
  97271. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  97272. return impostor.physicsBody.shapes.restitution;
  97273. };
  97274. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  97275. impostor.physicsBody.shapes.restitution = restitution;
  97276. };
  97277. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  97278. impostor.physicsBody.sleep();
  97279. };
  97280. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  97281. impostor.physicsBody.awake();
  97282. };
  97283. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  97284. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  97285. if (minDistance !== void 0) {
  97286. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  97287. }
  97288. };
  97289. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  97290. //TODO separate rotational and transational motors.
  97291. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  97292. if (motor) {
  97293. motor.setMotor(speed, maxForce);
  97294. }
  97295. };
  97296. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  97297. //TODO separate rotational and transational motors.
  97298. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  97299. if (motor) {
  97300. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  97301. }
  97302. };
  97303. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  97304. var body = impostor.physicsBody;
  97305. mesh.position.x = body.position.x;
  97306. mesh.position.y = body.position.y;
  97307. mesh.position.z = body.position.z;
  97308. if (mesh.rotationQuaternion) {
  97309. mesh.rotationQuaternion.x = body.orientation.x;
  97310. mesh.rotationQuaternion.y = body.orientation.y;
  97311. mesh.rotationQuaternion.z = body.orientation.z;
  97312. mesh.rotationQuaternion.w = body.orientation.s;
  97313. }
  97314. };
  97315. OimoJSPlugin.prototype.getRadius = function (impostor) {
  97316. return impostor.physicsBody.shapes.radius;
  97317. };
  97318. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  97319. var shape = impostor.physicsBody.shapes;
  97320. result.x = shape.halfWidth * 2;
  97321. result.y = shape.halfHeight * 2;
  97322. result.z = shape.halfDepth * 2;
  97323. };
  97324. OimoJSPlugin.prototype.dispose = function () {
  97325. this.world.clear();
  97326. };
  97327. return OimoJSPlugin;
  97328. }());
  97329. BABYLON.OimoJSPlugin = OimoJSPlugin;
  97330. })(BABYLON || (BABYLON = {}));
  97331. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  97332. var BABYLON;
  97333. (function (BABYLON) {
  97334. /**
  97335. * Gets the current physics engine
  97336. * @returns a IPhysicsEngine or null if none attached
  97337. */
  97338. BABYLON.Scene.prototype.getPhysicsEngine = function () {
  97339. return this._physicsEngine;
  97340. };
  97341. /**
  97342. * Enables physics to the current scene
  97343. * @param gravity defines the scene's gravity for the physics engine
  97344. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  97345. * @return a boolean indicating if the physics engine was initialized
  97346. */
  97347. BABYLON.Scene.prototype.enablePhysics = function (gravity, plugin) {
  97348. if (gravity === void 0) { gravity = null; }
  97349. if (this._physicsEngine) {
  97350. return true;
  97351. }
  97352. // Register the component to the scene
  97353. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE);
  97354. if (!component) {
  97355. component = new PhysicsEngineSceneComponent(this);
  97356. this._addComponent(component);
  97357. }
  97358. try {
  97359. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  97360. return true;
  97361. }
  97362. catch (e) {
  97363. BABYLON.Tools.Error(e.message);
  97364. return false;
  97365. }
  97366. };
  97367. /**
  97368. * Disables and disposes the physics engine associated with the scene
  97369. */
  97370. BABYLON.Scene.prototype.disablePhysicsEngine = function () {
  97371. if (!this._physicsEngine) {
  97372. return;
  97373. }
  97374. this._physicsEngine.dispose();
  97375. this._physicsEngine = null;
  97376. };
  97377. /**
  97378. * Gets a boolean indicating if there is an active physics engine
  97379. * @returns a boolean indicating if there is an active physics engine
  97380. */
  97381. BABYLON.Scene.prototype.isPhysicsEnabled = function () {
  97382. return this._physicsEngine !== undefined;
  97383. };
  97384. /**
  97385. * Deletes a physics compound impostor
  97386. * @param compound defines the compound to delete
  97387. */
  97388. BABYLON.Scene.prototype.deleteCompoundImpostor = function (compound) {
  97389. var mesh = compound.parts[0].mesh;
  97390. if (mesh.physicsImpostor) {
  97391. mesh.physicsImpostor.dispose( /*true*/);
  97392. mesh.physicsImpostor = null;
  97393. }
  97394. };
  97395. /** @hidden */
  97396. BABYLON.Scene.prototype._advancePhysicsEngineStep = function (step) {
  97397. if (this._physicsEngine) {
  97398. this.onBeforePhysicsObservable.notifyObservers(this);
  97399. this._physicsEngine._step(step / 1000);
  97400. this.onAfterPhysicsObservable.notifyObservers(this);
  97401. }
  97402. };
  97403. Object.defineProperty(BABYLON.AbstractMesh.prototype, "physicsImpostor", {
  97404. get: function () {
  97405. return this._physicsImpostor;
  97406. },
  97407. set: function (value) {
  97408. var _this = this;
  97409. if (this._physicsImpostor === value) {
  97410. return;
  97411. }
  97412. if (this._disposePhysicsObserver) {
  97413. this.onDisposeObservable.remove(this._disposePhysicsObserver);
  97414. }
  97415. this._physicsImpostor = value;
  97416. if (value) {
  97417. this._disposePhysicsObserver = this.onDisposeObservable.add(function () {
  97418. // Physics
  97419. if (_this.physicsImpostor) {
  97420. _this.physicsImpostor.dispose( /*!doNotRecurse*/);
  97421. _this.physicsImpostor = null;
  97422. }
  97423. });
  97424. }
  97425. },
  97426. enumerable: true,
  97427. configurable: true
  97428. });
  97429. /**
  97430. * Gets the current physics impostor
  97431. * @see http://doc.babylonjs.com/features/physics_engine
  97432. * @returns a physics impostor or null
  97433. */
  97434. BABYLON.AbstractMesh.prototype.getPhysicsImpostor = function () {
  97435. return this.physicsImpostor;
  97436. };
  97437. /**
  97438. * Apply a physic impulse to the mesh
  97439. * @param force defines the force to apply
  97440. * @param contactPoint defines where to apply the force
  97441. * @returns the current mesh
  97442. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  97443. */
  97444. BABYLON.AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  97445. if (!this.physicsImpostor) {
  97446. return this;
  97447. }
  97448. this.physicsImpostor.applyImpulse(force, contactPoint);
  97449. return this;
  97450. };
  97451. /**
  97452. * Creates a physic joint between two meshes
  97453. * @param otherMesh defines the other mesh to use
  97454. * @param pivot1 defines the pivot to use on this mesh
  97455. * @param pivot2 defines the pivot to use on the other mesh
  97456. * @param options defines additional options (can be plugin dependent)
  97457. * @returns the current mesh
  97458. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  97459. */
  97460. BABYLON.AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  97461. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  97462. return this;
  97463. }
  97464. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  97465. mainPivot: pivot1,
  97466. connectedPivot: pivot2,
  97467. nativeParams: options
  97468. });
  97469. return this;
  97470. };
  97471. /**
  97472. * Defines the physics engine scene component responsible to manage a physics engine
  97473. */
  97474. var PhysicsEngineSceneComponent = /** @class */ (function () {
  97475. /**
  97476. * Creates a new instance of the component for the given scene
  97477. * @param scene Defines the scene to register the component in
  97478. */
  97479. function PhysicsEngineSceneComponent(scene) {
  97480. var _this = this;
  97481. /**
  97482. * The component name helpful to identify the component in the list of scene components.
  97483. */
  97484. this.name = BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE;
  97485. this.scene = scene;
  97486. this.scene.onBeforePhysicsObservable = new BABYLON.Observable();
  97487. this.scene.onAfterPhysicsObservable = new BABYLON.Observable();
  97488. // Replace the function used to get the deterministic frame time
  97489. this.scene.getDeterministicFrameTime = function () {
  97490. if (_this.scene._physicsEngine) {
  97491. return _this.scene._physicsEngine.getTimeStep() * 1000;
  97492. }
  97493. return 1000.0 / 60.0;
  97494. };
  97495. }
  97496. /**
  97497. * Registers the component in a given scene
  97498. */
  97499. PhysicsEngineSceneComponent.prototype.register = function () {
  97500. };
  97501. /**
  97502. * Rebuilds the elements related to this component in case of
  97503. * context lost for instance.
  97504. */
  97505. PhysicsEngineSceneComponent.prototype.rebuild = function () {
  97506. // Nothing to do for this component
  97507. };
  97508. /**
  97509. * Disposes the component and the associated ressources
  97510. */
  97511. PhysicsEngineSceneComponent.prototype.dispose = function () {
  97512. this.scene.onBeforePhysicsObservable.clear();
  97513. this.scene.onAfterPhysicsObservable.clear();
  97514. if (this.scene._physicsEngine) {
  97515. this.scene.disablePhysicsEngine();
  97516. }
  97517. };
  97518. return PhysicsEngineSceneComponent;
  97519. }());
  97520. BABYLON.PhysicsEngineSceneComponent = PhysicsEngineSceneComponent;
  97521. })(BABYLON || (BABYLON = {}));
  97522. //# sourceMappingURL=babylon.physicsEngineComponent.js.map
  97523. var BABYLON;
  97524. (function (BABYLON) {
  97525. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  97526. // All values and structures referenced from:
  97527. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  97528. var DDS_MAGIC = 0x20534444;
  97529. var
  97530. //DDSD_CAPS = 0x1,
  97531. //DDSD_HEIGHT = 0x2,
  97532. //DDSD_WIDTH = 0x4,
  97533. //DDSD_PITCH = 0x8,
  97534. //DDSD_PIXELFORMAT = 0x1000,
  97535. DDSD_MIPMAPCOUNT = 0x20000;
  97536. //DDSD_LINEARSIZE = 0x80000,
  97537. //DDSD_DEPTH = 0x800000;
  97538. // var DDSCAPS_COMPLEX = 0x8,
  97539. // DDSCAPS_MIPMAP = 0x400000,
  97540. // DDSCAPS_TEXTURE = 0x1000;
  97541. var DDSCAPS2_CUBEMAP = 0x200;
  97542. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  97543. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  97544. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  97545. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  97546. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  97547. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  97548. // DDSCAPS2_VOLUME = 0x200000;
  97549. var
  97550. //DDPF_ALPHAPIXELS = 0x1,
  97551. //DDPF_ALPHA = 0x2,
  97552. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  97553. //DDPF_YUV = 0x200,
  97554. DDPF_LUMINANCE = 0x20000;
  97555. function FourCCToInt32(value) {
  97556. return value.charCodeAt(0) +
  97557. (value.charCodeAt(1) << 8) +
  97558. (value.charCodeAt(2) << 16) +
  97559. (value.charCodeAt(3) << 24);
  97560. }
  97561. function Int32ToFourCC(value) {
  97562. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  97563. }
  97564. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  97565. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  97566. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  97567. var FOURCC_DX10 = FourCCToInt32("DX10");
  97568. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  97569. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  97570. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  97571. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  97572. var headerLengthInt = 31; // The header length in 32 bit ints
  97573. // Offsets into the header array
  97574. var off_magic = 0;
  97575. var off_size = 1;
  97576. var off_flags = 2;
  97577. var off_height = 3;
  97578. var off_width = 4;
  97579. var off_mipmapCount = 7;
  97580. var off_pfFlags = 20;
  97581. var off_pfFourCC = 21;
  97582. var off_RGBbpp = 22;
  97583. var off_RMask = 23;
  97584. var off_GMask = 24;
  97585. var off_BMask = 25;
  97586. var off_AMask = 26;
  97587. // var off_caps1 = 27;
  97588. var off_caps2 = 28;
  97589. // var off_caps3 = 29;
  97590. // var off_caps4 = 30;
  97591. var off_dxgiFormat = 32;
  97592. /**
  97593. * Class used to provide DDS decompression tools
  97594. */
  97595. var DDSTools = /** @class */ (function () {
  97596. function DDSTools() {
  97597. }
  97598. /**
  97599. * Gets DDS information from an array buffer
  97600. * @param arrayBuffer defines the array buffer to read data from
  97601. * @returns the DDS information
  97602. */
  97603. DDSTools.GetDDSInfo = function (arrayBuffer) {
  97604. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  97605. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  97606. var mipmapCount = 1;
  97607. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  97608. mipmapCount = Math.max(1, header[off_mipmapCount]);
  97609. }
  97610. var fourCC = header[off_pfFourCC];
  97611. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  97612. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97613. switch (fourCC) {
  97614. case FOURCC_D3DFMT_R16G16B16A16F:
  97615. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97616. break;
  97617. case FOURCC_D3DFMT_R32G32B32A32F:
  97618. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  97619. break;
  97620. case FOURCC_DX10:
  97621. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  97622. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97623. break;
  97624. }
  97625. }
  97626. return {
  97627. width: header[off_width],
  97628. height: header[off_height],
  97629. mipmapCount: mipmapCount,
  97630. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  97631. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  97632. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  97633. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  97634. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  97635. dxgiFormat: dxgiFormat,
  97636. textureType: textureType
  97637. };
  97638. };
  97639. DDSTools._ToHalfFloat = function (value) {
  97640. if (!DDSTools._FloatView) {
  97641. DDSTools._FloatView = new Float32Array(1);
  97642. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  97643. }
  97644. DDSTools._FloatView[0] = value;
  97645. var x = DDSTools._Int32View[0];
  97646. var bits = (x >> 16) & 0x8000; /* Get the sign */
  97647. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  97648. var e = (x >> 23) & 0xff; /* Using int is faster here */
  97649. /* If zero, or denormal, or exponent underflows too much for a denormal
  97650. * half, return signed zero. */
  97651. if (e < 103) {
  97652. return bits;
  97653. }
  97654. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  97655. if (e > 142) {
  97656. bits |= 0x7c00;
  97657. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  97658. * not Inf, so make sure we set one mantissa bit too. */
  97659. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  97660. return bits;
  97661. }
  97662. /* If exponent underflows but not too much, return a denormal */
  97663. if (e < 113) {
  97664. m |= 0x0800;
  97665. /* Extra rounding may overflow and set mantissa to 0 and exponent
  97666. * to 1, which is OK. */
  97667. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  97668. return bits;
  97669. }
  97670. bits |= ((e - 112) << 10) | (m >> 1);
  97671. bits += m & 1;
  97672. return bits;
  97673. };
  97674. DDSTools._FromHalfFloat = function (value) {
  97675. var s = (value & 0x8000) >> 15;
  97676. var e = (value & 0x7C00) >> 10;
  97677. var f = value & 0x03FF;
  97678. if (e === 0) {
  97679. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  97680. }
  97681. else if (e == 0x1F) {
  97682. return f ? NaN : ((s ? -1 : 1) * Infinity);
  97683. }
  97684. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  97685. };
  97686. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  97687. var destArray = new Float32Array(dataLength);
  97688. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  97689. var index = 0;
  97690. for (var y = 0; y < height; y++) {
  97691. for (var x = 0; x < width; x++) {
  97692. var srcPos = (x + y * width) * 4;
  97693. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  97694. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  97695. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  97696. if (DDSTools.StoreLODInAlphaChannel) {
  97697. destArray[index + 3] = lod;
  97698. }
  97699. else {
  97700. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  97701. }
  97702. index += 4;
  97703. }
  97704. }
  97705. return destArray;
  97706. };
  97707. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  97708. if (DDSTools.StoreLODInAlphaChannel) {
  97709. var destArray = new Uint16Array(dataLength);
  97710. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  97711. var index = 0;
  97712. for (var y = 0; y < height; y++) {
  97713. for (var x = 0; x < width; x++) {
  97714. var srcPos = (x + y * width) * 4;
  97715. destArray[index] = srcData[srcPos];
  97716. destArray[index + 1] = srcData[srcPos + 1];
  97717. destArray[index + 2] = srcData[srcPos + 2];
  97718. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  97719. index += 4;
  97720. }
  97721. }
  97722. return destArray;
  97723. }
  97724. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  97725. };
  97726. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  97727. if (DDSTools.StoreLODInAlphaChannel) {
  97728. var destArray = new Float32Array(dataLength);
  97729. var srcData = new Float32Array(arrayBuffer, dataOffset);
  97730. var index = 0;
  97731. for (var y = 0; y < height; y++) {
  97732. for (var x = 0; x < width; x++) {
  97733. var srcPos = (x + y * width) * 4;
  97734. destArray[index] = srcData[srcPos];
  97735. destArray[index + 1] = srcData[srcPos + 1];
  97736. destArray[index + 2] = srcData[srcPos + 2];
  97737. destArray[index + 3] = lod;
  97738. index += 4;
  97739. }
  97740. }
  97741. return destArray;
  97742. }
  97743. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  97744. };
  97745. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  97746. var destArray = new Uint8Array(dataLength);
  97747. var srcData = new Float32Array(arrayBuffer, dataOffset);
  97748. var index = 0;
  97749. for (var y = 0; y < height; y++) {
  97750. for (var x = 0; x < width; x++) {
  97751. var srcPos = (x + y * width) * 4;
  97752. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  97753. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  97754. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  97755. if (DDSTools.StoreLODInAlphaChannel) {
  97756. destArray[index + 3] = lod;
  97757. }
  97758. else {
  97759. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  97760. }
  97761. index += 4;
  97762. }
  97763. }
  97764. return destArray;
  97765. };
  97766. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  97767. var destArray = new Uint8Array(dataLength);
  97768. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  97769. var index = 0;
  97770. for (var y = 0; y < height; y++) {
  97771. for (var x = 0; x < width; x++) {
  97772. var srcPos = (x + y * width) * 4;
  97773. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  97774. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  97775. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  97776. if (DDSTools.StoreLODInAlphaChannel) {
  97777. destArray[index + 3] = lod;
  97778. }
  97779. else {
  97780. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  97781. }
  97782. index += 4;
  97783. }
  97784. }
  97785. return destArray;
  97786. };
  97787. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  97788. var byteArray = new Uint8Array(dataLength);
  97789. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  97790. var index = 0;
  97791. for (var y = 0; y < height; y++) {
  97792. for (var x = 0; x < width; x++) {
  97793. var srcPos = (x + y * width) * 4;
  97794. byteArray[index] = srcData[srcPos + rOffset];
  97795. byteArray[index + 1] = srcData[srcPos + gOffset];
  97796. byteArray[index + 2] = srcData[srcPos + bOffset];
  97797. byteArray[index + 3] = srcData[srcPos + aOffset];
  97798. index += 4;
  97799. }
  97800. }
  97801. return byteArray;
  97802. };
  97803. DDSTools._ExtractLongWordOrder = function (value) {
  97804. if (value === 0 || value === 255 || value === -16777216) {
  97805. return 0;
  97806. }
  97807. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  97808. };
  97809. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  97810. var byteArray = new Uint8Array(dataLength);
  97811. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  97812. var index = 0;
  97813. for (var y = 0; y < height; y++) {
  97814. for (var x = 0; x < width; x++) {
  97815. var srcPos = (x + y * width) * 3;
  97816. byteArray[index] = srcData[srcPos + rOffset];
  97817. byteArray[index + 1] = srcData[srcPos + gOffset];
  97818. byteArray[index + 2] = srcData[srcPos + bOffset];
  97819. index += 3;
  97820. }
  97821. }
  97822. return byteArray;
  97823. };
  97824. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  97825. var byteArray = new Uint8Array(dataLength);
  97826. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  97827. var index = 0;
  97828. for (var y = 0; y < height; y++) {
  97829. for (var x = 0; x < width; x++) {
  97830. var srcPos = (x + y * width);
  97831. byteArray[index] = srcData[srcPos];
  97832. index++;
  97833. }
  97834. }
  97835. return byteArray;
  97836. };
  97837. /**
  97838. * Uploads DDS Levels to a Babylon Texture
  97839. * @hidden
  97840. */
  97841. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  97842. if (lodIndex === void 0) { lodIndex = -1; }
  97843. var sphericalPolynomialFaces = null;
  97844. if (info.sphericalPolynomial) {
  97845. sphericalPolynomialFaces = new Array();
  97846. }
  97847. var ext = engine.getCaps().s3tc;
  97848. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  97849. var fourCC, width, height, dataLength = 0, dataOffset;
  97850. var byteArray, mipmapCount, mip;
  97851. var internalCompressedFormat = 0;
  97852. var blockBytes = 1;
  97853. if (header[off_magic] !== DDS_MAGIC) {
  97854. BABYLON.Tools.Error("Invalid magic number in DDS header");
  97855. return;
  97856. }
  97857. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  97858. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  97859. return;
  97860. }
  97861. if (info.isCompressed && !ext) {
  97862. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  97863. return;
  97864. }
  97865. var bpp = header[off_RGBbpp];
  97866. dataOffset = header[off_size] + 4;
  97867. var computeFormats = false;
  97868. if (info.isFourCC) {
  97869. fourCC = header[off_pfFourCC];
  97870. switch (fourCC) {
  97871. case FOURCC_DXT1:
  97872. blockBytes = 8;
  97873. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  97874. break;
  97875. case FOURCC_DXT3:
  97876. blockBytes = 16;
  97877. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  97878. break;
  97879. case FOURCC_DXT5:
  97880. blockBytes = 16;
  97881. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  97882. break;
  97883. case FOURCC_D3DFMT_R16G16B16A16F:
  97884. computeFormats = true;
  97885. break;
  97886. case FOURCC_D3DFMT_R32G32B32A32F:
  97887. computeFormats = true;
  97888. break;
  97889. case FOURCC_DX10:
  97890. // There is an additionnal header so dataOffset need to be changed
  97891. dataOffset += 5 * 4; // 5 uints
  97892. var supported = false;
  97893. switch (info.dxgiFormat) {
  97894. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  97895. computeFormats = true;
  97896. supported = true;
  97897. break;
  97898. case DXGI_FORMAT_B8G8R8X8_UNORM:
  97899. info.isRGB = true;
  97900. info.isFourCC = false;
  97901. bpp = 32;
  97902. supported = true;
  97903. break;
  97904. }
  97905. if (supported) {
  97906. break;
  97907. }
  97908. default:
  97909. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  97910. return;
  97911. }
  97912. }
  97913. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  97914. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  97915. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  97916. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  97917. if (computeFormats) {
  97918. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  97919. }
  97920. mipmapCount = 1;
  97921. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  97922. mipmapCount = Math.max(1, header[off_mipmapCount]);
  97923. }
  97924. for (var face = 0; face < faces; face++) {
  97925. width = header[off_width];
  97926. height = header[off_height];
  97927. for (mip = 0; mip < mipmapCount; ++mip) {
  97928. if (lodIndex === -1 || lodIndex === mip) {
  97929. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  97930. var i = (lodIndex === -1) ? mip : 0;
  97931. if (!info.isCompressed && info.isFourCC) {
  97932. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  97933. dataLength = width * height * 4;
  97934. var floatArray = null;
  97935. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  97936. if (bpp === 128) {
  97937. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  97938. if (sphericalPolynomialFaces && i == 0) {
  97939. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  97940. }
  97941. }
  97942. else if (bpp === 64) {
  97943. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  97944. if (sphericalPolynomialFaces && i == 0) {
  97945. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  97946. }
  97947. }
  97948. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97949. }
  97950. else {
  97951. if (bpp === 128) {
  97952. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  97953. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  97954. if (sphericalPolynomialFaces && i == 0) {
  97955. sphericalPolynomialFaces.push(floatArray);
  97956. }
  97957. }
  97958. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  97959. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  97960. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  97961. if (sphericalPolynomialFaces && i == 0) {
  97962. sphericalPolynomialFaces.push(floatArray);
  97963. }
  97964. }
  97965. else { // 64
  97966. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97967. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  97968. if (sphericalPolynomialFaces && i == 0) {
  97969. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  97970. }
  97971. }
  97972. }
  97973. if (floatArray) {
  97974. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  97975. }
  97976. }
  97977. else if (info.isRGB) {
  97978. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97979. if (bpp === 24) {
  97980. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  97981. dataLength = width * height * 3;
  97982. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  97983. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  97984. }
  97985. else { // 32
  97986. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  97987. dataLength = width * height * 4;
  97988. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  97989. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  97990. }
  97991. }
  97992. else if (info.isLuminance) {
  97993. var unpackAlignment = engine._getUnpackAlignement();
  97994. var unpaddedRowSize = width;
  97995. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  97996. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  97997. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  97998. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  97999. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  98000. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  98001. }
  98002. else {
  98003. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  98004. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  98005. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  98006. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  98007. }
  98008. }
  98009. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  98010. width *= 0.5;
  98011. height *= 0.5;
  98012. width = Math.max(1.0, width);
  98013. height = Math.max(1.0, height);
  98014. }
  98015. if (currentFace !== undefined) {
  98016. // Loading a single face
  98017. break;
  98018. }
  98019. }
  98020. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  98021. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  98022. size: header[off_width],
  98023. right: sphericalPolynomialFaces[0],
  98024. left: sphericalPolynomialFaces[1],
  98025. up: sphericalPolynomialFaces[2],
  98026. down: sphericalPolynomialFaces[3],
  98027. front: sphericalPolynomialFaces[4],
  98028. back: sphericalPolynomialFaces[5],
  98029. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  98030. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  98031. gammaSpace: false,
  98032. });
  98033. }
  98034. else {
  98035. info.sphericalPolynomial = undefined;
  98036. }
  98037. };
  98038. /**
  98039. * Gets or sets a boolean indicating that LOD info is stored in alpha channel (false by default)
  98040. */
  98041. DDSTools.StoreLODInAlphaChannel = false;
  98042. return DDSTools;
  98043. }());
  98044. BABYLON.DDSTools = DDSTools;
  98045. })(BABYLON || (BABYLON = {}));
  98046. //# sourceMappingURL=babylon.dds.js.map
  98047. var BABYLON;
  98048. (function (BABYLON) {
  98049. /**
  98050. * Implementation of the DDS Texture Loader.
  98051. */
  98052. var DDSTextureLoader = /** @class */ (function () {
  98053. function DDSTextureLoader() {
  98054. /**
  98055. * Defines wether the loader supports cascade loading the different faces.
  98056. */
  98057. this.supportCascades = true;
  98058. }
  98059. /**
  98060. * This returns if the loader support the current file information.
  98061. * @param extension defines the file extension of the file being loaded
  98062. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98063. * @param fallback defines the fallback internal texture if any
  98064. * @param isBase64 defines whether the texture is encoded as a base64
  98065. * @param isBuffer defines whether the texture data are stored as a buffer
  98066. * @returns true if the loader can load the specified file
  98067. */
  98068. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  98069. return extension.indexOf(".dds") === 0;
  98070. };
  98071. /**
  98072. * Transform the url before loading if required.
  98073. * @param rootUrl the url of the texture
  98074. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98075. * @returns the transformed texture
  98076. */
  98077. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  98078. return rootUrl;
  98079. };
  98080. /**
  98081. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  98082. * @param rootUrl the url of the texture
  98083. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98084. * @returns the fallback texture
  98085. */
  98086. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  98087. return null;
  98088. };
  98089. /**
  98090. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  98091. * @param data contains the texture data
  98092. * @param texture defines the BabylonJS internal texture
  98093. * @param createPolynomials will be true if polynomials have been requested
  98094. * @param onLoad defines the callback to trigger once the texture is ready
  98095. * @param onError defines the callback to trigger in case of error
  98096. */
  98097. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  98098. var engine = texture.getEngine();
  98099. var info;
  98100. var loadMipmap = false;
  98101. if (Array.isArray(imgs)) {
  98102. for (var index = 0; index < imgs.length; index++) {
  98103. var data_1 = imgs[index];
  98104. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  98105. texture.width = info.width;
  98106. texture.height = info.height;
  98107. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  98108. engine._unpackFlipY(info.isCompressed);
  98109. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  98110. if (!info.isFourCC && info.mipmapCount === 1) {
  98111. engine.generateMipMapsForCubemap(texture);
  98112. }
  98113. }
  98114. }
  98115. else {
  98116. var data = imgs;
  98117. info = BABYLON.DDSTools.GetDDSInfo(data);
  98118. texture.width = info.width;
  98119. texture.height = info.height;
  98120. if (createPolynomials) {
  98121. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  98122. }
  98123. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  98124. engine._unpackFlipY(info.isCompressed);
  98125. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  98126. if (!info.isFourCC && info.mipmapCount === 1) {
  98127. engine.generateMipMapsForCubemap(texture);
  98128. }
  98129. }
  98130. engine._setCubeMapTextureParams(loadMipmap);
  98131. texture.isReady = true;
  98132. if (onLoad) {
  98133. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  98134. }
  98135. };
  98136. /**
  98137. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  98138. * @param data contains the texture data
  98139. * @param texture defines the BabylonJS internal texture
  98140. * @param callback defines the method to call once ready to upload
  98141. */
  98142. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  98143. var info = BABYLON.DDSTools.GetDDSInfo(data);
  98144. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  98145. callback(info.width, info.height, loadMipmap, info.isFourCC, function () {
  98146. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  98147. });
  98148. };
  98149. return DDSTextureLoader;
  98150. }());
  98151. // Register the loader.
  98152. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  98153. })(BABYLON || (BABYLON = {}));
  98154. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  98155. var BABYLON;
  98156. (function (BABYLON) {
  98157. /**
  98158. * Based on jsTGALoader - Javascript loader for TGA file
  98159. * By Vincent Thibault
  98160. * @see http://blog.robrowser.com/javascript-tga-loader.html
  98161. */
  98162. var TGATools = /** @class */ (function () {
  98163. function TGATools() {
  98164. }
  98165. /**
  98166. * Gets the header of a TGA file
  98167. * @param data defines the TGA data
  98168. * @returns the header
  98169. */
  98170. TGATools.GetTGAHeader = function (data) {
  98171. var offset = 0;
  98172. var header = {
  98173. id_length: data[offset++],
  98174. colormap_type: data[offset++],
  98175. image_type: data[offset++],
  98176. colormap_index: data[offset++] | data[offset++] << 8,
  98177. colormap_length: data[offset++] | data[offset++] << 8,
  98178. colormap_size: data[offset++],
  98179. origin: [
  98180. data[offset++] | data[offset++] << 8,
  98181. data[offset++] | data[offset++] << 8
  98182. ],
  98183. width: data[offset++] | data[offset++] << 8,
  98184. height: data[offset++] | data[offset++] << 8,
  98185. pixel_size: data[offset++],
  98186. flags: data[offset++]
  98187. };
  98188. return header;
  98189. };
  98190. /**
  98191. * Uploads TGA content to a Babylon Texture
  98192. * @hidden
  98193. */
  98194. TGATools.UploadContent = function (texture, data) {
  98195. // Not enough data to contain header ?
  98196. if (data.length < 19) {
  98197. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  98198. return;
  98199. }
  98200. // Read Header
  98201. var offset = 18;
  98202. var header = TGATools.GetTGAHeader(data);
  98203. // Assume it's a valid Targa file.
  98204. if (header.id_length + offset > data.length) {
  98205. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  98206. return;
  98207. }
  98208. // Skip not needed data
  98209. offset += header.id_length;
  98210. var use_rle = false;
  98211. var use_pal = false;
  98212. var use_grey = false;
  98213. // Get some informations.
  98214. switch (header.image_type) {
  98215. case TGATools._TYPE_RLE_INDEXED:
  98216. use_rle = true;
  98217. case TGATools._TYPE_INDEXED:
  98218. use_pal = true;
  98219. break;
  98220. case TGATools._TYPE_RLE_RGB:
  98221. use_rle = true;
  98222. case TGATools._TYPE_RGB:
  98223. // use_rgb = true;
  98224. break;
  98225. case TGATools._TYPE_RLE_GREY:
  98226. use_rle = true;
  98227. case TGATools._TYPE_GREY:
  98228. use_grey = true;
  98229. break;
  98230. }
  98231. var pixel_data;
  98232. // var numAlphaBits = header.flags & 0xf;
  98233. var pixel_size = header.pixel_size >> 3;
  98234. var pixel_total = header.width * header.height * pixel_size;
  98235. // Read palettes
  98236. var palettes;
  98237. if (use_pal) {
  98238. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  98239. }
  98240. // Read LRE
  98241. if (use_rle) {
  98242. pixel_data = new Uint8Array(pixel_total);
  98243. var c, count, i;
  98244. var localOffset = 0;
  98245. var pixels = new Uint8Array(pixel_size);
  98246. while (offset < pixel_total && localOffset < pixel_total) {
  98247. c = data[offset++];
  98248. count = (c & 0x7f) + 1;
  98249. // RLE pixels
  98250. if (c & 0x80) {
  98251. // Bind pixel tmp array
  98252. for (i = 0; i < pixel_size; ++i) {
  98253. pixels[i] = data[offset++];
  98254. }
  98255. // Copy pixel array
  98256. for (i = 0; i < count; ++i) {
  98257. pixel_data.set(pixels, localOffset + i * pixel_size);
  98258. }
  98259. localOffset += pixel_size * count;
  98260. }
  98261. // Raw pixels
  98262. else {
  98263. count *= pixel_size;
  98264. for (i = 0; i < count; ++i) {
  98265. pixel_data[localOffset + i] = data[offset++];
  98266. }
  98267. localOffset += count;
  98268. }
  98269. }
  98270. }
  98271. // RAW Pixels
  98272. else {
  98273. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  98274. }
  98275. // Load to texture
  98276. var x_start, y_start, x_step, y_step, y_end, x_end;
  98277. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  98278. default:
  98279. case TGATools._ORIGIN_UL:
  98280. x_start = 0;
  98281. x_step = 1;
  98282. x_end = header.width;
  98283. y_start = 0;
  98284. y_step = 1;
  98285. y_end = header.height;
  98286. break;
  98287. case TGATools._ORIGIN_BL:
  98288. x_start = 0;
  98289. x_step = 1;
  98290. x_end = header.width;
  98291. y_start = header.height - 1;
  98292. y_step = -1;
  98293. y_end = -1;
  98294. break;
  98295. case TGATools._ORIGIN_UR:
  98296. x_start = header.width - 1;
  98297. x_step = -1;
  98298. x_end = -1;
  98299. y_start = 0;
  98300. y_step = 1;
  98301. y_end = header.height;
  98302. break;
  98303. case TGATools._ORIGIN_BR:
  98304. x_start = header.width - 1;
  98305. x_step = -1;
  98306. x_end = -1;
  98307. y_start = header.height - 1;
  98308. y_step = -1;
  98309. y_end = -1;
  98310. break;
  98311. }
  98312. // Load the specify method
  98313. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  98314. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  98315. var engine = texture.getEngine();
  98316. engine._uploadDataToTextureDirectly(texture, imageData);
  98317. };
  98318. /** @hidden */
  98319. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  98320. var image = pixel_data, colormap = palettes;
  98321. var width = header.width, height = header.height;
  98322. var color, i = 0, x, y;
  98323. var imageData = new Uint8Array(width * height * 4);
  98324. for (y = y_start; y !== y_end; y += y_step) {
  98325. for (x = x_start; x !== x_end; x += x_step, i++) {
  98326. color = image[i];
  98327. imageData[(x + width * y) * 4 + 3] = 255;
  98328. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  98329. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  98330. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  98331. }
  98332. }
  98333. return imageData;
  98334. };
  98335. /** @hidden */
  98336. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  98337. var image = pixel_data;
  98338. var width = header.width, height = header.height;
  98339. var color, i = 0, x, y;
  98340. var imageData = new Uint8Array(width * height * 4);
  98341. for (y = y_start; y !== y_end; y += y_step) {
  98342. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  98343. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  98344. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  98345. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  98346. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  98347. imageData[(x + width * y) * 4 + 0] = r;
  98348. imageData[(x + width * y) * 4 + 1] = g;
  98349. imageData[(x + width * y) * 4 + 2] = b;
  98350. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  98351. }
  98352. }
  98353. return imageData;
  98354. };
  98355. /** @hidden */
  98356. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  98357. var image = pixel_data;
  98358. var width = header.width, height = header.height;
  98359. var i = 0, x, y;
  98360. var imageData = new Uint8Array(width * height * 4);
  98361. for (y = y_start; y !== y_end; y += y_step) {
  98362. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  98363. imageData[(x + width * y) * 4 + 3] = 255;
  98364. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  98365. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  98366. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  98367. }
  98368. }
  98369. return imageData;
  98370. };
  98371. /** @hidden */
  98372. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  98373. var image = pixel_data;
  98374. var width = header.width, height = header.height;
  98375. var i = 0, x, y;
  98376. var imageData = new Uint8Array(width * height * 4);
  98377. for (y = y_start; y !== y_end; y += y_step) {
  98378. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  98379. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  98380. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  98381. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  98382. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  98383. }
  98384. }
  98385. return imageData;
  98386. };
  98387. /** @hidden */
  98388. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  98389. var image = pixel_data;
  98390. var width = header.width, height = header.height;
  98391. var color, i = 0, x, y;
  98392. var imageData = new Uint8Array(width * height * 4);
  98393. for (y = y_start; y !== y_end; y += y_step) {
  98394. for (x = x_start; x !== x_end; x += x_step, i++) {
  98395. color = image[i];
  98396. imageData[(x + width * y) * 4 + 0] = color;
  98397. imageData[(x + width * y) * 4 + 1] = color;
  98398. imageData[(x + width * y) * 4 + 2] = color;
  98399. imageData[(x + width * y) * 4 + 3] = 255;
  98400. }
  98401. }
  98402. return imageData;
  98403. };
  98404. /** @hidden */
  98405. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  98406. var image = pixel_data;
  98407. var width = header.width, height = header.height;
  98408. var i = 0, x, y;
  98409. var imageData = new Uint8Array(width * height * 4);
  98410. for (y = y_start; y !== y_end; y += y_step) {
  98411. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  98412. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  98413. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  98414. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  98415. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  98416. }
  98417. }
  98418. return imageData;
  98419. };
  98420. //private static _TYPE_NO_DATA = 0;
  98421. TGATools._TYPE_INDEXED = 1;
  98422. TGATools._TYPE_RGB = 2;
  98423. TGATools._TYPE_GREY = 3;
  98424. TGATools._TYPE_RLE_INDEXED = 9;
  98425. TGATools._TYPE_RLE_RGB = 10;
  98426. TGATools._TYPE_RLE_GREY = 11;
  98427. TGATools._ORIGIN_MASK = 0x30;
  98428. TGATools._ORIGIN_SHIFT = 0x04;
  98429. TGATools._ORIGIN_BL = 0x00;
  98430. TGATools._ORIGIN_BR = 0x01;
  98431. TGATools._ORIGIN_UL = 0x02;
  98432. TGATools._ORIGIN_UR = 0x03;
  98433. return TGATools;
  98434. }());
  98435. BABYLON.TGATools = TGATools;
  98436. })(BABYLON || (BABYLON = {}));
  98437. //# sourceMappingURL=babylon.tga.js.map
  98438. var BABYLON;
  98439. (function (BABYLON) {
  98440. /**
  98441. * Implementation of the TGA Texture Loader.
  98442. */
  98443. var TGATextureLoader = /** @class */ (function () {
  98444. function TGATextureLoader() {
  98445. /**
  98446. * Defines wether the loader supports cascade loading the different faces.
  98447. */
  98448. this.supportCascades = false;
  98449. }
  98450. /**
  98451. * This returns if the loader support the current file information.
  98452. * @param extension defines the file extension of the file being loaded
  98453. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98454. * @param fallback defines the fallback internal texture if any
  98455. * @param isBase64 defines whether the texture is encoded as a base64
  98456. * @param isBuffer defines whether the texture data are stored as a buffer
  98457. * @returns true if the loader can load the specified file
  98458. */
  98459. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  98460. return extension.indexOf(".tga") === 0;
  98461. };
  98462. /**
  98463. * Transform the url before loading if required.
  98464. * @param rootUrl the url of the texture
  98465. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98466. * @returns the transformed texture
  98467. */
  98468. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  98469. return rootUrl;
  98470. };
  98471. /**
  98472. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  98473. * @param rootUrl the url of the texture
  98474. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98475. * @returns the fallback texture
  98476. */
  98477. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  98478. return null;
  98479. };
  98480. /**
  98481. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  98482. * @param data contains the texture data
  98483. * @param texture defines the BabylonJS internal texture
  98484. * @param createPolynomials will be true if polynomials have been requested
  98485. * @param onLoad defines the callback to trigger once the texture is ready
  98486. * @param onError defines the callback to trigger in case of error
  98487. */
  98488. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  98489. throw ".env not supported in Cube.";
  98490. };
  98491. /**
  98492. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  98493. * @param data contains the texture data
  98494. * @param texture defines the BabylonJS internal texture
  98495. * @param callback defines the method to call once ready to upload
  98496. */
  98497. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  98498. var uintData = new Uint8Array(data);
  98499. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  98500. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  98501. BABYLON.TGATools.UploadContent(texture, uintData);
  98502. });
  98503. };
  98504. return TGATextureLoader;
  98505. }());
  98506. // Register the loader.
  98507. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  98508. })(BABYLON || (BABYLON = {}));
  98509. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  98510. var BABYLON;
  98511. (function (BABYLON) {
  98512. /**
  98513. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  98514. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  98515. */
  98516. var KhronosTextureContainer = /** @class */ (function () {
  98517. /**
  98518. * Creates a new KhronosTextureContainer
  98519. * @param arrayBuffer contents of the KTX container file
  98520. * @param facesExpected should be either 1 or 6, based whether a cube texture or or
  98521. * @param threeDExpected provision for indicating that data should be a 3D texture, not implemented
  98522. * @param textureArrayExpected provision for indicating that data should be a texture array, not implemented
  98523. */
  98524. function KhronosTextureContainer(
  98525. /** contents of the KTX container file */
  98526. arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  98527. this.arrayBuffer = arrayBuffer;
  98528. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  98529. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  98530. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  98531. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  98532. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  98533. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  98534. BABYLON.Tools.Error("texture missing KTX identifier");
  98535. return;
  98536. }
  98537. // load the reset of the header in native 32 bit int
  98538. var header = new Int32Array(this.arrayBuffer, 12, 13);
  98539. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  98540. var oppositeEndianess = header[0] === 0x01020304;
  98541. // read all the header elements in order they exist in the file, without modification (sans endainness)
  98542. this.glType = oppositeEndianess ? this.switchEndianness(header[1]) : header[1]; // must be 0 for compressed textures
  98543. this.glTypeSize = oppositeEndianess ? this.switchEndianness(header[2]) : header[2]; // must be 1 for compressed textures
  98544. this.glFormat = oppositeEndianess ? this.switchEndianness(header[3]) : header[3]; // must be 0 for compressed textures
  98545. this.glInternalFormat = oppositeEndianess ? this.switchEndianness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  98546. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndianness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  98547. this.pixelWidth = oppositeEndianess ? this.switchEndianness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  98548. this.pixelHeight = oppositeEndianess ? this.switchEndianness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  98549. this.pixelDepth = oppositeEndianess ? this.switchEndianness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  98550. this.numberOfArrayElements = oppositeEndianess ? this.switchEndianness(header[9]) : header[9]; // used for texture arrays
  98551. this.numberOfFaces = oppositeEndianess ? this.switchEndianness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  98552. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndianness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  98553. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndianness(header[12]) : header[12]; // the amount of space after the header for meta-data
  98554. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  98555. if (this.glType !== 0) {
  98556. BABYLON.Tools.Error("only compressed formats currently supported");
  98557. return;
  98558. }
  98559. else {
  98560. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  98561. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  98562. }
  98563. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  98564. BABYLON.Tools.Error("only 2D textures currently supported");
  98565. return;
  98566. }
  98567. if (this.numberOfArrayElements !== 0) {
  98568. BABYLON.Tools.Error("texture arrays not currently supported");
  98569. return;
  98570. }
  98571. if (this.numberOfFaces !== facesExpected) {
  98572. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  98573. return;
  98574. }
  98575. // we now have a completely validated file, so could use existence of loadType as success
  98576. // would need to make this more elaborate & adjust checks above to support more than one load type
  98577. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  98578. }
  98579. //
  98580. /**
  98581. * Revert the endianness of a value.
  98582. * Not as fast hardware based, but will probably never need to use
  98583. * @param val defines the value to convert
  98584. * @returns the new value
  98585. */
  98586. KhronosTextureContainer.prototype.switchEndianness = function (val) {
  98587. return ((val & 0xFF) << 24)
  98588. | ((val & 0xFF00) << 8)
  98589. | ((val >> 8) & 0xFF00)
  98590. | ((val >> 24) & 0xFF);
  98591. };
  98592. /**
  98593. * Uploads KTX content to a Babylon Texture.
  98594. * It is assumed that the texture has already been created & is currently bound
  98595. * @hidden
  98596. */
  98597. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  98598. switch (this.loadType) {
  98599. case KhronosTextureContainer.COMPRESSED_2D:
  98600. this._upload2DCompressedLevels(texture, loadMipmaps);
  98601. break;
  98602. case KhronosTextureContainer.TEX_2D:
  98603. case KhronosTextureContainer.COMPRESSED_3D:
  98604. case KhronosTextureContainer.TEX_3D:
  98605. }
  98606. };
  98607. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  98608. // initialize width & height for level 1
  98609. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  98610. var width = this.pixelWidth;
  98611. var height = this.pixelHeight;
  98612. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  98613. for (var level = 0; level < mipmapCount; level++) {
  98614. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  98615. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  98616. for (var face = 0; face < this.numberOfFaces; face++) {
  98617. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  98618. var engine = texture.getEngine();
  98619. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  98620. dataOffset += imageSize; // add size of the image for the next face/mipmap
  98621. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  98622. }
  98623. width = Math.max(1.0, width * 0.5);
  98624. height = Math.max(1.0, height * 0.5);
  98625. }
  98626. };
  98627. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  98628. // load types
  98629. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  98630. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  98631. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  98632. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  98633. return KhronosTextureContainer;
  98634. }());
  98635. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  98636. })(BABYLON || (BABYLON = {}));
  98637. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  98638. var BABYLON;
  98639. (function (BABYLON) {
  98640. /**
  98641. * Implementation of the KTX Texture Loader.
  98642. */
  98643. var KTXTextureLoader = /** @class */ (function () {
  98644. function KTXTextureLoader() {
  98645. /**
  98646. * Defines wether the loader supports cascade loading the different faces.
  98647. */
  98648. this.supportCascades = false;
  98649. }
  98650. /**
  98651. * This returns if the loader support the current file information.
  98652. * @param extension defines the file extension of the file being loaded
  98653. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98654. * @param fallback defines the fallback internal texture if any
  98655. * @param isBase64 defines whether the texture is encoded as a base64
  98656. * @param isBuffer defines whether the texture data are stored as a buffer
  98657. * @returns true if the loader can load the specified file
  98658. */
  98659. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  98660. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  98661. return true;
  98662. }
  98663. return false;
  98664. };
  98665. /**
  98666. * Transform the url before loading if required.
  98667. * @param rootUrl the url of the texture
  98668. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98669. * @returns the transformed texture
  98670. */
  98671. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  98672. var lastDot = rootUrl.lastIndexOf('.');
  98673. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  98674. };
  98675. /**
  98676. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  98677. * @param rootUrl the url of the texture
  98678. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98679. * @returns the fallback texture
  98680. */
  98681. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  98682. // remove the format appended to the rootUrl in the original createCubeTexture call.
  98683. var exp = new RegExp("" + textureFormatInUse + "$");
  98684. return rootUrl.replace(exp, "");
  98685. };
  98686. /**
  98687. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  98688. * @param data contains the texture data
  98689. * @param texture defines the BabylonJS internal texture
  98690. * @param createPolynomials will be true if polynomials have been requested
  98691. * @param onLoad defines the callback to trigger once the texture is ready
  98692. * @param onError defines the callback to trigger in case of error
  98693. */
  98694. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  98695. if (Array.isArray(data)) {
  98696. return;
  98697. }
  98698. var engine = texture.getEngine();
  98699. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  98700. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  98701. engine._unpackFlipY(true);
  98702. ktx.uploadLevels(texture, texture.generateMipMaps);
  98703. texture.width = ktx.pixelWidth;
  98704. texture.height = ktx.pixelHeight;
  98705. engine._setCubeMapTextureParams(loadMipmap);
  98706. texture.isReady = true;
  98707. };
  98708. /**
  98709. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  98710. * @param data contains the texture data
  98711. * @param texture defines the BabylonJS internal texture
  98712. * @param callback defines the method to call once ready to upload
  98713. */
  98714. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  98715. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  98716. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  98717. ktx.uploadLevels(texture, texture.generateMipMaps);
  98718. });
  98719. };
  98720. return KTXTextureLoader;
  98721. }());
  98722. // Register the loader.
  98723. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  98724. })(BABYLON || (BABYLON = {}));
  98725. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  98726. var BABYLON;
  98727. (function (BABYLON) {
  98728. /**
  98729. * Sets of helpers addressing the serialization and deserialization of environment texture
  98730. * stored in a BabylonJS env file.
  98731. * Those files are usually stored as .env files.
  98732. */
  98733. var EnvironmentTextureTools = /** @class */ (function () {
  98734. function EnvironmentTextureTools() {
  98735. }
  98736. /**
  98737. * Gets the environment info from an env file.
  98738. * @param data The array buffer containing the .env bytes.
  98739. * @returns the environment file info (the json header) if successfully parsed.
  98740. */
  98741. EnvironmentTextureTools.GetEnvInfo = function (data) {
  98742. var dataView = new DataView(data);
  98743. var pos = 0;
  98744. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  98745. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  98746. BABYLON.Tools.Error('Not a babylon environment map');
  98747. return null;
  98748. }
  98749. }
  98750. // Read json manifest - collect characters up to null terminator
  98751. var manifestString = '';
  98752. var charCode = 0x00;
  98753. while ((charCode = dataView.getUint8(pos++))) {
  98754. manifestString += String.fromCharCode(charCode);
  98755. }
  98756. var manifest = JSON.parse(manifestString);
  98757. if (manifest.specular) {
  98758. // Extend the header with the position of the payload.
  98759. manifest.specular.specularDataPosition = pos;
  98760. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  98761. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  98762. }
  98763. return manifest;
  98764. };
  98765. /**
  98766. * Creates an environment texture from a loaded cube texture.
  98767. * @param texture defines the cube texture to convert in env file
  98768. * @return a promise containing the environment data if succesfull.
  98769. */
  98770. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  98771. var _this = this;
  98772. var internalTexture = texture.getInternalTexture();
  98773. if (!internalTexture) {
  98774. return Promise.reject("The cube texture is invalid.");
  98775. }
  98776. if (!texture._prefiltered) {
  98777. return Promise.reject("The cube texture is invalid (not prefiltered).");
  98778. }
  98779. var engine = internalTexture.getEngine();
  98780. if (engine && engine.premultipliedAlpha) {
  98781. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  98782. }
  98783. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  98784. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  98785. }
  98786. var canvas = engine.getRenderingCanvas();
  98787. if (!canvas) {
  98788. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  98789. }
  98790. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  98791. if (!engine.getCaps().textureFloatRender) {
  98792. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  98793. if (!engine.getCaps().textureHalfFloatRender) {
  98794. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  98795. }
  98796. }
  98797. var cubeWidth = internalTexture.width;
  98798. var hostingScene = new BABYLON.Scene(engine);
  98799. var specularTextures = {};
  98800. var promises = [];
  98801. // Read and collect all mipmaps data from the cube.
  98802. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  98803. mipmapsCount = Math.round(mipmapsCount);
  98804. var _loop_1 = function (i) {
  98805. var faceWidth = Math.pow(2, mipmapsCount - i);
  98806. var _loop_2 = function (face) {
  98807. var data = texture.readPixels(face, i);
  98808. // Creates a temp texture with the face data.
  98809. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  98810. // And rgbdEncode them.
  98811. var promise = new Promise(function (resolve, reject) {
  98812. 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);
  98813. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  98814. rgbdPostProcess.onApply = function (effect) {
  98815. effect._bindTexture("textureSampler", tempTexture);
  98816. };
  98817. // As the process needs to happen on the main canvas, keep track of the current size
  98818. var currentW = engine.getRenderWidth();
  98819. var currentH = engine.getRenderHeight();
  98820. // Set the desired size for the texture
  98821. engine.setSize(faceWidth, faceWidth);
  98822. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  98823. // Reading datas from WebGL
  98824. BABYLON.Tools.ToBlob(canvas, function (blob) {
  98825. var fileReader = new FileReader();
  98826. fileReader.onload = function (event) {
  98827. var arrayBuffer = event.target.result;
  98828. specularTextures[i * 6 + face] = arrayBuffer;
  98829. resolve();
  98830. };
  98831. fileReader.readAsArrayBuffer(blob);
  98832. });
  98833. // Reapply the previous canvas size
  98834. engine.setSize(currentW, currentH);
  98835. });
  98836. });
  98837. promises.push(promise);
  98838. };
  98839. // All faces of the cube.
  98840. for (var face = 0; face < 6; face++) {
  98841. _loop_2(face);
  98842. }
  98843. };
  98844. for (var i = 0; i <= mipmapsCount; i++) {
  98845. _loop_1(i);
  98846. }
  98847. // Once all the textures haves been collected as RGBD stored in PNGs
  98848. return Promise.all(promises).then(function () {
  98849. // We can delete the hosting scene keeping track of all the creation objects
  98850. hostingScene.dispose();
  98851. // Creates the json header for the env texture
  98852. var info = {
  98853. version: 1,
  98854. width: cubeWidth,
  98855. irradiance: _this._CreateEnvTextureIrradiance(texture),
  98856. specular: {
  98857. mipmaps: [],
  98858. lodGenerationScale: texture.lodGenerationScale
  98859. }
  98860. };
  98861. // Sets the specular image data information
  98862. var position = 0;
  98863. for (var i = 0; i <= mipmapsCount; i++) {
  98864. for (var face = 0; face < 6; face++) {
  98865. var byteLength = specularTextures[i * 6 + face].byteLength;
  98866. info.specular.mipmaps.push({
  98867. length: byteLength,
  98868. position: position
  98869. });
  98870. position += byteLength;
  98871. }
  98872. }
  98873. // Encode the JSON as an array buffer
  98874. var infoString = JSON.stringify(info);
  98875. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  98876. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  98877. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  98878. infoView[i] = infoString.charCodeAt(i);
  98879. }
  98880. // Ends up with a null terminator for easier parsing
  98881. infoView[infoString.length] = 0x00;
  98882. // Computes the final required size and creates the storage
  98883. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  98884. var finalBuffer = new ArrayBuffer(totalSize);
  98885. var finalBufferView = new Uint8Array(finalBuffer);
  98886. var dataView = new DataView(finalBuffer);
  98887. // Copy the magic bytes identifying the file in
  98888. var pos = 0;
  98889. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  98890. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  98891. }
  98892. // Add the json info
  98893. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  98894. pos += infoBuffer.byteLength;
  98895. // Finally inserts the texture data
  98896. for (var i = 0; i <= mipmapsCount; i++) {
  98897. for (var face = 0; face < 6; face++) {
  98898. var dataBuffer = specularTextures[i * 6 + face];
  98899. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  98900. pos += dataBuffer.byteLength;
  98901. }
  98902. }
  98903. // Voila
  98904. return finalBuffer;
  98905. });
  98906. };
  98907. /**
  98908. * Creates a JSON representation of the spherical data.
  98909. * @param texture defines the texture containing the polynomials
  98910. * @return the JSON representation of the spherical info
  98911. */
  98912. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  98913. var polynmials = texture.sphericalPolynomial;
  98914. if (polynmials == null) {
  98915. return null;
  98916. }
  98917. return {
  98918. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  98919. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  98920. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  98921. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  98922. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  98923. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  98924. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  98925. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  98926. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  98927. };
  98928. };
  98929. /**
  98930. * Uploads the texture info contained in the env file to the GPU.
  98931. * @param texture defines the internal texture to upload to
  98932. * @param arrayBuffer defines the buffer cotaining the data to load
  98933. * @param info defines the texture info retrieved through the GetEnvInfo method
  98934. * @returns a promise
  98935. */
  98936. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  98937. if (info.version !== 1) {
  98938. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  98939. }
  98940. var specularInfo = info.specular;
  98941. if (!specularInfo) {
  98942. // Nothing else parsed so far
  98943. return Promise.resolve();
  98944. }
  98945. // Double checks the enclosed info
  98946. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  98947. mipmapsCount = Math.round(mipmapsCount) + 1;
  98948. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  98949. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  98950. }
  98951. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  98952. var imageData = new Array(mipmapsCount);
  98953. for (var i = 0; i < mipmapsCount; i++) {
  98954. imageData[i] = new Array(6);
  98955. for (var face = 0; face < 6; face++) {
  98956. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  98957. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  98958. }
  98959. }
  98960. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  98961. };
  98962. /**
  98963. * Uploads the levels of image data to the GPU.
  98964. * @param texture defines the internal texture to upload to
  98965. * @param imageData defines the array buffer views of image data [mipmap][face]
  98966. * @returns a promise
  98967. */
  98968. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  98969. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  98970. throw new Error("Texture size must be a power of two");
  98971. }
  98972. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  98973. // Gets everything ready.
  98974. var engine = texture.getEngine();
  98975. var expandTexture = false;
  98976. var generateNonLODTextures = false;
  98977. var rgbdPostProcess = null;
  98978. var cubeRtt = null;
  98979. var lodTextures = null;
  98980. var caps = engine.getCaps();
  98981. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  98982. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  98983. texture.generateMipMaps = true;
  98984. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  98985. // Add extra process if texture lod is not supported
  98986. if (!caps.textureLOD) {
  98987. expandTexture = false;
  98988. generateNonLODTextures = true;
  98989. lodTextures = {};
  98990. }
  98991. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  98992. else if (engine.webGLVersion < 2) {
  98993. expandTexture = false;
  98994. }
  98995. // If half float available we can uncompress the texture
  98996. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  98997. expandTexture = true;
  98998. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  98999. }
  99000. // If full float available we can uncompress the texture
  99001. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  99002. expandTexture = true;
  99003. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  99004. }
  99005. // Expand the texture if possible
  99006. if (expandTexture) {
  99007. // Simply run through the decode PP
  99008. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  99009. texture._isRGBD = false;
  99010. texture.invertY = false;
  99011. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  99012. generateDepthBuffer: false,
  99013. generateMipMaps: true,
  99014. generateStencilBuffer: false,
  99015. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  99016. type: texture.type,
  99017. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  99018. });
  99019. }
  99020. else {
  99021. texture._isRGBD = true;
  99022. texture.invertY = true;
  99023. // In case of missing support, applies the same patch than DDS files.
  99024. if (generateNonLODTextures) {
  99025. var mipSlices = 3;
  99026. var scale = texture._lodGenerationScale;
  99027. var offset = texture._lodGenerationOffset;
  99028. for (var i = 0; i < mipSlices; i++) {
  99029. //compute LOD from even spacing in smoothness (matching shader calculation)
  99030. var smoothness = i / (mipSlices - 1);
  99031. var roughness = 1 - smoothness;
  99032. var minLODIndex = offset; // roughness = 0
  99033. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  99034. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  99035. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  99036. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  99037. glTextureFromLod.isCube = true;
  99038. glTextureFromLod.invertY = true;
  99039. glTextureFromLod.generateMipMaps = false;
  99040. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  99041. // Wrap in a base texture for easy binding.
  99042. var lodTexture = new BABYLON.BaseTexture(null);
  99043. lodTexture.isCube = true;
  99044. lodTexture._texture = glTextureFromLod;
  99045. lodTextures[mipmapIndex] = lodTexture;
  99046. switch (i) {
  99047. case 0:
  99048. texture._lodTextureLow = lodTexture;
  99049. break;
  99050. case 1:
  99051. texture._lodTextureMid = lodTexture;
  99052. break;
  99053. case 2:
  99054. texture._lodTextureHigh = lodTexture;
  99055. break;
  99056. }
  99057. }
  99058. }
  99059. }
  99060. var promises = [];
  99061. var _loop_3 = function (i) {
  99062. var _loop_4 = function (face) {
  99063. // Constructs an image element from image data
  99064. var bytes = imageData[i][face];
  99065. var blob = new Blob([bytes], { type: 'image/png' });
  99066. var url = URL.createObjectURL(blob);
  99067. var image = new Image();
  99068. image.src = url;
  99069. // Enqueue promise to upload to the texture.
  99070. var promise = new Promise(function (resolve, reject) {
  99071. image.onload = function () {
  99072. if (expandTexture) {
  99073. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  99074. reject(message);
  99075. }, image);
  99076. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  99077. // Uncompress the data to a RTT
  99078. rgbdPostProcess.onApply = function (effect) {
  99079. effect._bindTexture("textureSampler", tempTexture_1);
  99080. effect.setFloat2("scale", 1, 1);
  99081. };
  99082. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  99083. // Cleanup
  99084. engine.restoreDefaultFramebuffer();
  99085. tempTexture_1.dispose();
  99086. window.URL.revokeObjectURL(url);
  99087. resolve();
  99088. });
  99089. }
  99090. else {
  99091. engine._uploadImageToTexture(texture, image, face, i);
  99092. // Upload the face to the non lod texture support
  99093. if (generateNonLODTextures) {
  99094. var lodTexture = lodTextures[i];
  99095. if (lodTexture) {
  99096. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  99097. }
  99098. }
  99099. resolve();
  99100. }
  99101. };
  99102. image.onerror = function (error) {
  99103. reject(error);
  99104. };
  99105. });
  99106. promises.push(promise);
  99107. };
  99108. // All faces
  99109. for (var face = 0; face < 6; face++) {
  99110. _loop_4(face);
  99111. }
  99112. };
  99113. // All mipmaps up to provided number of images
  99114. for (var i = 0; i < imageData.length; i++) {
  99115. _loop_3(i);
  99116. }
  99117. // Fill remaining mipmaps with black textures.
  99118. if (imageData.length < mipmapsCount) {
  99119. var data = void 0;
  99120. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  99121. var dataLength = size * size * 4;
  99122. switch (texture.type) {
  99123. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  99124. data = new Uint8Array(dataLength);
  99125. break;
  99126. }
  99127. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  99128. data = new Uint16Array(dataLength);
  99129. break;
  99130. }
  99131. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  99132. data = new Float32Array(dataLength);
  99133. break;
  99134. }
  99135. }
  99136. for (var i = imageData.length; i < mipmapsCount; i++) {
  99137. for (var face = 0; face < 6; face++) {
  99138. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  99139. }
  99140. }
  99141. }
  99142. // Once all done, finishes the cleanup and return
  99143. return Promise.all(promises).then(function () {
  99144. // Release temp RTT.
  99145. if (cubeRtt) {
  99146. engine._releaseFramebufferObjects(cubeRtt);
  99147. cubeRtt._swapAndDie(texture);
  99148. }
  99149. // Release temp Post Process.
  99150. if (rgbdPostProcess) {
  99151. rgbdPostProcess.dispose();
  99152. }
  99153. // Flag internal texture as ready in case they are in use.
  99154. if (generateNonLODTextures) {
  99155. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  99156. texture._lodTextureHigh._texture.isReady = true;
  99157. }
  99158. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  99159. texture._lodTextureMid._texture.isReady = true;
  99160. }
  99161. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  99162. texture._lodTextureLow._texture.isReady = true;
  99163. }
  99164. }
  99165. });
  99166. };
  99167. /**
  99168. * Uploads spherical polynomials information to the texture.
  99169. * @param texture defines the texture we are trying to upload the information to
  99170. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  99171. */
  99172. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  99173. if (info.version !== 1) {
  99174. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  99175. }
  99176. var irradianceInfo = info.irradiance;
  99177. if (!irradianceInfo) {
  99178. return;
  99179. }
  99180. var sp = new BABYLON.SphericalPolynomial();
  99181. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  99182. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  99183. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  99184. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  99185. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  99186. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  99187. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  99188. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  99189. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  99190. texture._sphericalPolynomial = sp;
  99191. };
  99192. /**
  99193. * Magic number identifying the env file.
  99194. */
  99195. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  99196. return EnvironmentTextureTools;
  99197. }());
  99198. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  99199. })(BABYLON || (BABYLON = {}));
  99200. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  99201. var BABYLON;
  99202. (function (BABYLON) {
  99203. /**
  99204. * Implementation of the ENV Texture Loader.
  99205. */
  99206. var ENVTextureLoader = /** @class */ (function () {
  99207. function ENVTextureLoader() {
  99208. /**
  99209. * Defines wether the loader supports cascade loading the different faces.
  99210. */
  99211. this.supportCascades = false;
  99212. }
  99213. /**
  99214. * This returns if the loader support the current file information.
  99215. * @param extension defines the file extension of the file being loaded
  99216. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99217. * @param fallback defines the fallback internal texture if any
  99218. * @param isBase64 defines whether the texture is encoded as a base64
  99219. * @param isBuffer defines whether the texture data are stored as a buffer
  99220. * @returns true if the loader can load the specified file
  99221. */
  99222. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  99223. return extension.indexOf(".env") === 0;
  99224. };
  99225. /**
  99226. * Transform the url before loading if required.
  99227. * @param rootUrl the url of the texture
  99228. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99229. * @returns the transformed texture
  99230. */
  99231. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  99232. return rootUrl;
  99233. };
  99234. /**
  99235. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  99236. * @param rootUrl the url of the texture
  99237. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99238. * @returns the fallback texture
  99239. */
  99240. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  99241. return null;
  99242. };
  99243. /**
  99244. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  99245. * @param data contains the texture data
  99246. * @param texture defines the BabylonJS internal texture
  99247. * @param createPolynomials will be true if polynomials have been requested
  99248. * @param onLoad defines the callback to trigger once the texture is ready
  99249. * @param onError defines the callback to trigger in case of error
  99250. */
  99251. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  99252. if (Array.isArray(data)) {
  99253. return;
  99254. }
  99255. data = data;
  99256. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  99257. if (info) {
  99258. texture.width = info.width;
  99259. texture.height = info.width;
  99260. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  99261. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  99262. texture.isReady = true;
  99263. if (onLoad) {
  99264. onLoad();
  99265. }
  99266. });
  99267. }
  99268. else if (onError) {
  99269. onError("Can not parse the environment file", null);
  99270. }
  99271. };
  99272. /**
  99273. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  99274. * @param data contains the texture data
  99275. * @param texture defines the BabylonJS internal texture
  99276. * @param callback defines the method to call once ready to upload
  99277. */
  99278. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  99279. throw ".env not supported in 2d.";
  99280. };
  99281. return ENVTextureLoader;
  99282. }());
  99283. // Register the loader.
  99284. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  99285. })(BABYLON || (BABYLON = {}));
  99286. //# sourceMappingURL=babylon.envTextureLoader.js.map
  99287. var BABYLON;
  99288. (function (BABYLON) {
  99289. /**
  99290. * Renders a layer on top of an existing scene
  99291. */
  99292. var UtilityLayerRenderer = /** @class */ (function () {
  99293. /**
  99294. * Instantiates a UtilityLayerRenderer
  99295. * @param originalScene the original scene that will be rendered on top of
  99296. */
  99297. function UtilityLayerRenderer(
  99298. /** the original scene that will be rendered on top of */
  99299. originalScene) {
  99300. var _this = this;
  99301. this.originalScene = originalScene;
  99302. this._pointerCaptures = {};
  99303. this._lastPointerEvents = {};
  99304. /**
  99305. * If the utility layer should automatically be rendered on top of existing scene
  99306. */
  99307. this.shouldRender = true;
  99308. /**
  99309. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  99310. */
  99311. this.onlyCheckPointerDownEvents = true;
  99312. /**
  99313. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  99314. */
  99315. this.processAllEvents = false;
  99316. /**
  99317. * Observable raised when the pointer move from the utility layer scene to the main scene
  99318. */
  99319. this.onPointerOutObservable = new BABYLON.Observable();
  99320. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  99321. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  99322. this.utilityLayerScene.useRightHandedSystem = originalScene.useRightHandedSystem;
  99323. this.utilityLayerScene._allowPostProcessClearColor = false;
  99324. originalScene.getEngine().scenes.pop();
  99325. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  99326. this.utilityLayerScene.detachControl();
  99327. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  99328. if (!_this.processAllEvents) {
  99329. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  99330. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  99331. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  99332. return;
  99333. }
  99334. }
  99335. var pointerEvent = (prePointerInfo.event);
  99336. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  99337. _this._pointerCaptures[pointerEvent.pointerId] = false;
  99338. return;
  99339. }
  99340. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  99341. if (!prePointerInfo.ray && utilityScenePick) {
  99342. prePointerInfo.ray = utilityScenePick.ray;
  99343. }
  99344. // always fire the prepointer oversvable
  99345. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  99346. // allow every non pointer down event to flow to the utility layer
  99347. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  99348. if (!prePointerInfo.skipOnPointerObservable) {
  99349. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  99350. }
  99351. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  99352. _this._pointerCaptures[pointerEvent.pointerId] = false;
  99353. }
  99354. return;
  99355. }
  99356. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  99357. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  99358. if (utilityScenePick && utilityScenePick.hit) {
  99359. if (!prePointerInfo.skipOnPointerObservable) {
  99360. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  99361. }
  99362. prePointerInfo.skipOnPointerObservable = true;
  99363. }
  99364. }
  99365. else {
  99366. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  99367. var pointerEvent_1 = (prePointerInfo.event);
  99368. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  99369. if (originalScenePick && utilityScenePick) {
  99370. // No pick in utility scene
  99371. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  99372. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  99373. // We touched an utility mesh present in the main scene
  99374. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  99375. prePointerInfo.skipOnPointerObservable = true;
  99376. }
  99377. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  99378. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  99379. }
  99380. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  99381. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  99382. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  99383. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  99384. }
  99385. }
  99386. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  99387. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  99388. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  99389. // If a previous utility layer set this, do not unset this
  99390. if (!prePointerInfo.skipOnPointerObservable) {
  99391. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  99392. }
  99393. }
  99394. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  99395. // We have a pick in both scenes but main is closer than utility
  99396. // We touched an utility mesh present in the main scene
  99397. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  99398. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  99399. prePointerInfo.skipOnPointerObservable = true;
  99400. }
  99401. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  99402. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  99403. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  99404. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  99405. }
  99406. }
  99407. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  99408. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  99409. }
  99410. }
  99411. }
  99412. });
  99413. // Render directly on top of existing scene without clearing
  99414. this.utilityLayerScene.autoClear = false;
  99415. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  99416. if (_this.shouldRender) {
  99417. _this.render();
  99418. }
  99419. });
  99420. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  99421. _this.dispose();
  99422. });
  99423. this._updateCamera();
  99424. }
  99425. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  99426. /**
  99427. * 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)
  99428. */
  99429. get: function () {
  99430. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  99431. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  99432. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  99433. UtilityLayerRenderer._DefaultUtilityLayer = null;
  99434. });
  99435. }
  99436. return UtilityLayerRenderer._DefaultUtilityLayer;
  99437. },
  99438. enumerable: true,
  99439. configurable: true
  99440. });
  99441. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  99442. /**
  99443. * 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)
  99444. */
  99445. get: function () {
  99446. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  99447. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  99448. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  99449. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  99450. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  99451. });
  99452. }
  99453. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  99454. },
  99455. enumerable: true,
  99456. configurable: true
  99457. });
  99458. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  99459. if (!prePointerInfo.skipOnPointerObservable) {
  99460. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  99461. this._lastPointerEvents[pointerEvent.pointerId] = true;
  99462. }
  99463. };
  99464. /**
  99465. * Renders the utility layers scene on top of the original scene
  99466. */
  99467. UtilityLayerRenderer.prototype.render = function () {
  99468. this._updateCamera();
  99469. if (this.utilityLayerScene.activeCamera) {
  99470. // Set the camera's scene to utility layers scene
  99471. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  99472. var camera = this.utilityLayerScene.activeCamera;
  99473. camera._scene = this.utilityLayerScene;
  99474. if (camera.leftCamera) {
  99475. camera.leftCamera._scene = this.utilityLayerScene;
  99476. }
  99477. if (camera.rightCamera) {
  99478. camera.rightCamera._scene = this.utilityLayerScene;
  99479. }
  99480. this.utilityLayerScene.render(false);
  99481. // Reset camera's scene back to original
  99482. camera._scene = oldScene;
  99483. if (camera.leftCamera) {
  99484. camera.leftCamera._scene = oldScene;
  99485. }
  99486. if (camera.rightCamera) {
  99487. camera.rightCamera._scene = oldScene;
  99488. }
  99489. }
  99490. };
  99491. /**
  99492. * Disposes of the renderer
  99493. */
  99494. UtilityLayerRenderer.prototype.dispose = function () {
  99495. this.onPointerOutObservable.clear();
  99496. if (this._afterRenderObserver) {
  99497. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  99498. }
  99499. if (this._sceneDisposeObserver) {
  99500. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  99501. }
  99502. if (this._originalPointerObserver) {
  99503. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  99504. }
  99505. this.utilityLayerScene.dispose();
  99506. };
  99507. UtilityLayerRenderer.prototype._updateCamera = function () {
  99508. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  99509. };
  99510. UtilityLayerRenderer._DefaultUtilityLayer = null;
  99511. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  99512. return UtilityLayerRenderer;
  99513. }());
  99514. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  99515. })(BABYLON || (BABYLON = {}));
  99516. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  99517. //# sourceMappingURL=babylon.behavior.js.map
  99518. var BABYLON;
  99519. (function (BABYLON) {
  99520. /**
  99521. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  99522. */
  99523. var PointerDragBehavior = /** @class */ (function () {
  99524. /**
  99525. * Creates a pointer drag behavior that can be attached to a mesh
  99526. * @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)
  99527. */
  99528. function PointerDragBehavior(options) {
  99529. /**
  99530. * 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)
  99531. */
  99532. this.maxDragAngle = 0;
  99533. /**
  99534. * @hidden
  99535. */
  99536. this._useAlternatePickedPointAboveMaxDragAngle = false;
  99537. /**
  99538. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  99539. */
  99540. this.currentDraggingPointerID = -1;
  99541. /**
  99542. * If the behavior is currently in a dragging state
  99543. */
  99544. this.dragging = false;
  99545. /**
  99546. * 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)
  99547. */
  99548. this.dragDeltaRatio = 0.2;
  99549. /**
  99550. * If the drag plane orientation should be updated during the dragging (Default: true)
  99551. */
  99552. this.updateDragPlane = true;
  99553. // Debug mode will display drag planes to help visualize behavior
  99554. this._debugMode = false;
  99555. this._moving = false;
  99556. /**
  99557. * Fires each time the attached mesh is dragged with the pointer
  99558. * * delta between last drag position and current drag position in world space
  99559. * * dragDistance along the drag axis
  99560. * * dragPlaneNormal normal of the current drag plane used during the drag
  99561. * * dragPlanePoint in world space where the drag intersects the drag plane
  99562. */
  99563. this.onDragObservable = new BABYLON.Observable();
  99564. /**
  99565. * Fires each time a drag begins (eg. mouse down on mesh)
  99566. */
  99567. this.onDragStartObservable = new BABYLON.Observable();
  99568. /**
  99569. * Fires each time a drag ends (eg. mouse release after drag)
  99570. */
  99571. this.onDragEndObservable = new BABYLON.Observable();
  99572. /**
  99573. * If the attached mesh should be moved when dragged
  99574. */
  99575. this.moveAttached = true;
  99576. /**
  99577. * If the drag behavior will react to drag events (Default: true)
  99578. */
  99579. this.enabled = true;
  99580. /**
  99581. * If camera controls should be detached during the drag
  99582. */
  99583. this.detachCameraControls = true;
  99584. /**
  99585. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  99586. */
  99587. this.useObjectOrienationForDragging = true;
  99588. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  99589. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  99590. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  99591. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  99592. this._attachedElement = null;
  99593. this._startDragRay = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  99594. this._lastPointerRay = {};
  99595. this._dragDelta = new BABYLON.Vector3();
  99596. // Variables to avoid instantiation in the below method
  99597. this._pointA = new BABYLON.Vector3(0, 0, 0);
  99598. this._pointB = new BABYLON.Vector3(0, 0, 0);
  99599. this._pointC = new BABYLON.Vector3(0, 0, 0);
  99600. this._lineA = new BABYLON.Vector3(0, 0, 0);
  99601. this._lineB = new BABYLON.Vector3(0, 0, 0);
  99602. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  99603. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  99604. this._options = options ? options : {};
  99605. var optionCount = 0;
  99606. if (this._options.dragAxis) {
  99607. optionCount++;
  99608. }
  99609. if (this._options.dragPlaneNormal) {
  99610. optionCount++;
  99611. }
  99612. if (optionCount > 1) {
  99613. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  99614. }
  99615. }
  99616. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  99617. /**
  99618. * The name of the behavior
  99619. */
  99620. get: function () {
  99621. return "PointerDrag";
  99622. },
  99623. enumerable: true,
  99624. configurable: true
  99625. });
  99626. /**
  99627. * Initializes the behavior
  99628. */
  99629. PointerDragBehavior.prototype.init = function () { };
  99630. /**
  99631. * Attaches the drag behavior the passed in mesh
  99632. * @param ownerNode The mesh that will be dragged around once attached
  99633. */
  99634. PointerDragBehavior.prototype.attach = function (ownerNode) {
  99635. var _this = this;
  99636. this._scene = ownerNode.getScene();
  99637. this._attachedNode = ownerNode;
  99638. // Initialize drag plane to not interfere with existing scene
  99639. if (!PointerDragBehavior._planeScene) {
  99640. if (this._debugMode) {
  99641. PointerDragBehavior._planeScene = this._scene;
  99642. }
  99643. else {
  99644. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  99645. PointerDragBehavior._planeScene.detachControl();
  99646. this._scene.getEngine().scenes.pop();
  99647. this._scene.onDisposeObservable.addOnce(function () {
  99648. PointerDragBehavior._planeScene.dispose();
  99649. PointerDragBehavior._planeScene = null;
  99650. });
  99651. }
  99652. }
  99653. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  99654. // State of the drag
  99655. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  99656. var pickPredicate = function (m) {
  99657. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  99658. };
  99659. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  99660. if (!_this.enabled) {
  99661. return;
  99662. }
  99663. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  99664. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  99665. _this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  99666. }
  99667. }
  99668. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  99669. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  99670. _this.releaseDrag();
  99671. }
  99672. }
  99673. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  99674. var pointerId = pointerInfo.event.pointerId;
  99675. // If drag was started with anyMouseID specified, set pointerID to the next mouse that moved
  99676. if (_this.currentDraggingPointerID === PointerDragBehavior._AnyMouseID && pointerId !== PointerDragBehavior._AnyMouseID && pointerInfo.event.pointerType == "mouse") {
  99677. if (_this._lastPointerRay[_this.currentDraggingPointerID]) {
  99678. _this._lastPointerRay[pointerId] = _this._lastPointerRay[_this.currentDraggingPointerID];
  99679. delete _this._lastPointerRay[_this.currentDraggingPointerID];
  99680. }
  99681. _this.currentDraggingPointerID = pointerId;
  99682. }
  99683. // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag()
  99684. if (!_this._lastPointerRay[pointerId]) {
  99685. _this._lastPointerRay[pointerId] = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  99686. }
  99687. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  99688. _this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);
  99689. _this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);
  99690. if (_this.currentDraggingPointerID == pointerId && _this.dragging) {
  99691. _this._moveDrag(pointerInfo.pickInfo.ray);
  99692. }
  99693. }
  99694. }
  99695. });
  99696. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  99697. if (_this._moving && _this.moveAttached) {
  99698. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(_this._attachedNode);
  99699. // Slowly move mesh to avoid jitter
  99700. _this._targetPosition.subtractToRef((_this._attachedNode).absolutePosition, _this._tmpVector);
  99701. _this._tmpVector.scaleInPlace(_this.dragDeltaRatio);
  99702. (_this._attachedNode).getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  99703. (_this._attachedNode).setAbsolutePosition(_this._tmpVector);
  99704. BABYLON.BoundingBoxGizmo._RestorePivotPoint(_this._attachedNode);
  99705. }
  99706. });
  99707. };
  99708. /**
  99709. * Force relase the drag action by code.
  99710. */
  99711. PointerDragBehavior.prototype.releaseDrag = function () {
  99712. this.dragging = false;
  99713. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  99714. this.currentDraggingPointerID = -1;
  99715. this._moving = false;
  99716. // Reattach camera controls
  99717. if (this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  99718. this._scene.activeCamera.attachControl(this._attachedElement, true);
  99719. }
  99720. };
  99721. /**
  99722. * Simulates the start of a pointer drag event on the behavior
  99723. * @param pointerId pointerID of the pointer that should be simulated (Default: Any mouse pointer ID)
  99724. * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh)
  99725. * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position)
  99726. */
  99727. PointerDragBehavior.prototype.startDrag = function (pointerId, fromRay, startPickedPoint) {
  99728. if (pointerId === void 0) { pointerId = PointerDragBehavior._AnyMouseID; }
  99729. this._startDrag(pointerId, fromRay, startPickedPoint);
  99730. var lastRay = this._lastPointerRay[pointerId];
  99731. if (pointerId === PointerDragBehavior._AnyMouseID) {
  99732. lastRay = this._lastPointerRay[Object.keys(this._lastPointerRay)[0]];
  99733. }
  99734. if (lastRay) {
  99735. // if there was a last pointer ray drag the object there
  99736. this._moveDrag(lastRay);
  99737. }
  99738. };
  99739. PointerDragBehavior.prototype._startDrag = function (pointerId, fromRay, startPickedPoint) {
  99740. if (!this._scene.activeCamera || this.dragging || !this._attachedNode) {
  99741. return;
  99742. }
  99743. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(this._attachedNode);
  99744. // Create start ray from the camera to the object
  99745. if (fromRay) {
  99746. this._startDragRay.direction.copyFrom(fromRay.direction);
  99747. this._startDragRay.origin.copyFrom(fromRay.origin);
  99748. }
  99749. else {
  99750. this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);
  99751. this._attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);
  99752. this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);
  99753. }
  99754. this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector);
  99755. var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);
  99756. if (pickedPoint) {
  99757. this.dragging = true;
  99758. this.currentDraggingPointerID = pointerId;
  99759. this.lastDragPosition.copyFrom(pickedPoint);
  99760. this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID });
  99761. this._targetPosition.copyFrom((this._attachedNode).absolutePosition);
  99762. // Detatch camera controls
  99763. if (this.detachCameraControls && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  99764. if (this._scene.activeCamera.inputs.attachedElement) {
  99765. this._attachedElement = this._scene.activeCamera.inputs.attachedElement;
  99766. this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement);
  99767. }
  99768. else {
  99769. this._attachedElement = null;
  99770. }
  99771. }
  99772. }
  99773. BABYLON.BoundingBoxGizmo._RestorePivotPoint(this._attachedNode);
  99774. };
  99775. PointerDragBehavior.prototype._moveDrag = function (ray) {
  99776. this._moving = true;
  99777. var pickedPoint = this._pickWithRayOnDragPlane(ray);
  99778. if (pickedPoint) {
  99779. if (this.updateDragPlane) {
  99780. this._updateDragPlanePosition(ray, pickedPoint);
  99781. }
  99782. var dragLength = 0;
  99783. // depending on the drag mode option drag accordingly
  99784. if (this._options.dragAxis) {
  99785. // Convert local drag axis to world
  99786. BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis);
  99787. // Project delta drag from the drag plane onto the drag axis
  99788. pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);
  99789. dragLength = BABYLON.Vector3.Dot(this._tmpVector, this._worldDragAxis);
  99790. this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);
  99791. }
  99792. else {
  99793. dragLength = this._dragDelta.length();
  99794. pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);
  99795. }
  99796. this._targetPosition.addInPlace(this._dragDelta);
  99797. this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID });
  99798. this.lastDragPosition.copyFrom(pickedPoint);
  99799. }
  99800. };
  99801. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  99802. var _this = this;
  99803. if (!ray) {
  99804. return null;
  99805. }
  99806. // Calculate angle between plane normal and ray
  99807. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  99808. // Correct if ray is casted from oposite side
  99809. if (angle > Math.PI / 2) {
  99810. angle = Math.PI - angle;
  99811. }
  99812. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  99813. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  99814. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  99815. // Invert ray direction along the towards object axis
  99816. this._tmpVector.copyFrom(ray.direction);
  99817. (this._attachedNode).absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  99818. this._alternatePickedPoint.normalize();
  99819. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  99820. this._tmpVector.addInPlace(this._alternatePickedPoint);
  99821. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  99822. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  99823. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  99824. this._alternatePickedPoint.addInPlace(this._tmpVector);
  99825. this._alternatePickedPoint.addInPlace((this._attachedNode).absolutePosition);
  99826. return this._alternatePickedPoint;
  99827. }
  99828. else {
  99829. return null;
  99830. }
  99831. }
  99832. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  99833. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  99834. return pickResult.pickedPoint;
  99835. }
  99836. else {
  99837. return null;
  99838. }
  99839. };
  99840. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  99841. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  99842. this._pointA.copyFrom(dragPlanePosition);
  99843. if (this._options.dragAxis) {
  99844. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  99845. // Calculate plane normal in direction of camera but perpendicular to drag axis
  99846. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  99847. ray.origin.subtractToRef(this._pointA, this._pointC);
  99848. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  99849. // Get perpendicular line from direction to camera and drag axis
  99850. this._pointB.subtractToRef(this._pointA, this._lineA);
  99851. this._pointC.subtractToRef(this._pointA, this._lineB);
  99852. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  99853. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  99854. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  99855. this._lookAt.normalize();
  99856. this._dragPlane.position.copyFrom(this._pointA);
  99857. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  99858. this._dragPlane.lookAt(this._lookAt);
  99859. }
  99860. else if (this._options.dragPlaneNormal) {
  99861. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  99862. this._dragPlane.position.copyFrom(this._pointA);
  99863. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  99864. this._dragPlane.lookAt(this._lookAt);
  99865. }
  99866. else {
  99867. this._dragPlane.position.copyFrom(this._pointA);
  99868. this._dragPlane.lookAt(ray.origin);
  99869. }
  99870. this._dragPlane.computeWorldMatrix(true);
  99871. };
  99872. /**
  99873. * Detaches the behavior from the mesh
  99874. */
  99875. PointerDragBehavior.prototype.detach = function () {
  99876. if (this._pointerObserver) {
  99877. this._scene.onPointerObservable.remove(this._pointerObserver);
  99878. }
  99879. if (this._beforeRenderObserver) {
  99880. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  99881. }
  99882. };
  99883. PointerDragBehavior._AnyMouseID = -2;
  99884. return PointerDragBehavior;
  99885. }());
  99886. BABYLON.PointerDragBehavior = PointerDragBehavior;
  99887. })(BABYLON || (BABYLON = {}));
  99888. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  99889. var BABYLON;
  99890. (function (BABYLON) {
  99891. /**
  99892. * A behavior that when attached to a mesh will allow the mesh to be scaled
  99893. */
  99894. var MultiPointerScaleBehavior = /** @class */ (function () {
  99895. /**
  99896. * Instantiate a new behavior that when attached to a mesh will allow the mesh to be scaled
  99897. */
  99898. function MultiPointerScaleBehavior() {
  99899. this._startDistance = 0;
  99900. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  99901. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  99902. this._sceneRenderObserver = null;
  99903. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  99904. this._dragBehaviorA.moveAttached = false;
  99905. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  99906. this._dragBehaviorB.moveAttached = false;
  99907. }
  99908. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  99909. /**
  99910. * The name of the behavior
  99911. */
  99912. get: function () {
  99913. return "MultiPointerScale";
  99914. },
  99915. enumerable: true,
  99916. configurable: true
  99917. });
  99918. /**
  99919. * Initializes the behavior
  99920. */
  99921. MultiPointerScaleBehavior.prototype.init = function () { };
  99922. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  99923. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  99924. };
  99925. /**
  99926. * Attaches the scale behavior the passed in mesh
  99927. * @param ownerNode The mesh that will be scaled around once attached
  99928. */
  99929. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  99930. var _this = this;
  99931. this._ownerNode = ownerNode;
  99932. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  99933. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  99934. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  99935. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  99936. _this._dragBehaviorA.releaseDrag();
  99937. }
  99938. else {
  99939. _this._initialScale.copyFrom(ownerNode.scaling);
  99940. _this._startDistance = _this._getCurrentDistance();
  99941. }
  99942. }
  99943. });
  99944. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  99945. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  99946. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  99947. _this._dragBehaviorB.releaseDrag();
  99948. }
  99949. else {
  99950. _this._initialScale.copyFrom(ownerNode.scaling);
  99951. _this._startDistance = _this._getCurrentDistance();
  99952. }
  99953. }
  99954. });
  99955. // Once both drag behaviors are active scale based on the distance between the two pointers
  99956. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  99957. behavior.onDragObservable.add(function () {
  99958. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  99959. var ratio = _this._getCurrentDistance() / _this._startDistance;
  99960. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  99961. }
  99962. });
  99963. });
  99964. ownerNode.addBehavior(this._dragBehaviorA);
  99965. ownerNode.addBehavior(this._dragBehaviorB);
  99966. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  99967. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  99968. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  99969. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  99970. if (change.length() > 0.01) {
  99971. ownerNode.scaling.addInPlace(change);
  99972. }
  99973. }
  99974. });
  99975. };
  99976. /**
  99977. * Detaches the behavior from the mesh
  99978. */
  99979. MultiPointerScaleBehavior.prototype.detach = function () {
  99980. var _this = this;
  99981. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  99982. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  99983. behavior.onDragStartObservable.clear();
  99984. behavior.onDragObservable.clear();
  99985. _this._ownerNode.removeBehavior(behavior);
  99986. });
  99987. };
  99988. return MultiPointerScaleBehavior;
  99989. }());
  99990. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  99991. })(BABYLON || (BABYLON = {}));
  99992. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  99993. var BABYLON;
  99994. (function (BABYLON) {
  99995. /**
  99996. * 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
  99997. */
  99998. var SixDofDragBehavior = /** @class */ (function () {
  99999. /**
  100000. * 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
  100001. */
  100002. function SixDofDragBehavior() {
  100003. this._sceneRenderObserver = null;
  100004. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  100005. this._moving = false;
  100006. this._startingOrientation = new BABYLON.Quaternion();
  100007. /**
  100008. * 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)
  100009. */
  100010. this.zDragFactor = 3;
  100011. /**
  100012. * If the behavior is currently in a dragging state
  100013. */
  100014. this.dragging = false;
  100015. /**
  100016. * 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)
  100017. */
  100018. this.dragDeltaRatio = 0.2;
  100019. /**
  100020. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  100021. */
  100022. this.currentDraggingPointerID = -1;
  100023. /**
  100024. * If camera controls should be detached during the drag
  100025. */
  100026. this.detachCameraControls = true;
  100027. /**
  100028. * Fires each time a drag starts
  100029. */
  100030. this.onDragStartObservable = new BABYLON.Observable();
  100031. /**
  100032. * Fires each time a drag ends (eg. mouse release after drag)
  100033. */
  100034. this.onDragEndObservable = new BABYLON.Observable();
  100035. }
  100036. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  100037. /**
  100038. * The name of the behavior
  100039. */
  100040. get: function () {
  100041. return "SixDofDrag";
  100042. },
  100043. enumerable: true,
  100044. configurable: true
  100045. });
  100046. /**
  100047. * Initializes the behavior
  100048. */
  100049. SixDofDragBehavior.prototype.init = function () { };
  100050. /**
  100051. * Attaches the scale behavior the passed in mesh
  100052. * @param ownerNode The mesh that will be scaled around once attached
  100053. */
  100054. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  100055. var _this = this;
  100056. this._ownerNode = ownerNode;
  100057. this._scene = this._ownerNode.getScene();
  100058. if (!SixDofDragBehavior._virtualScene) {
  100059. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  100060. SixDofDragBehavior._virtualScene.detachControl();
  100061. this._scene.getEngine().scenes.pop();
  100062. }
  100063. var pickedMesh = null;
  100064. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  100065. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  100066. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  100067. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  100068. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  100069. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  100070. var pickPredicate = function (m) {
  100071. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  100072. };
  100073. var attachedElement = null;
  100074. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  100075. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  100076. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  100077. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  100078. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  100079. }
  100080. pickedMesh = _this._ownerNode;
  100081. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  100082. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  100083. // Set position and orientation of the controller
  100084. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  100085. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  100086. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  100087. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  100088. pickedMesh.computeWorldMatrix();
  100089. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  100090. if (!pickedMesh.rotationQuaternion) {
  100091. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  100092. }
  100093. var oldParent = pickedMesh.parent;
  100094. pickedMesh.setParent(null);
  100095. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  100096. pickedMesh.setParent(oldParent);
  100097. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  100098. // Update state
  100099. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  100100. _this.dragging = true;
  100101. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  100102. // Detatch camera controls
  100103. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  100104. if (_this._scene.activeCamera.inputs.attachedElement) {
  100105. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  100106. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  100107. }
  100108. else {
  100109. attachedElement = null;
  100110. }
  100111. }
  100112. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  100113. _this.onDragStartObservable.notifyObservers({});
  100114. }
  100115. }
  100116. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  100117. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  100118. _this.dragging = false;
  100119. _this._moving = false;
  100120. _this.currentDraggingPointerID = -1;
  100121. pickedMesh = null;
  100122. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  100123. // Reattach camera controls
  100124. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  100125. _this._scene.activeCamera.attachControl(attachedElement, true);
  100126. }
  100127. _this.onDragEndObservable.notifyObservers({});
  100128. }
  100129. }
  100130. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  100131. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  100132. var zDragFactor = _this.zDragFactor;
  100133. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  100134. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  100135. zDragFactor = 0;
  100136. }
  100137. // Calculate controller drag distance in controller space
  100138. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  100139. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  100140. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  100141. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  100142. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  100143. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  100144. if (_this._virtualDragMesh.position.z < 0) {
  100145. _this._virtualDragMesh.position.z = 0;
  100146. }
  100147. // Update the controller position
  100148. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  100149. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  100150. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  100151. // Move the virtualObjectsPosition into the picked mesh's space if needed
  100152. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  100153. if (pickedMesh.parent) {
  100154. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  100155. }
  100156. if (!_this._moving) {
  100157. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  100158. }
  100159. _this._moving = true;
  100160. }
  100161. }
  100162. });
  100163. var tmpQuaternion = new BABYLON.Quaternion();
  100164. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  100165. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  100166. if (_this.dragging && _this._moving && pickedMesh) {
  100167. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  100168. // Slowly move mesh to avoid jitter
  100169. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  100170. // Get change in rotation
  100171. tmpQuaternion.copyFrom(_this._startingOrientation);
  100172. tmpQuaternion.x = -tmpQuaternion.x;
  100173. tmpQuaternion.y = -tmpQuaternion.y;
  100174. tmpQuaternion.z = -tmpQuaternion.z;
  100175. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  100176. // Convert change in rotation to only y axis rotation
  100177. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  100178. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  100179. // Slowly move mesh to avoid jitter
  100180. var oldParent = pickedMesh.parent;
  100181. pickedMesh.setParent(null);
  100182. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  100183. pickedMesh.setParent(oldParent);
  100184. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  100185. }
  100186. });
  100187. };
  100188. /**
  100189. * Detaches the behavior from the mesh
  100190. */
  100191. SixDofDragBehavior.prototype.detach = function () {
  100192. if (this._scene) {
  100193. this._scene.onPointerObservable.remove(this._pointerObserver);
  100194. }
  100195. if (this._ownerNode) {
  100196. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  100197. }
  100198. if (this._virtualOriginMesh) {
  100199. this._virtualOriginMesh.dispose();
  100200. }
  100201. if (this._virtualDragMesh) {
  100202. this._virtualDragMesh.dispose();
  100203. }
  100204. this.onDragEndObservable.clear();
  100205. this.onDragStartObservable.clear();
  100206. };
  100207. return SixDofDragBehavior;
  100208. }());
  100209. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  100210. })(BABYLON || (BABYLON = {}));
  100211. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  100212. var BABYLON;
  100213. (function (BABYLON) {
  100214. /**
  100215. * @hidden
  100216. */
  100217. var FaceDirectionInfo = /** @class */ (function () {
  100218. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  100219. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  100220. if (diff === void 0) { diff = 0; }
  100221. if (ignore === void 0) { ignore = false; }
  100222. this.direction = direction;
  100223. this.rotatedDirection = rotatedDirection;
  100224. this.diff = diff;
  100225. this.ignore = ignore;
  100226. }
  100227. return FaceDirectionInfo;
  100228. }());
  100229. /**
  100230. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  100231. */
  100232. var AttachToBoxBehavior = /** @class */ (function () {
  100233. /**
  100234. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  100235. * @param ui The transform node that should be attched to the mesh
  100236. */
  100237. function AttachToBoxBehavior(ui) {
  100238. this.ui = ui;
  100239. /**
  100240. * The name of the behavior
  100241. */
  100242. this.name = "AttachToBoxBehavior";
  100243. /**
  100244. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  100245. */
  100246. this.distanceAwayFromFace = 0.15;
  100247. /**
  100248. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  100249. */
  100250. this.distanceAwayFromBottomOfFace = 0.15;
  100251. 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))];
  100252. this._tmpMatrix = new BABYLON.Matrix();
  100253. this._tmpVector = new BABYLON.Vector3();
  100254. this._zeroVector = BABYLON.Vector3.Zero();
  100255. this._lookAtTmpMatrix = new BABYLON.Matrix();
  100256. /* Does nothing */
  100257. }
  100258. /**
  100259. * Initializes the behavior
  100260. */
  100261. AttachToBoxBehavior.prototype.init = function () {
  100262. /* Does nothing */
  100263. };
  100264. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  100265. var _this = this;
  100266. // Go over each face and calculate the angle between the face's normal and targetDirection
  100267. this._faceVectors.forEach(function (v) {
  100268. if (!_this._target.rotationQuaternion) {
  100269. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  100270. }
  100271. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  100272. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  100273. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  100274. });
  100275. // Return the face information of the one with the normal closeset to target direction
  100276. return this._faceVectors.reduce(function (min, p) {
  100277. if (min.ignore) {
  100278. return p;
  100279. }
  100280. else if (p.ignore) {
  100281. return min;
  100282. }
  100283. else {
  100284. return min.diff < p.diff ? min : p;
  100285. }
  100286. }, this._faceVectors[0]);
  100287. };
  100288. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  100289. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  100290. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  100291. this._lookAtTmpMatrix.invert();
  100292. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  100293. };
  100294. /**
  100295. * Attaches the AttachToBoxBehavior to the passed in mesh
  100296. * @param target The mesh that the specified node will be attached to
  100297. */
  100298. AttachToBoxBehavior.prototype.attach = function (target) {
  100299. var _this = this;
  100300. this._target = target;
  100301. this._scene = this._target.getScene();
  100302. // Every frame, update the app bars position
  100303. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  100304. if (!_this._scene.activeCamera) {
  100305. return;
  100306. }
  100307. // Find the face closest to the cameras position
  100308. var cameraPos = _this._scene.activeCamera.position;
  100309. if (_this._scene.activeCamera.devicePosition) {
  100310. cameraPos = _this._scene.activeCamera.devicePosition;
  100311. }
  100312. var facing = _this._closestFace(cameraPos.subtract(target.position));
  100313. if (_this._scene.activeCamera.leftCamera) {
  100314. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  100315. }
  100316. else {
  100317. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  100318. }
  100319. // Get camera up direction
  100320. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  100321. // Ignore faces to not select a parrelel face for the up vector of the UI
  100322. _this._faceVectors.forEach(function (v) {
  100323. if (facing.direction.x && v.direction.x) {
  100324. v.ignore = true;
  100325. }
  100326. if (facing.direction.y && v.direction.y) {
  100327. v.ignore = true;
  100328. }
  100329. if (facing.direction.z && v.direction.z) {
  100330. v.ignore = true;
  100331. }
  100332. });
  100333. var facingUp = _this._closestFace(_this._tmpVector);
  100334. // Unignore faces
  100335. _this._faceVectors.forEach(function (v) {
  100336. v.ignore = false;
  100337. });
  100338. // Position the app bar on that face
  100339. _this.ui.position.copyFrom(target.position);
  100340. if (facing.direction.x) {
  100341. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  100342. _this.ui.position.addInPlace(_this._tmpVector);
  100343. }
  100344. if (facing.direction.y) {
  100345. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  100346. _this.ui.position.addInPlace(_this._tmpVector);
  100347. }
  100348. if (facing.direction.z) {
  100349. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  100350. _this.ui.position.addInPlace(_this._tmpVector);
  100351. }
  100352. // Rotate to be oriented properly to the camera
  100353. if (!_this.ui.rotationQuaternion) {
  100354. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  100355. }
  100356. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  100357. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  100358. // Place ui the correct distance from the bottom of the mesh
  100359. if (facingUp.direction.x) {
  100360. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  100361. }
  100362. if (facingUp.direction.y) {
  100363. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  100364. }
  100365. if (facingUp.direction.z) {
  100366. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  100367. }
  100368. _this.ui.position.addInPlace(_this._tmpVector);
  100369. });
  100370. };
  100371. /**
  100372. * Detaches the behavior from the mesh
  100373. */
  100374. AttachToBoxBehavior.prototype.detach = function () {
  100375. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  100376. };
  100377. return AttachToBoxBehavior;
  100378. }());
  100379. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  100380. })(BABYLON || (BABYLON = {}));
  100381. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  100382. var BABYLON;
  100383. (function (BABYLON) {
  100384. /**
  100385. * A behavior that when attached to a mesh will allow the mesh to fade in and out
  100386. */
  100387. var FadeInOutBehavior = /** @class */ (function () {
  100388. /**
  100389. * Instatiates the FadeInOutBehavior
  100390. */
  100391. function FadeInOutBehavior() {
  100392. var _this = this;
  100393. /**
  100394. * Time in milliseconds to delay before fading in (Default: 0)
  100395. */
  100396. this.delay = 0;
  100397. /**
  100398. * Time in milliseconds for the mesh to fade in (Default: 300)
  100399. */
  100400. this.fadeInTime = 300;
  100401. this._millisecondsPerFrame = 1000 / 60;
  100402. this._hovered = false;
  100403. this._hoverValue = 0;
  100404. this._ownerNode = null;
  100405. this._update = function () {
  100406. if (_this._ownerNode) {
  100407. _this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame;
  100408. _this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime);
  100409. if (_this._ownerNode.visibility > 1) {
  100410. _this._setAllVisibility(_this._ownerNode, 1);
  100411. _this._hoverValue = _this.fadeInTime + _this.delay;
  100412. return;
  100413. }
  100414. else if (_this._ownerNode.visibility < 0) {
  100415. _this._setAllVisibility(_this._ownerNode, 0);
  100416. if (_this._hoverValue < 0) {
  100417. _this._hoverValue = 0;
  100418. return;
  100419. }
  100420. }
  100421. setTimeout(_this._update, _this._millisecondsPerFrame);
  100422. }
  100423. };
  100424. }
  100425. Object.defineProperty(FadeInOutBehavior.prototype, "name", {
  100426. /**
  100427. * The name of the behavior
  100428. */
  100429. get: function () {
  100430. return "FadeInOut";
  100431. },
  100432. enumerable: true,
  100433. configurable: true
  100434. });
  100435. /**
  100436. * Initializes the behavior
  100437. */
  100438. FadeInOutBehavior.prototype.init = function () {
  100439. };
  100440. /**
  100441. * Attaches the fade behavior on the passed in mesh
  100442. * @param ownerNode The mesh that will be faded in/out once attached
  100443. */
  100444. FadeInOutBehavior.prototype.attach = function (ownerNode) {
  100445. this._ownerNode = ownerNode;
  100446. this._setAllVisibility(this._ownerNode, 0);
  100447. };
  100448. /**
  100449. * Detaches the behavior from the mesh
  100450. */
  100451. FadeInOutBehavior.prototype.detach = function () {
  100452. this._ownerNode = null;
  100453. };
  100454. /**
  100455. * Triggers the mesh to begin fading in or out
  100456. * @param value if the object should fade in or out (true to fade in)
  100457. */
  100458. FadeInOutBehavior.prototype.fadeIn = function (value) {
  100459. this._hovered = value;
  100460. this._update();
  100461. };
  100462. FadeInOutBehavior.prototype._setAllVisibility = function (mesh, value) {
  100463. var _this = this;
  100464. mesh.visibility = value;
  100465. mesh.getChildMeshes().forEach(function (c) {
  100466. _this._setAllVisibility(c, value);
  100467. });
  100468. };
  100469. return FadeInOutBehavior;
  100470. }());
  100471. BABYLON.FadeInOutBehavior = FadeInOutBehavior;
  100472. })(BABYLON || (BABYLON = {}));
  100473. //# sourceMappingURL=babylon.fadeInOutBehavior.js.map
  100474. var BABYLON;
  100475. (function (BABYLON) {
  100476. /**
  100477. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  100478. */
  100479. var Gizmo = /** @class */ (function () {
  100480. /**
  100481. * Creates a gizmo
  100482. * @param gizmoLayer The utility layer the gizmo will be added to
  100483. */
  100484. function Gizmo(
  100485. /** The utility layer the gizmo will be added to */
  100486. gizmoLayer) {
  100487. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  100488. var _this = this;
  100489. this.gizmoLayer = gizmoLayer;
  100490. /**
  100491. * Ratio for the scale of the gizmo (Default: 1)
  100492. */
  100493. this.scaleRatio = 1;
  100494. this._tmpMatrix = new BABYLON.Matrix();
  100495. /**
  100496. * If a custom mesh has been set (Default: false)
  100497. */
  100498. this._customMeshSet = false;
  100499. /**
  100500. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  100501. */
  100502. this.updateGizmoRotationToMatchAttachedMesh = true;
  100503. /**
  100504. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  100505. */
  100506. this.updateGizmoPositionToMatchAttachedMesh = true;
  100507. /**
  100508. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  100509. */
  100510. this._updateScale = true;
  100511. this._interactionsEnabled = true;
  100512. this._tempVector = new BABYLON.Vector3();
  100513. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  100514. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  100515. _this._update();
  100516. });
  100517. this.attachedMesh = null;
  100518. }
  100519. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  100520. /**
  100521. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  100522. * * When set, interactions will be enabled
  100523. */
  100524. get: function () {
  100525. return this._attachedMesh;
  100526. },
  100527. set: function (value) {
  100528. this._attachedMesh = value;
  100529. this._rootMesh.setEnabled(value ? true : false);
  100530. this._attachedMeshChanged(value);
  100531. },
  100532. enumerable: true,
  100533. configurable: true
  100534. });
  100535. /**
  100536. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  100537. * @param mesh The mesh to replace the default mesh of the gizmo
  100538. */
  100539. Gizmo.prototype.setCustomMesh = function (mesh) {
  100540. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  100541. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  100542. }
  100543. this._rootMesh.getChildMeshes().forEach(function (c) {
  100544. c.dispose();
  100545. });
  100546. mesh.parent = this._rootMesh;
  100547. this._customMeshSet = true;
  100548. };
  100549. Gizmo.prototype._attachedMeshChanged = function (value) {
  100550. };
  100551. /**
  100552. * @hidden
  100553. * Updates the gizmo to match the attached mesh's position/rotation
  100554. */
  100555. Gizmo.prototype._update = function () {
  100556. if (this.attachedMesh) {
  100557. if (this.updateGizmoRotationToMatchAttachedMesh) {
  100558. if (!this._rootMesh.rotationQuaternion) {
  100559. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  100560. }
  100561. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  100562. this._tempVector.copyFrom(this.attachedMesh.scaling);
  100563. if (this.attachedMesh.scaling.x < 0) {
  100564. this.attachedMesh.scaling.x *= -1;
  100565. }
  100566. if (this.attachedMesh.scaling.y < 0) {
  100567. this.attachedMesh.scaling.y *= -1;
  100568. }
  100569. if (this.attachedMesh.scaling.z < 0) {
  100570. this.attachedMesh.scaling.z *= -1;
  100571. }
  100572. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  100573. this.attachedMesh.scaling.copyFrom(this._tempVector);
  100574. this.attachedMesh.computeWorldMatrix();
  100575. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  100576. }
  100577. else if (this._rootMesh.rotationQuaternion) {
  100578. this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
  100579. }
  100580. if (this.updateGizmoPositionToMatchAttachedMesh) {
  100581. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  100582. }
  100583. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  100584. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
  100585. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  100586. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  100587. }
  100588. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  100589. var dist = this._tempVector.length() * this.scaleRatio;
  100590. this._rootMesh.scaling.set(dist, dist, dist);
  100591. }
  100592. }
  100593. };
  100594. /**
  100595. * Disposes of the gizmo
  100596. */
  100597. Gizmo.prototype.dispose = function () {
  100598. this._rootMesh.dispose();
  100599. if (this._beforeRenderObserver) {
  100600. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  100601. }
  100602. };
  100603. return Gizmo;
  100604. }());
  100605. BABYLON.Gizmo = Gizmo;
  100606. })(BABYLON || (BABYLON = {}));
  100607. //# sourceMappingURL=babylon.gizmo.js.map
  100608. var BABYLON;
  100609. (function (BABYLON) {
  100610. /**
  100611. * Single axis drag gizmo
  100612. */
  100613. var AxisDragGizmo = /** @class */ (function (_super) {
  100614. __extends(AxisDragGizmo, _super);
  100615. /**
  100616. * Creates an AxisDragGizmo
  100617. * @param gizmoLayer The utility layer the gizmo will be added to
  100618. * @param dragAxis The axis which the gizmo will be able to drag on
  100619. * @param color The color of the gizmo
  100620. */
  100621. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  100622. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  100623. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  100624. var _this = _super.call(this, gizmoLayer) || this;
  100625. _this._pointerObserver = null;
  100626. /**
  100627. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  100628. */
  100629. _this.snapDistance = 0;
  100630. /**
  100631. * Event that fires each time the gizmo snaps to a new location.
  100632. * * snapDistance is the the change in distance
  100633. */
  100634. _this.onSnapObservable = new BABYLON.Observable();
  100635. // Create Material
  100636. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  100637. coloredMaterial.disableLighting = true;
  100638. coloredMaterial.emissiveColor = color;
  100639. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  100640. hoverMaterial.disableLighting = true;
  100641. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  100642. // Build mesh on root node
  100643. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  100644. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  100645. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  100646. arrowTail.color = coloredMaterial.emissiveColor;
  100647. arrow.addChild(arrowMesh);
  100648. arrow.addChild(arrowTail);
  100649. // Position arrow pointing in its drag axis
  100650. arrowMesh.scaling.scaleInPlace(0.05);
  100651. arrowMesh.material = coloredMaterial;
  100652. arrowMesh.rotation.x = Math.PI / 2;
  100653. arrowMesh.position.z += 0.3;
  100654. arrowTail.scaling.scaleInPlace(0.26);
  100655. arrowTail.rotation.x = Math.PI / 2;
  100656. arrowTail.material = coloredMaterial;
  100657. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  100658. arrow.scaling.scaleInPlace(1 / 3);
  100659. _this._rootMesh.addChild(arrow);
  100660. var currentSnapDragDistance = 0;
  100661. var tmpVector = new BABYLON.Vector3();
  100662. var tmpSnapEvent = { snapDistance: 0 };
  100663. // Add drag behavior to handle events when the gizmo is dragged
  100664. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  100665. _this.dragBehavior.moveAttached = false;
  100666. _this._rootMesh.addBehavior(_this.dragBehavior);
  100667. var localDelta = new BABYLON.Vector3();
  100668. var tmpMatrix = new BABYLON.Matrix();
  100669. _this.dragBehavior.onDragObservable.add(function (event) {
  100670. if (_this.attachedMesh) {
  100671. // Convert delta to local translation if it has a parent
  100672. if (_this.attachedMesh.parent) {
  100673. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  100674. tmpMatrix.setTranslationFromFloats(0, 0, 0);
  100675. BABYLON.Vector3.TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
  100676. }
  100677. else {
  100678. localDelta.copyFrom(event.delta);
  100679. }
  100680. // Snapping logic
  100681. if (_this.snapDistance == 0) {
  100682. _this.attachedMesh.position.addInPlace(localDelta);
  100683. }
  100684. else {
  100685. currentSnapDragDistance += event.dragDistance;
  100686. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  100687. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  100688. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  100689. localDelta.normalizeToRef(tmpVector);
  100690. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  100691. _this.attachedMesh.position.addInPlace(tmpVector);
  100692. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  100693. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  100694. }
  100695. }
  100696. }
  100697. });
  100698. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  100699. if (_this._customMeshSet) {
  100700. return;
  100701. }
  100702. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  100703. var material = isHovered ? hoverMaterial : coloredMaterial;
  100704. _this._rootMesh.getChildMeshes().forEach(function (m) {
  100705. m.material = material;
  100706. if (m.color) {
  100707. m.color = material.emissiveColor;
  100708. }
  100709. });
  100710. });
  100711. return _this;
  100712. }
  100713. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  100714. if (this.dragBehavior) {
  100715. this.dragBehavior.enabled = value ? true : false;
  100716. }
  100717. };
  100718. /**
  100719. * Disposes of the gizmo
  100720. */
  100721. AxisDragGizmo.prototype.dispose = function () {
  100722. this.onSnapObservable.clear();
  100723. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  100724. this.dragBehavior.detach();
  100725. _super.prototype.dispose.call(this);
  100726. };
  100727. return AxisDragGizmo;
  100728. }(BABYLON.Gizmo));
  100729. BABYLON.AxisDragGizmo = AxisDragGizmo;
  100730. })(BABYLON || (BABYLON = {}));
  100731. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  100732. var BABYLON;
  100733. (function (BABYLON) {
  100734. /**
  100735. * Single axis scale gizmo
  100736. */
  100737. var AxisScaleGizmo = /** @class */ (function (_super) {
  100738. __extends(AxisScaleGizmo, _super);
  100739. /**
  100740. * Creates an AxisScaleGizmo
  100741. * @param gizmoLayer The utility layer the gizmo will be added to
  100742. * @param dragAxis The axis which the gizmo will be able to scale on
  100743. * @param color The color of the gizmo
  100744. */
  100745. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  100746. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  100747. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  100748. var _this = _super.call(this, gizmoLayer) || this;
  100749. _this._pointerObserver = null;
  100750. /**
  100751. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  100752. */
  100753. _this.snapDistance = 0;
  100754. /**
  100755. * Event that fires each time the gizmo snaps to a new location.
  100756. * * snapDistance is the the change in distance
  100757. */
  100758. _this.onSnapObservable = new BABYLON.Observable();
  100759. /**
  100760. * If the scaling operation should be done on all axis (default: false)
  100761. */
  100762. _this.uniformScaling = false;
  100763. // Create Material
  100764. _this._coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  100765. _this._coloredMaterial.disableLighting = true;
  100766. _this._coloredMaterial.emissiveColor = color;
  100767. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  100768. hoverMaterial.disableLighting = true;
  100769. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  100770. // Build mesh on root node
  100771. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  100772. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  100773. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  100774. arrowTail.color = _this._coloredMaterial.emissiveColor;
  100775. arrow.addChild(arrowMesh);
  100776. arrow.addChild(arrowTail);
  100777. // Position arrow pointing in its drag axis
  100778. arrowMesh.scaling.scaleInPlace(0.1);
  100779. arrowMesh.material = _this._coloredMaterial;
  100780. arrowMesh.rotation.x = Math.PI / 2;
  100781. arrowMesh.position.z += 0.3;
  100782. arrowTail.scaling.scaleInPlace(0.26);
  100783. arrowTail.rotation.x = Math.PI / 2;
  100784. arrowTail.material = _this._coloredMaterial;
  100785. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  100786. _this._rootMesh.addChild(arrow);
  100787. arrow.scaling.scaleInPlace(1 / 3);
  100788. // Add drag behavior to handle events when the gizmo is dragged
  100789. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  100790. _this.dragBehavior.moveAttached = false;
  100791. _this._rootMesh.addBehavior(_this.dragBehavior);
  100792. var currentSnapDragDistance = 0;
  100793. var tmpVector = new BABYLON.Vector3();
  100794. var tmpSnapEvent = { snapDistance: 0 };
  100795. _this.dragBehavior.onDragObservable.add(function (event) {
  100796. if (_this.attachedMesh) {
  100797. // Snapping logic
  100798. var snapped = false;
  100799. var dragSteps = 0;
  100800. if (_this.uniformScaling) {
  100801. _this.attachedMesh.scaling.normalizeToRef(tmpVector);
  100802. if (tmpVector.y < 0) {
  100803. tmpVector.scaleInPlace(-1);
  100804. }
  100805. }
  100806. else {
  100807. tmpVector.copyFrom(dragAxis);
  100808. }
  100809. if (_this.snapDistance == 0) {
  100810. tmpVector.scaleToRef(event.dragDistance, tmpVector);
  100811. }
  100812. else {
  100813. currentSnapDragDistance += event.dragDistance;
  100814. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  100815. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  100816. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  100817. tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  100818. snapped = true;
  100819. }
  100820. else {
  100821. tmpVector.scaleInPlace(0);
  100822. }
  100823. }
  100824. _this.attachedMesh.scaling.addInPlace(tmpVector);
  100825. if (snapped) {
  100826. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  100827. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  100828. }
  100829. }
  100830. });
  100831. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  100832. if (_this._customMeshSet) {
  100833. return;
  100834. }
  100835. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  100836. var material = isHovered ? hoverMaterial : _this._coloredMaterial;
  100837. _this._rootMesh.getChildMeshes().forEach(function (m) {
  100838. m.material = material;
  100839. if (m.color) {
  100840. m.color = material.emissiveColor;
  100841. }
  100842. });
  100843. });
  100844. return _this;
  100845. }
  100846. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  100847. if (this.dragBehavior) {
  100848. this.dragBehavior.enabled = value ? true : false;
  100849. }
  100850. };
  100851. /**
  100852. * Disposes of the gizmo
  100853. */
  100854. AxisScaleGizmo.prototype.dispose = function () {
  100855. this.onSnapObservable.clear();
  100856. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  100857. this.dragBehavior.detach();
  100858. _super.prototype.dispose.call(this);
  100859. };
  100860. /**
  100861. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  100862. * @param mesh The mesh to replace the default mesh of the gizmo
  100863. * @param useGizmoMaterial If the gizmo's default material should be used (default: false)
  100864. */
  100865. AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) {
  100866. var _this = this;
  100867. if (useGizmoMaterial === void 0) { useGizmoMaterial = false; }
  100868. _super.prototype.setCustomMesh.call(this, mesh);
  100869. if (useGizmoMaterial) {
  100870. this._rootMesh.getChildMeshes().forEach(function (m) {
  100871. m.material = _this._coloredMaterial;
  100872. if (m.color) {
  100873. m.color = _this._coloredMaterial.emissiveColor;
  100874. }
  100875. });
  100876. this._customMeshSet = false;
  100877. }
  100878. };
  100879. return AxisScaleGizmo;
  100880. }(BABYLON.Gizmo));
  100881. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  100882. })(BABYLON || (BABYLON = {}));
  100883. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  100884. var BABYLON;
  100885. (function (BABYLON) {
  100886. /**
  100887. * Single plane rotation gizmo
  100888. */
  100889. var PlaneRotationGizmo = /** @class */ (function (_super) {
  100890. __extends(PlaneRotationGizmo, _super);
  100891. /**
  100892. * Creates a PlaneRotationGizmo
  100893. * @param gizmoLayer The utility layer the gizmo will be added to
  100894. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  100895. * @param color The color of the gizmo
  100896. * @param tessellation Amount of tessellation to be used when creating rotation circles
  100897. */
  100898. function PlaneRotationGizmo(planeNormal, color, gizmoLayer, tessellation) {
  100899. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  100900. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  100901. if (tessellation === void 0) { tessellation = 32; }
  100902. var _this = _super.call(this, gizmoLayer) || this;
  100903. _this._pointerObserver = null;
  100904. /**
  100905. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  100906. */
  100907. _this.snapDistance = 0;
  100908. /**
  100909. * Event that fires each time the gizmo snaps to a new location.
  100910. * * snapDistance is the the change in distance
  100911. */
  100912. _this.onSnapObservable = new BABYLON.Observable();
  100913. // Create Material
  100914. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  100915. coloredMaterial.disableLighting = true;
  100916. coloredMaterial.emissiveColor = color;
  100917. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  100918. hoverMaterial.disableLighting = true;
  100919. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  100920. // Build mesh on root node
  100921. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  100922. // Create circle out of lines
  100923. var radius = 0.8;
  100924. var points = new Array();
  100925. for (var i = 0; i < tessellation; i++) {
  100926. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  100927. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  100928. }
  100929. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  100930. rotationMesh.color = coloredMaterial.emissiveColor;
  100931. // Position arrow pointing in its drag axis
  100932. rotationMesh.scaling.scaleInPlace(0.26);
  100933. rotationMesh.material = coloredMaterial;
  100934. rotationMesh.rotation.x = Math.PI / 2;
  100935. parentMesh.addChild(rotationMesh);
  100936. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  100937. _this._rootMesh.addChild(parentMesh);
  100938. parentMesh.scaling.scaleInPlace(1 / 3);
  100939. // Add drag behavior to handle events when the gizmo is dragged
  100940. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  100941. _this.dragBehavior.moveAttached = false;
  100942. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  100943. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  100944. _this._rootMesh.addBehavior(_this.dragBehavior);
  100945. var lastDragPosition = new BABYLON.Vector3();
  100946. _this.dragBehavior.onDragStartObservable.add(function (e) {
  100947. if (_this.attachedMesh) {
  100948. lastDragPosition.copyFrom(e.dragPlanePoint);
  100949. }
  100950. });
  100951. var rotationMatrix = new BABYLON.Matrix();
  100952. var planeNormalTowardsCamera = new BABYLON.Vector3();
  100953. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  100954. var tmpSnapEvent = { snapDistance: 0 };
  100955. var currentSnapDragDistance = 0;
  100956. var tmpMatrix = new BABYLON.Matrix();
  100957. var tmpVector = new BABYLON.Vector3();
  100958. var amountToRotate = new BABYLON.Quaternion();
  100959. _this.dragBehavior.onDragObservable.add(function (event) {
  100960. if (_this.attachedMesh) {
  100961. if (!_this.attachedMesh.rotationQuaternion) {
  100962. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  100963. }
  100964. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  100965. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize();
  100966. var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize();
  100967. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  100968. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  100969. var angle = Math.atan2(cross.length(), dot);
  100970. planeNormalTowardsCamera.copyFrom(planeNormal);
  100971. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  100972. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  100973. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  100974. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  100975. }
  100976. // Flip up vector depending on which side the camera is on
  100977. if (gizmoLayer.utilityLayerScene.activeCamera) {
  100978. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  100979. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  100980. planeNormalTowardsCamera.scaleInPlace(-1);
  100981. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  100982. }
  100983. }
  100984. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  100985. if (halfCircleSide) {
  100986. angle = -angle;
  100987. }
  100988. // Snapping logic
  100989. var snapped = false;
  100990. if (_this.snapDistance != 0) {
  100991. currentSnapDragDistance += angle;
  100992. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  100993. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  100994. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  100995. angle = _this.snapDistance * dragSteps;
  100996. snapped = true;
  100997. }
  100998. else {
  100999. angle = 0;
  101000. }
  101001. }
  101002. // If the mesh has a parent, convert needed world rotation to local rotation
  101003. tmpMatrix.reset();
  101004. if (_this.attachedMesh.parent) {
  101005. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  101006. tmpMatrix.getRotationMatrixToRef(tmpMatrix);
  101007. BABYLON.Vector3.TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera);
  101008. }
  101009. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  101010. var quaternionCoefficient = Math.sin(angle / 2);
  101011. amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  101012. // 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
  101013. if (tmpMatrix.determinant() > 0) {
  101014. amountToRotate.toEulerAnglesToRef(tmpVector);
  101015. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
  101016. }
  101017. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  101018. // Rotate selected mesh quaternion over fixed axis
  101019. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  101020. }
  101021. else {
  101022. // Rotate selected mesh quaternion over rotated axis
  101023. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  101024. }
  101025. lastDragPosition.copyFrom(event.dragPlanePoint);
  101026. if (snapped) {
  101027. tmpSnapEvent.snapDistance = angle;
  101028. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  101029. }
  101030. }
  101031. });
  101032. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  101033. if (_this._customMeshSet) {
  101034. return;
  101035. }
  101036. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  101037. var material = isHovered ? hoverMaterial : coloredMaterial;
  101038. _this._rootMesh.getChildMeshes().forEach(function (m) {
  101039. m.material = material;
  101040. if (m.color) {
  101041. m.color = material.emissiveColor;
  101042. }
  101043. });
  101044. });
  101045. return _this;
  101046. }
  101047. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  101048. if (this.dragBehavior) {
  101049. this.dragBehavior.enabled = value ? true : false;
  101050. }
  101051. };
  101052. /**
  101053. * Disposes of the gizmo
  101054. */
  101055. PlaneRotationGizmo.prototype.dispose = function () {
  101056. this.onSnapObservable.clear();
  101057. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  101058. this.dragBehavior.detach();
  101059. _super.prototype.dispose.call(this);
  101060. };
  101061. return PlaneRotationGizmo;
  101062. }(BABYLON.Gizmo));
  101063. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  101064. })(BABYLON || (BABYLON = {}));
  101065. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  101066. var BABYLON;
  101067. (function (BABYLON) {
  101068. /**
  101069. * Gizmo that enables dragging a mesh along 3 axis
  101070. */
  101071. var PositionGizmo = /** @class */ (function (_super) {
  101072. __extends(PositionGizmo, _super);
  101073. /**
  101074. * Creates a PositionGizmo
  101075. * @param gizmoLayer The utility layer the gizmo will be added to
  101076. */
  101077. function PositionGizmo(gizmoLayer) {
  101078. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  101079. var _this = _super.call(this, gizmoLayer) || this;
  101080. /** Fires an event when any of it's sub gizmos are dragged */
  101081. _this.onDragStartObservable = new BABYLON.Observable();
  101082. /** Fires an event when any of it's sub gizmos are released from dragging */
  101083. _this.onDragEndObservable = new BABYLON.Observable();
  101084. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  101085. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  101086. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  101087. // Relay drag events
  101088. [_this.xGizmo, _this.yGizmo, _this.zGizmo].forEach(function (gizmo) {
  101089. gizmo.dragBehavior.onDragStartObservable.add(function () {
  101090. _this.onDragStartObservable.notifyObservers({});
  101091. });
  101092. gizmo.dragBehavior.onDragEndObservable.add(function () {
  101093. _this.onDragEndObservable.notifyObservers({});
  101094. });
  101095. });
  101096. _this.attachedMesh = null;
  101097. return _this;
  101098. }
  101099. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  101100. set: function (mesh) {
  101101. if (this.xGizmo) {
  101102. this.xGizmo.attachedMesh = mesh;
  101103. this.yGizmo.attachedMesh = mesh;
  101104. this.zGizmo.attachedMesh = mesh;
  101105. }
  101106. },
  101107. enumerable: true,
  101108. configurable: true
  101109. });
  101110. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  101111. get: function () {
  101112. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  101113. },
  101114. set: function (value) {
  101115. if (this.xGizmo) {
  101116. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  101117. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  101118. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  101119. }
  101120. },
  101121. enumerable: true,
  101122. configurable: true
  101123. });
  101124. Object.defineProperty(PositionGizmo.prototype, "snapDistance", {
  101125. get: function () {
  101126. return this.xGizmo.snapDistance;
  101127. },
  101128. /**
  101129. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  101130. */
  101131. set: function (value) {
  101132. if (this.xGizmo) {
  101133. this.xGizmo.snapDistance = value;
  101134. this.yGizmo.snapDistance = value;
  101135. this.zGizmo.snapDistance = value;
  101136. }
  101137. },
  101138. enumerable: true,
  101139. configurable: true
  101140. });
  101141. Object.defineProperty(PositionGizmo.prototype, "scaleRatio", {
  101142. get: function () {
  101143. return this.xGizmo.scaleRatio;
  101144. },
  101145. /**
  101146. * Ratio for the scale of the gizmo (Default: 1)
  101147. */
  101148. set: function (value) {
  101149. if (this.xGizmo) {
  101150. this.xGizmo.scaleRatio = value;
  101151. this.yGizmo.scaleRatio = value;
  101152. this.zGizmo.scaleRatio = value;
  101153. }
  101154. },
  101155. enumerable: true,
  101156. configurable: true
  101157. });
  101158. /**
  101159. * Disposes of the gizmo
  101160. */
  101161. PositionGizmo.prototype.dispose = function () {
  101162. this.xGizmo.dispose();
  101163. this.yGizmo.dispose();
  101164. this.zGizmo.dispose();
  101165. this.onDragStartObservable.clear();
  101166. this.onDragEndObservable.clear();
  101167. };
  101168. /**
  101169. * CustomMeshes are not supported by this gizmo
  101170. * @param mesh The mesh to replace the default mesh of the gizmo
  101171. */
  101172. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  101173. 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)");
  101174. };
  101175. return PositionGizmo;
  101176. }(BABYLON.Gizmo));
  101177. BABYLON.PositionGizmo = PositionGizmo;
  101178. })(BABYLON || (BABYLON = {}));
  101179. //# sourceMappingURL=babylon.positionGizmo.js.map
  101180. var BABYLON;
  101181. (function (BABYLON) {
  101182. /**
  101183. * Gizmo that enables rotating a mesh along 3 axis
  101184. */
  101185. var RotationGizmo = /** @class */ (function (_super) {
  101186. __extends(RotationGizmo, _super);
  101187. /**
  101188. * Creates a RotationGizmo
  101189. * @param gizmoLayer The utility layer the gizmo will be added to
  101190. * @param tessellation Amount of tessellation to be used when creating rotation circles
  101191. */
  101192. function RotationGizmo(gizmoLayer, tessellation) {
  101193. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  101194. if (tessellation === void 0) { tessellation = 32; }
  101195. var _this = _super.call(this, gizmoLayer) || this;
  101196. /** Fires an event when any of it's sub gizmos are dragged */
  101197. _this.onDragStartObservable = new BABYLON.Observable();
  101198. /** Fires an event when any of it's sub gizmos are released from dragging */
  101199. _this.onDragEndObservable = new BABYLON.Observable();
  101200. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer, tessellation);
  101201. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer, tessellation);
  101202. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer, tessellation);
  101203. // Relay drag events
  101204. [_this.xGizmo, _this.yGizmo, _this.zGizmo].forEach(function (gizmo) {
  101205. gizmo.dragBehavior.onDragStartObservable.add(function () {
  101206. _this.onDragStartObservable.notifyObservers({});
  101207. });
  101208. gizmo.dragBehavior.onDragEndObservable.add(function () {
  101209. _this.onDragEndObservable.notifyObservers({});
  101210. });
  101211. });
  101212. _this.attachedMesh = null;
  101213. return _this;
  101214. }
  101215. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  101216. set: function (mesh) {
  101217. if (this.xGizmo) {
  101218. this.xGizmo.attachedMesh = mesh;
  101219. this.yGizmo.attachedMesh = mesh;
  101220. this.zGizmo.attachedMesh = mesh;
  101221. }
  101222. },
  101223. enumerable: true,
  101224. configurable: true
  101225. });
  101226. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  101227. get: function () {
  101228. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  101229. },
  101230. set: function (value) {
  101231. if (this.xGizmo) {
  101232. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  101233. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  101234. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  101235. }
  101236. },
  101237. enumerable: true,
  101238. configurable: true
  101239. });
  101240. Object.defineProperty(RotationGizmo.prototype, "snapDistance", {
  101241. get: function () {
  101242. return this.xGizmo.snapDistance;
  101243. },
  101244. /**
  101245. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  101246. */
  101247. set: function (value) {
  101248. if (this.xGizmo) {
  101249. this.xGizmo.snapDistance = value;
  101250. this.yGizmo.snapDistance = value;
  101251. this.zGizmo.snapDistance = value;
  101252. }
  101253. },
  101254. enumerable: true,
  101255. configurable: true
  101256. });
  101257. Object.defineProperty(RotationGizmo.prototype, "scaleRatio", {
  101258. get: function () {
  101259. return this.xGizmo.scaleRatio;
  101260. },
  101261. /**
  101262. * Ratio for the scale of the gizmo (Default: 1)
  101263. */
  101264. set: function (value) {
  101265. if (this.xGizmo) {
  101266. this.xGizmo.scaleRatio = value;
  101267. this.yGizmo.scaleRatio = value;
  101268. this.zGizmo.scaleRatio = value;
  101269. }
  101270. },
  101271. enumerable: true,
  101272. configurable: true
  101273. });
  101274. /**
  101275. * Disposes of the gizmo
  101276. */
  101277. RotationGizmo.prototype.dispose = function () {
  101278. this.xGizmo.dispose();
  101279. this.yGizmo.dispose();
  101280. this.zGizmo.dispose();
  101281. this.onDragStartObservable.clear();
  101282. this.onDragEndObservable.clear();
  101283. };
  101284. /**
  101285. * CustomMeshes are not supported by this gizmo
  101286. * @param mesh The mesh to replace the default mesh of the gizmo
  101287. */
  101288. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  101289. 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)");
  101290. };
  101291. return RotationGizmo;
  101292. }(BABYLON.Gizmo));
  101293. BABYLON.RotationGizmo = RotationGizmo;
  101294. })(BABYLON || (BABYLON = {}));
  101295. //# sourceMappingURL=babylon.rotationGizmo.js.map
  101296. var BABYLON;
  101297. (function (BABYLON) {
  101298. /**
  101299. * Gizmo that enables scaling a mesh along 3 axis
  101300. */
  101301. var ScaleGizmo = /** @class */ (function (_super) {
  101302. __extends(ScaleGizmo, _super);
  101303. /**
  101304. * Creates a ScaleGizmo
  101305. * @param gizmoLayer The utility layer the gizmo will be added to
  101306. */
  101307. function ScaleGizmo(gizmoLayer) {
  101308. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  101309. var _this = _super.call(this, gizmoLayer) || this;
  101310. /** Fires an event when any of it's sub gizmos are dragged */
  101311. _this.onDragStartObservable = new BABYLON.Observable();
  101312. /** Fires an event when any of it's sub gizmos are released from dragging */
  101313. _this.onDragEndObservable = new BABYLON.Observable();
  101314. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  101315. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  101316. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  101317. // Create uniform scale gizmo
  101318. _this.uniformScaleGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Yellow().scale(0.5), gizmoLayer);
  101319. _this.uniformScaleGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  101320. _this.uniformScaleGizmo.uniformScaling = true;
  101321. var uniformScalingMesh = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this.uniformScaleGizmo.gizmoLayer.utilityLayerScene);
  101322. uniformScalingMesh.scaling.scaleInPlace(0.02);
  101323. uniformScalingMesh.visibility = 0;
  101324. var octahedron = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this.uniformScaleGizmo.gizmoLayer.utilityLayerScene);
  101325. octahedron.scaling.scaleInPlace(0.007);
  101326. uniformScalingMesh.addChild(octahedron);
  101327. _this.uniformScaleGizmo.setCustomMesh(uniformScalingMesh, true);
  101328. // Relay drag events
  101329. [_this.xGizmo, _this.yGizmo, _this.zGizmo, _this.uniformScaleGizmo].forEach(function (gizmo) {
  101330. gizmo.dragBehavior.onDragStartObservable.add(function () {
  101331. _this.onDragStartObservable.notifyObservers({});
  101332. });
  101333. gizmo.dragBehavior.onDragEndObservable.add(function () {
  101334. _this.onDragEndObservable.notifyObservers({});
  101335. });
  101336. });
  101337. _this.attachedMesh = null;
  101338. return _this;
  101339. }
  101340. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  101341. set: function (mesh) {
  101342. if (this.xGizmo) {
  101343. this.xGizmo.attachedMesh = mesh;
  101344. this.yGizmo.attachedMesh = mesh;
  101345. this.zGizmo.attachedMesh = mesh;
  101346. this.uniformScaleGizmo.attachedMesh = mesh;
  101347. }
  101348. },
  101349. enumerable: true,
  101350. configurable: true
  101351. });
  101352. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  101353. get: function () {
  101354. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  101355. },
  101356. set: function (value) {
  101357. if (!value) {
  101358. BABYLON.Tools.Warn("Setting updateGizmoRotationToMatchAttachedMesh = false on scaling gizmo is not supported.");
  101359. }
  101360. if (this.xGizmo) {
  101361. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  101362. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  101363. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  101364. }
  101365. },
  101366. enumerable: true,
  101367. configurable: true
  101368. });
  101369. Object.defineProperty(ScaleGizmo.prototype, "snapDistance", {
  101370. get: function () {
  101371. return this.xGizmo.snapDistance;
  101372. },
  101373. /**
  101374. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  101375. */
  101376. set: function (value) {
  101377. if (this.xGizmo) {
  101378. this.xGizmo.snapDistance = value;
  101379. this.yGizmo.snapDistance = value;
  101380. this.zGizmo.snapDistance = value;
  101381. this.uniformScaleGizmo.snapDistance = value;
  101382. }
  101383. },
  101384. enumerable: true,
  101385. configurable: true
  101386. });
  101387. Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", {
  101388. get: function () {
  101389. return this.xGizmo.scaleRatio;
  101390. },
  101391. /**
  101392. * Ratio for the scale of the gizmo (Default: 1)
  101393. */
  101394. set: function (value) {
  101395. if (this.xGizmo) {
  101396. this.xGizmo.scaleRatio = value;
  101397. this.yGizmo.scaleRatio = value;
  101398. this.zGizmo.scaleRatio = value;
  101399. this.uniformScaleGizmo.scaleRatio = value;
  101400. }
  101401. },
  101402. enumerable: true,
  101403. configurable: true
  101404. });
  101405. /**
  101406. * Disposes of the gizmo
  101407. */
  101408. ScaleGizmo.prototype.dispose = function () {
  101409. this.xGizmo.dispose();
  101410. this.yGizmo.dispose();
  101411. this.zGizmo.dispose();
  101412. this.uniformScaleGizmo.dispose();
  101413. this.onDragStartObservable.clear();
  101414. this.onDragEndObservable.clear();
  101415. };
  101416. return ScaleGizmo;
  101417. }(BABYLON.Gizmo));
  101418. BABYLON.ScaleGizmo = ScaleGizmo;
  101419. })(BABYLON || (BABYLON = {}));
  101420. //# sourceMappingURL=babylon.scaleGizmo.js.map
  101421. var BABYLON;
  101422. (function (BABYLON) {
  101423. /**
  101424. * Bounding box gizmo
  101425. */
  101426. var BoundingBoxGizmo = /** @class */ (function (_super) {
  101427. __extends(BoundingBoxGizmo, _super);
  101428. /**
  101429. * Creates an BoundingBoxGizmo
  101430. * @param gizmoLayer The utility layer the gizmo will be added to
  101431. * @param color The color of the gizmo
  101432. */
  101433. function BoundingBoxGizmo(color, gizmoLayer) {
  101434. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  101435. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  101436. var _this = _super.call(this, gizmoLayer) || this;
  101437. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  101438. _this._renderObserver = null;
  101439. _this._pointerObserver = null;
  101440. _this._scaleDragSpeed = 0.2;
  101441. _this._tmpQuaternion = new BABYLON.Quaternion();
  101442. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  101443. _this._tmpRotationMatrix = new BABYLON.Matrix();
  101444. /**
  101445. * 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)
  101446. */
  101447. _this.ignoreChildren = false;
  101448. /**
  101449. * 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)
  101450. */
  101451. _this.includeChildPredicate = null;
  101452. /**
  101453. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  101454. */
  101455. _this.rotationSphereSize = 0.1;
  101456. /**
  101457. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  101458. */
  101459. _this.scaleBoxSize = 0.1;
  101460. /**
  101461. * 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)
  101462. */
  101463. _this.fixedDragMeshScreenSize = false;
  101464. /**
  101465. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  101466. */
  101467. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  101468. /**
  101469. * Fired when a rotation sphere or scale box is dragged
  101470. */
  101471. _this.onDragStartObservable = new BABYLON.Observable();
  101472. /**
  101473. * Fired when a scale box is dragged
  101474. */
  101475. _this.onScaleBoxDragObservable = new BABYLON.Observable();
  101476. /**
  101477. * Fired when a scale box drag is ended
  101478. */
  101479. _this.onScaleBoxDragEndObservable = new BABYLON.Observable();
  101480. /**
  101481. * Fired when a rotation sphere is dragged
  101482. */
  101483. _this.onRotationSphereDragObservable = new BABYLON.Observable();
  101484. /**
  101485. * Fired when a rotation sphere drag is ended
  101486. */
  101487. _this.onRotationSphereDragEndObservable = new BABYLON.Observable();
  101488. /**
  101489. * 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)
  101490. */
  101491. _this.scalePivot = null;
  101492. _this._existingMeshScale = new BABYLON.Vector3();
  101493. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  101494. _this._updateScale = false;
  101495. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  101496. // Create Materials
  101497. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  101498. coloredMaterial.disableLighting = true;
  101499. coloredMaterial.emissiveColor = color;
  101500. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  101501. hoverColoredMaterial.disableLighting = true;
  101502. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.3, 0.3, 0.3));
  101503. // Build bounding box out of lines
  101504. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  101505. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  101506. var lines = [];
  101507. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  101508. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  101509. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  101510. 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));
  101511. 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));
  101512. 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));
  101513. 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));
  101514. 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));
  101515. 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));
  101516. 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));
  101517. 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));
  101518. 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));
  101519. lines.forEach(function (l) {
  101520. l.color = color;
  101521. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  101522. l.isPickable = false;
  101523. _this._lineBoundingBox.addChild(l);
  101524. });
  101525. _this._rootMesh.addChild(_this._lineBoundingBox);
  101526. // Create rotation spheres
  101527. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  101528. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  101529. var _loop_1 = function (i_1) {
  101530. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  101531. sphere.rotationQuaternion = new BABYLON.Quaternion();
  101532. sphere.material = coloredMaterial;
  101533. // Drag behavior
  101534. _dragBehavior = new BABYLON.PointerDragBehavior({});
  101535. _dragBehavior.moveAttached = false;
  101536. _dragBehavior.updateDragPlane = false;
  101537. sphere.addBehavior(_dragBehavior);
  101538. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  101539. var totalTurnAmountOfDrag = 0;
  101540. _dragBehavior.onDragStartObservable.add(function (event) {
  101541. startingTurnDirection.copyFrom(sphere.forward);
  101542. totalTurnAmountOfDrag = 0;
  101543. });
  101544. _dragBehavior.onDragObservable.add(function (event) {
  101545. _this.onRotationSphereDragObservable.notifyObservers({});
  101546. if (_this.attachedMesh) {
  101547. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  101548. var worldDragDirection = startingTurnDirection;
  101549. // Project the world right on to the drag plane
  101550. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  101551. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  101552. // project drag delta on to the resulting drag axis and rotate based on that
  101553. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  101554. // Make rotation relative to size of mesh.
  101555. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  101556. // Rotate based on axis
  101557. if (!_this.attachedMesh.rotationQuaternion) {
  101558. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  101559. }
  101560. if (!_this._anchorMesh.rotationQuaternion) {
  101561. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  101562. }
  101563. // Do not allow the object to turn more than a full circle
  101564. totalTurnAmountOfDrag += projectDist;
  101565. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  101566. if (i_1 >= 8) {
  101567. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  101568. }
  101569. else if (i_1 >= 4) {
  101570. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  101571. }
  101572. else {
  101573. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  101574. }
  101575. // Rotate around center of bounding box
  101576. _this._anchorMesh.addChild(_this.attachedMesh);
  101577. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  101578. _this._anchorMesh.removeChild(_this.attachedMesh);
  101579. }
  101580. _this.updateBoundingBox();
  101581. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  101582. }
  101583. });
  101584. // Selection/deselection
  101585. _dragBehavior.onDragStartObservable.add(function () {
  101586. _this.onDragStartObservable.notifyObservers({});
  101587. _this._selectNode(sphere);
  101588. });
  101589. _dragBehavior.onDragEndObservable.add(function () {
  101590. _this.onRotationSphereDragEndObservable.notifyObservers({});
  101591. _this._selectNode(null);
  101592. });
  101593. this_1._rotateSpheresParent.addChild(sphere);
  101594. };
  101595. var this_1 = this, _dragBehavior;
  101596. for (var i_1 = 0; i_1 < 12; i_1++) {
  101597. _loop_1(i_1);
  101598. }
  101599. _this._rootMesh.addChild(_this._rotateSpheresParent);
  101600. // Create scale cubes
  101601. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  101602. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  101603. for (var i = 0; i < 2; i++) {
  101604. for (var j = 0; j < 2; j++) {
  101605. var _loop_2 = function () {
  101606. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  101607. box.material = coloredMaterial;
  101608. // Dragging logic
  101609. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  101610. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  101611. _dragBehavior.moveAttached = false;
  101612. box.addBehavior(_dragBehavior);
  101613. _dragBehavior.onDragObservable.add(function (event) {
  101614. _this.onScaleBoxDragObservable.notifyObservers({});
  101615. if (_this.attachedMesh) {
  101616. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  101617. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  101618. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  101619. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  101620. _this.updateBoundingBox();
  101621. if (_this.scalePivot) {
  101622. _this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(_this._tmpRotationMatrix);
  101623. // Move anchor to desired pivot point (Bottom left corner + dimension/2)
  101624. _this._boundingDimensions.scaleToRef(0.5, _this._tmpVector);
  101625. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  101626. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  101627. _this._boundingDimensions.multiplyToRef(_this.scalePivot, _this._tmpVector);
  101628. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  101629. _this._anchorMesh.position.addInPlace(_this._tmpVector);
  101630. }
  101631. else {
  101632. // Scale from the position of the opposite corner
  101633. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  101634. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  101635. }
  101636. _this._anchorMesh.addChild(_this.attachedMesh);
  101637. _this._anchorMesh.scaling.addInPlace(deltaScale);
  101638. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  101639. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  101640. }
  101641. _this._anchorMesh.removeChild(_this.attachedMesh);
  101642. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  101643. }
  101644. });
  101645. // Selection/deselection
  101646. _dragBehavior.onDragStartObservable.add(function () {
  101647. _this.onDragStartObservable.notifyObservers({});
  101648. _this._selectNode(box);
  101649. });
  101650. _dragBehavior.onDragEndObservable.add(function () {
  101651. _this.onScaleBoxDragEndObservable.notifyObservers({});
  101652. _this._selectNode(null);
  101653. });
  101654. this_2._scaleBoxesParent.addChild(box);
  101655. };
  101656. var this_2 = this, _dragBehavior;
  101657. for (var k = 0; k < 2; k++) {
  101658. _loop_2();
  101659. }
  101660. }
  101661. }
  101662. _this._rootMesh.addChild(_this._scaleBoxesParent);
  101663. // Hover color change
  101664. var pointerIds = new Array();
  101665. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  101666. if (!pointerIds[pointerInfo.event.pointerId]) {
  101667. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  101668. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  101669. pointerIds[pointerInfo.event.pointerId] = mesh;
  101670. mesh.material = hoverColoredMaterial;
  101671. }
  101672. });
  101673. }
  101674. else {
  101675. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  101676. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  101677. delete pointerIds[pointerInfo.event.pointerId];
  101678. }
  101679. }
  101680. });
  101681. // Update bounding box positions
  101682. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  101683. // Only update the bouding box if scaling has changed
  101684. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  101685. _this.updateBoundingBox();
  101686. }
  101687. });
  101688. _this.updateBoundingBox();
  101689. return _this;
  101690. }
  101691. /** @hidden */
  101692. BoundingBoxGizmo._RemoveAndStorePivotPoint = function (mesh) {
  101693. if (mesh && BoundingBoxGizmo._PivotCached === 0) {
  101694. // Save old pivot and set pivot to 0,0,0
  101695. mesh.getPivotPointToRef(BoundingBoxGizmo._OldPivotPoint);
  101696. if (!BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0)) {
  101697. mesh.setPivotMatrix(BABYLON.Matrix.IdentityReadOnly);
  101698. BoundingBoxGizmo._OldPivotPoint.subtractToRef(mesh.getPivotPoint(), BoundingBoxGizmo._PivotTranslation);
  101699. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  101700. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  101701. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  101702. mesh.position.addInPlace(BoundingBoxGizmo._PivotTmpVector);
  101703. }
  101704. }
  101705. BoundingBoxGizmo._PivotCached++;
  101706. };
  101707. /** @hidden */
  101708. BoundingBoxGizmo._RestorePivotPoint = function (mesh) {
  101709. if (mesh && !BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0) && BoundingBoxGizmo._PivotCached === 1) {
  101710. mesh.setPivotPoint(BoundingBoxGizmo._OldPivotPoint);
  101711. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  101712. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  101713. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  101714. mesh.position.subtractInPlace(BoundingBoxGizmo._PivotTmpVector);
  101715. }
  101716. this._PivotCached--;
  101717. };
  101718. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  101719. if (value) {
  101720. // Reset anchor mesh to match attached mesh's scale
  101721. // This is needed to avoid invalid box/sphere position on first drag
  101722. BoundingBoxGizmo._RemoveAndStorePivotPoint(value);
  101723. this._anchorMesh.addChild(value);
  101724. this._anchorMesh.removeChild(value);
  101725. BoundingBoxGizmo._RestorePivotPoint(value);
  101726. this.updateBoundingBox();
  101727. }
  101728. };
  101729. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  101730. this._rotateSpheresParent.getChildMeshes()
  101731. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  101732. m.isVisible = (!selectedMesh || m == selectedMesh);
  101733. });
  101734. };
  101735. /**
  101736. * Updates the bounding box information for the Gizmo
  101737. */
  101738. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  101739. if (this.attachedMesh) {
  101740. BoundingBoxGizmo._RemoveAndStorePivotPoint(this.attachedMesh);
  101741. this._update();
  101742. // Rotate based on axis
  101743. if (!this.attachedMesh.rotationQuaternion) {
  101744. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  101745. }
  101746. if (!this._anchorMesh.rotationQuaternion) {
  101747. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  101748. }
  101749. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  101750. // Store original position and reset mesh to origin before computing the bounding box
  101751. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  101752. this._tmpVector.copyFrom(this.attachedMesh.position);
  101753. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  101754. this.attachedMesh.position.set(0, 0, 0);
  101755. // Update bounding dimensions/positions
  101756. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren, this.includeChildPredicate);
  101757. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  101758. // Update gizmo to match bounding box scaling and rotation
  101759. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  101760. 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);
  101761. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  101762. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  101763. this._lineBoundingBox.computeWorldMatrix();
  101764. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  101765. // restore position/rotation values
  101766. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  101767. this.attachedMesh.position.copyFrom(this._tmpVector);
  101768. }
  101769. // Update rotation sphere locations
  101770. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  101771. for (var i = 0; i < 3; i++) {
  101772. for (var j = 0; j < 2; j++) {
  101773. for (var k = 0; k < 2; k++) {
  101774. var index = ((i * 4) + (j * 2)) + k;
  101775. if (i == 0) {
  101776. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  101777. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  101778. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  101779. }
  101780. if (i == 1) {
  101781. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  101782. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  101783. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  101784. }
  101785. if (i == 2) {
  101786. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  101787. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  101788. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  101789. }
  101790. if (this.fixedDragMeshScreenSize) {
  101791. this._rootMesh.computeWorldMatrix();
  101792. this._rotateSpheresParent.computeWorldMatrix();
  101793. rotateSpheres[index].computeWorldMatrix();
  101794. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  101795. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  101796. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  101797. }
  101798. else {
  101799. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  101800. }
  101801. }
  101802. }
  101803. }
  101804. // Update scale box locations
  101805. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  101806. for (var i = 0; i < 2; i++) {
  101807. for (var j = 0; j < 2; j++) {
  101808. for (var k = 0; k < 2; k++) {
  101809. var index = ((i * 4) + (j * 2)) + k;
  101810. if (scaleBoxes[index]) {
  101811. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  101812. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  101813. if (this.fixedDragMeshScreenSize) {
  101814. this._rootMesh.computeWorldMatrix();
  101815. this._scaleBoxesParent.computeWorldMatrix();
  101816. scaleBoxes[index].computeWorldMatrix();
  101817. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  101818. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  101819. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  101820. }
  101821. else {
  101822. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  101823. }
  101824. }
  101825. }
  101826. }
  101827. }
  101828. if (this.attachedMesh) {
  101829. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  101830. BoundingBoxGizmo._RestorePivotPoint(this.attachedMesh);
  101831. }
  101832. };
  101833. /**
  101834. * Enables rotation on the specified axis and disables rotation on the others
  101835. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  101836. */
  101837. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  101838. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  101839. if (i < 4) {
  101840. m.setEnabled(axis.indexOf("x") != -1);
  101841. }
  101842. else if (i < 8) {
  101843. m.setEnabled(axis.indexOf("y") != -1);
  101844. }
  101845. else {
  101846. m.setEnabled(axis.indexOf("z") != -1);
  101847. }
  101848. });
  101849. };
  101850. /**
  101851. * Disposes of the gizmo
  101852. */
  101853. BoundingBoxGizmo.prototype.dispose = function () {
  101854. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  101855. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  101856. this._lineBoundingBox.dispose();
  101857. this._rotateSpheresParent.dispose();
  101858. this._scaleBoxesParent.dispose();
  101859. _super.prototype.dispose.call(this);
  101860. };
  101861. /**
  101862. * 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)
  101863. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  101864. * @returns the bounding box mesh with the passed in mesh as a child
  101865. */
  101866. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  101867. var makeNotPickable = function (root) {
  101868. root.isPickable = false;
  101869. root.getChildMeshes().forEach(function (c) {
  101870. makeNotPickable(c);
  101871. });
  101872. };
  101873. makeNotPickable(mesh);
  101874. // Reset position to get boudning box from origin with no rotation
  101875. if (!mesh.rotationQuaternion) {
  101876. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  101877. }
  101878. var oldPos = mesh.position.clone();
  101879. var oldRot = mesh.rotationQuaternion.clone();
  101880. mesh.rotationQuaternion.set(0, 0, 0, 1);
  101881. mesh.position.set(0, 0, 0);
  101882. // Update bounding dimensions/positions
  101883. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  101884. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  101885. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  101886. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  101887. // Restore original positions
  101888. mesh.addChild(box);
  101889. mesh.rotationQuaternion.copyFrom(oldRot);
  101890. mesh.position.copyFrom(oldPos);
  101891. // Reverse parenting
  101892. mesh.removeChild(box);
  101893. box.addChild(mesh);
  101894. box.visibility = 0;
  101895. return box;
  101896. };
  101897. /**
  101898. * CustomMeshes are not supported by this gizmo
  101899. * @param mesh The mesh to replace the default mesh of the gizmo
  101900. */
  101901. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  101902. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  101903. };
  101904. // Stores the state of the pivot cache (_oldPivotPoint, _pivotTranslation)
  101905. // store/remove pivot point should only be applied during their outermost calls
  101906. BoundingBoxGizmo._PivotCached = 0;
  101907. BoundingBoxGizmo._OldPivotPoint = new BABYLON.Vector3();
  101908. BoundingBoxGizmo._PivotTranslation = new BABYLON.Vector3();
  101909. BoundingBoxGizmo._PivotTmpVector = new BABYLON.Vector3();
  101910. return BoundingBoxGizmo;
  101911. }(BABYLON.Gizmo));
  101912. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  101913. })(BABYLON || (BABYLON = {}));
  101914. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  101915. var BABYLON;
  101916. (function (BABYLON) {
  101917. /**
  101918. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  101919. */
  101920. var GizmoManager = /** @class */ (function () {
  101921. /**
  101922. * Instatiates a gizmo manager
  101923. * @param scene the scene to overlay the gizmos on top of
  101924. */
  101925. function GizmoManager(scene) {
  101926. var _this = this;
  101927. this.scene = scene;
  101928. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  101929. this._pointerObserver = null;
  101930. this._attachedMesh = null;
  101931. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  101932. /**
  101933. * When bounding box gizmo is enabled, this can be used to track drag/end events
  101934. */
  101935. this.boundingBoxDragBehavior = new BABYLON.SixDofDragBehavior();
  101936. /**
  101937. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  101938. */
  101939. this.attachableMeshes = null;
  101940. /**
  101941. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  101942. */
  101943. this.usePointerToAttachGizmos = true;
  101944. this._defaultKeepDepthUtilityLayer = new BABYLON.UtilityLayerRenderer(scene);
  101945. this._defaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  101946. this._defaultUtilityLayer = new BABYLON.UtilityLayerRenderer(scene);
  101947. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  101948. // Instatiate/dispose gizmos based on pointer actions
  101949. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  101950. if (!_this.usePointerToAttachGizmos) {
  101951. return;
  101952. }
  101953. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  101954. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  101955. var node = pointerInfo.pickInfo.pickedMesh;
  101956. if (_this.attachableMeshes == null) {
  101957. // Attach to the most parent node
  101958. while (node && node.parent != null) {
  101959. node = node.parent;
  101960. }
  101961. }
  101962. else {
  101963. // Attach to the parent node that is an attachableMesh
  101964. var found = false;
  101965. _this.attachableMeshes.forEach(function (mesh) {
  101966. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  101967. node = mesh;
  101968. found = true;
  101969. }
  101970. });
  101971. if (!found) {
  101972. node = null;
  101973. }
  101974. }
  101975. if (node instanceof BABYLON.AbstractMesh) {
  101976. if (_this._attachedMesh != node) {
  101977. _this.attachToMesh(node);
  101978. }
  101979. }
  101980. else {
  101981. _this.attachToMesh(null);
  101982. }
  101983. }
  101984. else {
  101985. _this.attachToMesh(null);
  101986. }
  101987. }
  101988. });
  101989. }
  101990. /**
  101991. * Attaches a set of gizmos to the specified mesh
  101992. * @param mesh The mesh the gizmo's should be attached to
  101993. */
  101994. GizmoManager.prototype.attachToMesh = function (mesh) {
  101995. if (this._attachedMesh) {
  101996. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  101997. }
  101998. this._attachedMesh = mesh;
  101999. for (var key in this.gizmos) {
  102000. var gizmo = (this.gizmos[key]);
  102001. if (gizmo && this._gizmosEnabled[key]) {
  102002. gizmo.attachedMesh = mesh;
  102003. }
  102004. }
  102005. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  102006. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  102007. }
  102008. };
  102009. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  102010. get: function () {
  102011. return this._gizmosEnabled.positionGizmo;
  102012. },
  102013. /**
  102014. * If the position gizmo is enabled
  102015. */
  102016. set: function (value) {
  102017. if (value) {
  102018. if (!this.gizmos.positionGizmo) {
  102019. this.gizmos.positionGizmo = new BABYLON.PositionGizmo(this._defaultUtilityLayer);
  102020. }
  102021. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  102022. }
  102023. else if (this.gizmos.positionGizmo) {
  102024. this.gizmos.positionGizmo.attachedMesh = null;
  102025. }
  102026. this._gizmosEnabled.positionGizmo = value;
  102027. },
  102028. enumerable: true,
  102029. configurable: true
  102030. });
  102031. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  102032. get: function () {
  102033. return this._gizmosEnabled.rotationGizmo;
  102034. },
  102035. /**
  102036. * If the rotation gizmo is enabled
  102037. */
  102038. set: function (value) {
  102039. if (value) {
  102040. if (!this.gizmos.rotationGizmo) {
  102041. this.gizmos.rotationGizmo = new BABYLON.RotationGizmo(this._defaultUtilityLayer);
  102042. }
  102043. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  102044. }
  102045. else if (this.gizmos.rotationGizmo) {
  102046. this.gizmos.rotationGizmo.attachedMesh = null;
  102047. }
  102048. this._gizmosEnabled.rotationGizmo = value;
  102049. },
  102050. enumerable: true,
  102051. configurable: true
  102052. });
  102053. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  102054. get: function () {
  102055. return this._gizmosEnabled.scaleGizmo;
  102056. },
  102057. /**
  102058. * If the scale gizmo is enabled
  102059. */
  102060. set: function (value) {
  102061. if (value) {
  102062. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo(this._defaultUtilityLayer);
  102063. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  102064. }
  102065. else if (this.gizmos.scaleGizmo) {
  102066. this.gizmos.scaleGizmo.attachedMesh = null;
  102067. }
  102068. this._gizmosEnabled.scaleGizmo = value;
  102069. },
  102070. enumerable: true,
  102071. configurable: true
  102072. });
  102073. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  102074. get: function () {
  102075. return this._gizmosEnabled.boundingBoxGizmo;
  102076. },
  102077. /**
  102078. * If the boundingBox gizmo is enabled
  102079. */
  102080. set: function (value) {
  102081. if (value) {
  102082. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor, this._defaultKeepDepthUtilityLayer);
  102083. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  102084. if (this._attachedMesh) {
  102085. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  102086. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  102087. }
  102088. }
  102089. else if (this.gizmos.boundingBoxGizmo) {
  102090. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  102091. }
  102092. this._gizmosEnabled.boundingBoxGizmo = value;
  102093. },
  102094. enumerable: true,
  102095. configurable: true
  102096. });
  102097. /**
  102098. * Disposes of the gizmo manager
  102099. */
  102100. GizmoManager.prototype.dispose = function () {
  102101. this.scene.onPointerObservable.remove(this._pointerObserver);
  102102. for (var key in this.gizmos) {
  102103. var gizmo = (this.gizmos[key]);
  102104. if (gizmo) {
  102105. gizmo.dispose();
  102106. }
  102107. }
  102108. this._defaultKeepDepthUtilityLayer.dispose();
  102109. this._defaultUtilityLayer.dispose();
  102110. this.boundingBoxDragBehavior.detach();
  102111. };
  102112. return GizmoManager;
  102113. }());
  102114. BABYLON.GizmoManager = GizmoManager;
  102115. })(BABYLON || (BABYLON = {}));
  102116. //# sourceMappingURL=babylon.gizmoManager.js.map
  102117. var BABYLON;
  102118. (function (BABYLON) {
  102119. /**
  102120. * Defines a target to use with MorphTargetManager
  102121. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  102122. */
  102123. var MorphTarget = /** @class */ (function () {
  102124. /**
  102125. * Creates a new MorphTarget
  102126. * @param name defines the name of the target
  102127. * @param influence defines the influence to use
  102128. */
  102129. function MorphTarget(
  102130. /** defines the name of the target */
  102131. name, influence, scene) {
  102132. if (influence === void 0) { influence = 0; }
  102133. if (scene === void 0) { scene = null; }
  102134. this.name = name;
  102135. /**
  102136. * Gets or sets the list of animations
  102137. */
  102138. this.animations = new Array();
  102139. this._positions = null;
  102140. this._normals = null;
  102141. this._tangents = null;
  102142. /**
  102143. * Observable raised when the influence changes
  102144. */
  102145. this.onInfluenceChanged = new BABYLON.Observable();
  102146. /** @hidden */
  102147. this._onDataLayoutChanged = new BABYLON.Observable();
  102148. this._animationPropertiesOverride = null;
  102149. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  102150. this.influence = influence;
  102151. }
  102152. Object.defineProperty(MorphTarget.prototype, "influence", {
  102153. /**
  102154. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  102155. */
  102156. get: function () {
  102157. return this._influence;
  102158. },
  102159. set: function (influence) {
  102160. if (this._influence === influence) {
  102161. return;
  102162. }
  102163. var previous = this._influence;
  102164. this._influence = influence;
  102165. if (this.onInfluenceChanged.hasObservers) {
  102166. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  102167. }
  102168. },
  102169. enumerable: true,
  102170. configurable: true
  102171. });
  102172. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  102173. /**
  102174. * Gets or sets the animation properties override
  102175. */
  102176. get: function () {
  102177. if (!this._animationPropertiesOverride && this._scene) {
  102178. return this._scene.animationPropertiesOverride;
  102179. }
  102180. return this._animationPropertiesOverride;
  102181. },
  102182. set: function (value) {
  102183. this._animationPropertiesOverride = value;
  102184. },
  102185. enumerable: true,
  102186. configurable: true
  102187. });
  102188. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  102189. /**
  102190. * Gets a boolean defining if the target contains position data
  102191. */
  102192. get: function () {
  102193. return !!this._positions;
  102194. },
  102195. enumerable: true,
  102196. configurable: true
  102197. });
  102198. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  102199. /**
  102200. * Gets a boolean defining if the target contains normal data
  102201. */
  102202. get: function () {
  102203. return !!this._normals;
  102204. },
  102205. enumerable: true,
  102206. configurable: true
  102207. });
  102208. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  102209. /**
  102210. * Gets a boolean defining if the target contains tangent data
  102211. */
  102212. get: function () {
  102213. return !!this._tangents;
  102214. },
  102215. enumerable: true,
  102216. configurable: true
  102217. });
  102218. /**
  102219. * Affects position data to this target
  102220. * @param data defines the position data to use
  102221. */
  102222. MorphTarget.prototype.setPositions = function (data) {
  102223. var hadPositions = this.hasPositions;
  102224. this._positions = data;
  102225. if (hadPositions !== this.hasPositions) {
  102226. this._onDataLayoutChanged.notifyObservers(undefined);
  102227. }
  102228. };
  102229. /**
  102230. * Gets the position data stored in this target
  102231. * @returns a FloatArray containing the position data (or null if not present)
  102232. */
  102233. MorphTarget.prototype.getPositions = function () {
  102234. return this._positions;
  102235. };
  102236. /**
  102237. * Affects normal data to this target
  102238. * @param data defines the normal data to use
  102239. */
  102240. MorphTarget.prototype.setNormals = function (data) {
  102241. var hadNormals = this.hasNormals;
  102242. this._normals = data;
  102243. if (hadNormals !== this.hasNormals) {
  102244. this._onDataLayoutChanged.notifyObservers(undefined);
  102245. }
  102246. };
  102247. /**
  102248. * Gets the normal data stored in this target
  102249. * @returns a FloatArray containing the normal data (or null if not present)
  102250. */
  102251. MorphTarget.prototype.getNormals = function () {
  102252. return this._normals;
  102253. };
  102254. /**
  102255. * Affects tangent data to this target
  102256. * @param data defines the tangent data to use
  102257. */
  102258. MorphTarget.prototype.setTangents = function (data) {
  102259. var hadTangents = this.hasTangents;
  102260. this._tangents = data;
  102261. if (hadTangents !== this.hasTangents) {
  102262. this._onDataLayoutChanged.notifyObservers(undefined);
  102263. }
  102264. };
  102265. /**
  102266. * Gets the tangent data stored in this target
  102267. * @returns a FloatArray containing the tangent data (or null if not present)
  102268. */
  102269. MorphTarget.prototype.getTangents = function () {
  102270. return this._tangents;
  102271. };
  102272. /**
  102273. * Serializes the current target into a Serialization object
  102274. * @returns the serialized object
  102275. */
  102276. MorphTarget.prototype.serialize = function () {
  102277. var serializationObject = {};
  102278. serializationObject.name = this.name;
  102279. serializationObject.influence = this.influence;
  102280. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  102281. if (this.hasNormals) {
  102282. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  102283. }
  102284. if (this.hasTangents) {
  102285. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  102286. }
  102287. // Animations
  102288. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  102289. return serializationObject;
  102290. };
  102291. // Statics
  102292. /**
  102293. * Creates a new target from serialized data
  102294. * @param serializationObject defines the serialized data to use
  102295. * @returns a new MorphTarget
  102296. */
  102297. MorphTarget.Parse = function (serializationObject) {
  102298. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  102299. result.setPositions(serializationObject.positions);
  102300. if (serializationObject.normals) {
  102301. result.setNormals(serializationObject.normals);
  102302. }
  102303. if (serializationObject.tangents) {
  102304. result.setTangents(serializationObject.tangents);
  102305. }
  102306. // Animations
  102307. if (serializationObject.animations) {
  102308. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  102309. var parsedAnimation = serializationObject.animations[animationIndex];
  102310. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  102311. }
  102312. }
  102313. return result;
  102314. };
  102315. /**
  102316. * Creates a MorphTarget from mesh data
  102317. * @param mesh defines the source mesh
  102318. * @param name defines the name to use for the new target
  102319. * @param influence defines the influence to attach to the target
  102320. * @returns a new MorphTarget
  102321. */
  102322. MorphTarget.FromMesh = function (mesh, name, influence) {
  102323. if (!name) {
  102324. name = mesh.name;
  102325. }
  102326. var result = new MorphTarget(name, influence, mesh.getScene());
  102327. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  102328. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  102329. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  102330. }
  102331. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  102332. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  102333. }
  102334. return result;
  102335. };
  102336. return MorphTarget;
  102337. }());
  102338. BABYLON.MorphTarget = MorphTarget;
  102339. })(BABYLON || (BABYLON = {}));
  102340. //# sourceMappingURL=babylon.morphTarget.js.map
  102341. var BABYLON;
  102342. (function (BABYLON) {
  102343. /**
  102344. * This class is used to deform meshes using morphing between different targets
  102345. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  102346. */
  102347. var MorphTargetManager = /** @class */ (function () {
  102348. /**
  102349. * Creates a new MorphTargetManager
  102350. * @param scene defines the current scene
  102351. */
  102352. function MorphTargetManager(scene) {
  102353. if (scene === void 0) { scene = null; }
  102354. this._targets = new Array();
  102355. this._targetInfluenceChangedObservers = new Array();
  102356. this._targetDataLayoutChangedObservers = new Array();
  102357. this._activeTargets = new BABYLON.SmartArray(16);
  102358. this._supportsNormals = false;
  102359. this._supportsTangents = false;
  102360. this._vertexCount = 0;
  102361. this._uniqueId = 0;
  102362. this._tempInfluences = new Array();
  102363. if (!scene) {
  102364. scene = BABYLON.Engine.LastCreatedScene;
  102365. }
  102366. this._scene = scene;
  102367. if (this._scene) {
  102368. this._scene.morphTargetManagers.push(this);
  102369. this._uniqueId = this._scene.getUniqueId();
  102370. }
  102371. }
  102372. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  102373. /**
  102374. * Gets the unique ID of this manager
  102375. */
  102376. get: function () {
  102377. return this._uniqueId;
  102378. },
  102379. enumerable: true,
  102380. configurable: true
  102381. });
  102382. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  102383. /**
  102384. * Gets the number of vertices handled by this manager
  102385. */
  102386. get: function () {
  102387. return this._vertexCount;
  102388. },
  102389. enumerable: true,
  102390. configurable: true
  102391. });
  102392. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  102393. /**
  102394. * Gets a boolean indicating if this manager supports morphing of normals
  102395. */
  102396. get: function () {
  102397. return this._supportsNormals;
  102398. },
  102399. enumerable: true,
  102400. configurable: true
  102401. });
  102402. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  102403. /**
  102404. * Gets a boolean indicating if this manager supports morphing of tangents
  102405. */
  102406. get: function () {
  102407. return this._supportsTangents;
  102408. },
  102409. enumerable: true,
  102410. configurable: true
  102411. });
  102412. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  102413. /**
  102414. * Gets the number of targets stored in this manager
  102415. */
  102416. get: function () {
  102417. return this._targets.length;
  102418. },
  102419. enumerable: true,
  102420. configurable: true
  102421. });
  102422. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  102423. /**
  102424. * Gets the number of influencers (ie. the number of targets with influences > 0)
  102425. */
  102426. get: function () {
  102427. return this._activeTargets.length;
  102428. },
  102429. enumerable: true,
  102430. configurable: true
  102431. });
  102432. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  102433. /**
  102434. * Gets the list of influences (one per target)
  102435. */
  102436. get: function () {
  102437. return this._influences;
  102438. },
  102439. enumerable: true,
  102440. configurable: true
  102441. });
  102442. /**
  102443. * Gets the active target at specified index. An active target is a target with an influence > 0
  102444. * @param index defines the index to check
  102445. * @returns the requested target
  102446. */
  102447. MorphTargetManager.prototype.getActiveTarget = function (index) {
  102448. return this._activeTargets.data[index];
  102449. };
  102450. /**
  102451. * Gets the target at specified index
  102452. * @param index defines the index to check
  102453. * @returns the requested target
  102454. */
  102455. MorphTargetManager.prototype.getTarget = function (index) {
  102456. return this._targets[index];
  102457. };
  102458. /**
  102459. * Add a new target to this manager
  102460. * @param target defines the target to add
  102461. */
  102462. MorphTargetManager.prototype.addTarget = function (target) {
  102463. var _this = this;
  102464. this._targets.push(target);
  102465. this._targetInfluenceChangedObservers.push(target.onInfluenceChanged.add(function (needUpdate) {
  102466. _this._syncActiveTargets(needUpdate);
  102467. }));
  102468. this._targetDataLayoutChangedObservers.push(target._onDataLayoutChanged.add(function () {
  102469. _this._syncActiveTargets(true);
  102470. }));
  102471. this._syncActiveTargets(true);
  102472. };
  102473. /**
  102474. * Removes a target from the manager
  102475. * @param target defines the target to remove
  102476. */
  102477. MorphTargetManager.prototype.removeTarget = function (target) {
  102478. var index = this._targets.indexOf(target);
  102479. if (index >= 0) {
  102480. this._targets.splice(index, 1);
  102481. target.onInfluenceChanged.remove(this._targetInfluenceChangedObservers.splice(index, 1)[0]);
  102482. target._onDataLayoutChanged.remove(this._targetDataLayoutChangedObservers.splice(index, 1)[0]);
  102483. this._syncActiveTargets(true);
  102484. }
  102485. };
  102486. /**
  102487. * Serializes the current manager into a Serialization object
  102488. * @returns the serialized object
  102489. */
  102490. MorphTargetManager.prototype.serialize = function () {
  102491. var serializationObject = {};
  102492. serializationObject.id = this.uniqueId;
  102493. serializationObject.targets = [];
  102494. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  102495. var target = _a[_i];
  102496. serializationObject.targets.push(target.serialize());
  102497. }
  102498. return serializationObject;
  102499. };
  102500. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  102501. var influenceCount = 0;
  102502. this._activeTargets.reset();
  102503. this._supportsNormals = true;
  102504. this._supportsTangents = true;
  102505. this._vertexCount = 0;
  102506. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  102507. var target = _a[_i];
  102508. if (target.influence === 0) {
  102509. continue;
  102510. }
  102511. this._activeTargets.push(target);
  102512. this._tempInfluences[influenceCount++] = target.influence;
  102513. this._supportsNormals = this._supportsNormals && target.hasNormals;
  102514. this._supportsTangents = this._supportsTangents && target.hasTangents;
  102515. var positions = target.getPositions();
  102516. if (positions) {
  102517. var vertexCount = positions.length / 3;
  102518. if (this._vertexCount === 0) {
  102519. this._vertexCount = vertexCount;
  102520. }
  102521. else if (this._vertexCount !== vertexCount) {
  102522. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  102523. return;
  102524. }
  102525. }
  102526. }
  102527. if (!this._influences || this._influences.length !== influenceCount) {
  102528. this._influences = new Float32Array(influenceCount);
  102529. }
  102530. for (var index = 0; index < influenceCount; index++) {
  102531. this._influences[index] = this._tempInfluences[index];
  102532. }
  102533. if (needUpdate) {
  102534. this.synchronize();
  102535. }
  102536. };
  102537. /**
  102538. * Syncrhonize the targets with all the meshes using this morph target manager
  102539. */
  102540. MorphTargetManager.prototype.synchronize = function () {
  102541. if (!this._scene) {
  102542. return;
  102543. }
  102544. // Flag meshes as dirty to resync with the active targets
  102545. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  102546. var mesh = _a[_i];
  102547. if (mesh.morphTargetManager === this) {
  102548. mesh._syncGeometryWithMorphTargetManager();
  102549. }
  102550. }
  102551. };
  102552. // Statics
  102553. /**
  102554. * Creates a new MorphTargetManager from serialized data
  102555. * @param serializationObject defines the serialized data
  102556. * @param scene defines the hosting scene
  102557. * @returns the new MorphTargetManager
  102558. */
  102559. MorphTargetManager.Parse = function (serializationObject, scene) {
  102560. var result = new MorphTargetManager(scene);
  102561. result._uniqueId = serializationObject.id;
  102562. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  102563. var targetData = _a[_i];
  102564. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  102565. }
  102566. return result;
  102567. };
  102568. return MorphTargetManager;
  102569. }());
  102570. BABYLON.MorphTargetManager = MorphTargetManager;
  102571. })(BABYLON || (BABYLON = {}));
  102572. //# sourceMappingURL=babylon.morphTargetManager.js.map
  102573. var BABYLON;
  102574. (function (BABYLON) {
  102575. /**
  102576. * Octrees are a really powerful data structure that can quickly select entities based on space coordinates.
  102577. * @see https://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  102578. */
  102579. var Octree = /** @class */ (function () {
  102580. /**
  102581. * Creates a octree
  102582. * @see https://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  102583. * @param creationFunc function to be used to instatiate the octree
  102584. * @param maxBlockCapacity defines the maximum number of meshes you want on your octree's leaves (default: 64)
  102585. * @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.)
  102586. */
  102587. function Octree(creationFunc, maxBlockCapacity,
  102588. /** 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.) */
  102589. maxDepth) {
  102590. if (maxDepth === void 0) { maxDepth = 2; }
  102591. this.maxDepth = maxDepth;
  102592. /**
  102593. * Content stored in the octree
  102594. */
  102595. this.dynamicContent = new Array();
  102596. this._maxBlockCapacity = maxBlockCapacity || 64;
  102597. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  102598. this._creationFunc = creationFunc;
  102599. }
  102600. // Methods
  102601. /**
  102602. * Updates the octree by adding blocks for the passed in meshes within the min and max world parameters
  102603. * @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);
  102604. * @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);
  102605. * @param entries meshes to be added to the octree blocks
  102606. */
  102607. Octree.prototype.update = function (worldMin, worldMax, entries) {
  102608. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  102609. };
  102610. /**
  102611. * Adds a mesh to the octree
  102612. * @param entry Mesh to add to the octree
  102613. */
  102614. Octree.prototype.addMesh = function (entry) {
  102615. for (var index = 0; index < this.blocks.length; index++) {
  102616. var block = this.blocks[index];
  102617. block.addEntry(entry);
  102618. }
  102619. };
  102620. /**
  102621. * Selects an array of meshes within the frustum
  102622. * @param frustumPlanes The frustum planes to use which will select all meshes within it
  102623. * @param allowDuplicate If duplicate objects are allowed in the resulting object array
  102624. * @returns array of meshes within the frustum
  102625. */
  102626. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  102627. this._selectionContent.reset();
  102628. for (var index = 0; index < this.blocks.length; index++) {
  102629. var block = this.blocks[index];
  102630. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  102631. }
  102632. if (allowDuplicate) {
  102633. this._selectionContent.concat(this.dynamicContent);
  102634. }
  102635. else {
  102636. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  102637. }
  102638. return this._selectionContent;
  102639. };
  102640. /**
  102641. * Test if the octree intersect with the given bounding sphere and if yes, then add its content to the selection array
  102642. * @param sphereCenter defines the bounding sphere center
  102643. * @param sphereRadius defines the bounding sphere radius
  102644. * @param allowDuplicate defines if the selection array can contains duplicated entries
  102645. * @returns an array of objects that intersect the sphere
  102646. */
  102647. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  102648. this._selectionContent.reset();
  102649. for (var index = 0; index < this.blocks.length; index++) {
  102650. var block = this.blocks[index];
  102651. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  102652. }
  102653. if (allowDuplicate) {
  102654. this._selectionContent.concat(this.dynamicContent);
  102655. }
  102656. else {
  102657. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  102658. }
  102659. return this._selectionContent;
  102660. };
  102661. /**
  102662. * Test if the octree intersect with the given ray and if yes, then add its content to resulting array
  102663. * @param ray defines the ray to test with
  102664. * @returns array of intersected objects
  102665. */
  102666. Octree.prototype.intersectsRay = function (ray) {
  102667. this._selectionContent.reset();
  102668. for (var index = 0; index < this.blocks.length; index++) {
  102669. var block = this.blocks[index];
  102670. block.intersectsRay(ray, this._selectionContent);
  102671. }
  102672. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  102673. return this._selectionContent;
  102674. };
  102675. /**
  102676. * @hidden
  102677. */
  102678. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  102679. target.blocks = new Array();
  102680. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  102681. // Segmenting space
  102682. for (var x = 0; x < 2; x++) {
  102683. for (var y = 0; y < 2; y++) {
  102684. for (var z = 0; z < 2; z++) {
  102685. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  102686. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  102687. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  102688. block.addEntries(entries);
  102689. target.blocks.push(block);
  102690. }
  102691. }
  102692. }
  102693. };
  102694. /**
  102695. * Adds a mesh into the octree block if it intersects the block
  102696. */
  102697. Octree.CreationFuncForMeshes = function (entry, block) {
  102698. var boundingInfo = entry.getBoundingInfo();
  102699. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  102700. block.entries.push(entry);
  102701. }
  102702. };
  102703. /**
  102704. * Adds a submesh into the octree block if it intersects the block
  102705. */
  102706. Octree.CreationFuncForSubMeshes = function (entry, block) {
  102707. var boundingInfo = entry.getBoundingInfo();
  102708. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  102709. block.entries.push(entry);
  102710. }
  102711. };
  102712. return Octree;
  102713. }());
  102714. BABYLON.Octree = Octree;
  102715. })(BABYLON || (BABYLON = {}));
  102716. //# sourceMappingURL=babylon.octree.js.map
  102717. var BABYLON;
  102718. (function (BABYLON) {
  102719. /**
  102720. * Class used to store a cell in an octree
  102721. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  102722. */
  102723. var OctreeBlock = /** @class */ (function () {
  102724. /**
  102725. * Creates a new block
  102726. * @param minPoint defines the minimum vector (in world space) of the block's bounding box
  102727. * @param maxPoint defines the maximum vector (in world space) of the block's bounding box
  102728. * @param capacity defines the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  102729. * @param depth defines the current depth of this block in the octree
  102730. * @param maxDepth defines the maximal depth allowed (beyond this value, the capacity is ignored)
  102731. * @param creationFunc defines a callback to call when an element is added to the block
  102732. */
  102733. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  102734. /**
  102735. * Gets the content of the current block
  102736. */
  102737. this.entries = new Array();
  102738. this._boundingVectors = new Array();
  102739. this._capacity = capacity;
  102740. this._depth = depth;
  102741. this._maxDepth = maxDepth;
  102742. this._creationFunc = creationFunc;
  102743. this._minPoint = minPoint;
  102744. this._maxPoint = maxPoint;
  102745. this._boundingVectors.push(minPoint.clone());
  102746. this._boundingVectors.push(maxPoint.clone());
  102747. this._boundingVectors.push(minPoint.clone());
  102748. this._boundingVectors[2].x = maxPoint.x;
  102749. this._boundingVectors.push(minPoint.clone());
  102750. this._boundingVectors[3].y = maxPoint.y;
  102751. this._boundingVectors.push(minPoint.clone());
  102752. this._boundingVectors[4].z = maxPoint.z;
  102753. this._boundingVectors.push(maxPoint.clone());
  102754. this._boundingVectors[5].z = minPoint.z;
  102755. this._boundingVectors.push(maxPoint.clone());
  102756. this._boundingVectors[6].x = minPoint.x;
  102757. this._boundingVectors.push(maxPoint.clone());
  102758. this._boundingVectors[7].y = minPoint.y;
  102759. }
  102760. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  102761. // Property
  102762. /**
  102763. * Gets the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  102764. */
  102765. get: function () {
  102766. return this._capacity;
  102767. },
  102768. enumerable: true,
  102769. configurable: true
  102770. });
  102771. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  102772. /**
  102773. * Gets the minimum vector (in world space) of the block's bounding box
  102774. */
  102775. get: function () {
  102776. return this._minPoint;
  102777. },
  102778. enumerable: true,
  102779. configurable: true
  102780. });
  102781. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  102782. /**
  102783. * Gets the maximum vector (in world space) of the block's bounding box
  102784. */
  102785. get: function () {
  102786. return this._maxPoint;
  102787. },
  102788. enumerable: true,
  102789. configurable: true
  102790. });
  102791. // Methods
  102792. /**
  102793. * Add a new element to this block
  102794. * @param entry defines the element to add
  102795. */
  102796. OctreeBlock.prototype.addEntry = function (entry) {
  102797. if (this.blocks) {
  102798. for (var index = 0; index < this.blocks.length; index++) {
  102799. var block = this.blocks[index];
  102800. block.addEntry(entry);
  102801. }
  102802. return;
  102803. }
  102804. this._creationFunc(entry, this);
  102805. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  102806. this.createInnerBlocks();
  102807. }
  102808. };
  102809. /**
  102810. * Add an array of elements to this block
  102811. * @param entries defines the array of elements to add
  102812. */
  102813. OctreeBlock.prototype.addEntries = function (entries) {
  102814. for (var index = 0; index < entries.length; index++) {
  102815. var mesh = entries[index];
  102816. this.addEntry(mesh);
  102817. }
  102818. };
  102819. /**
  102820. * Test if the current block intersects the furstum planes and if yes, then add its content to the selection array
  102821. * @param frustumPlanes defines the frustum planes to test
  102822. * @param selection defines the array to store current content if selection is positive
  102823. * @param allowDuplicate defines if the selection array can contains duplicated entries
  102824. */
  102825. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  102826. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  102827. if (this.blocks) {
  102828. for (var index = 0; index < this.blocks.length; index++) {
  102829. var block = this.blocks[index];
  102830. block.select(frustumPlanes, selection, allowDuplicate);
  102831. }
  102832. return;
  102833. }
  102834. if (allowDuplicate) {
  102835. selection.concat(this.entries);
  102836. }
  102837. else {
  102838. selection.concatWithNoDuplicate(this.entries);
  102839. }
  102840. }
  102841. };
  102842. /**
  102843. * Test if the current block intersect with the given bounding sphere and if yes, then add its content to the selection array
  102844. * @param sphereCenter defines the bounding sphere center
  102845. * @param sphereRadius defines the bounding sphere radius
  102846. * @param selection defines the array to store current content if selection is positive
  102847. * @param allowDuplicate defines if the selection array can contains duplicated entries
  102848. */
  102849. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  102850. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  102851. if (this.blocks) {
  102852. for (var index = 0; index < this.blocks.length; index++) {
  102853. var block = this.blocks[index];
  102854. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  102855. }
  102856. return;
  102857. }
  102858. if (allowDuplicate) {
  102859. selection.concat(this.entries);
  102860. }
  102861. else {
  102862. selection.concatWithNoDuplicate(this.entries);
  102863. }
  102864. }
  102865. };
  102866. /**
  102867. * Test if the current block intersect with the given ray and if yes, then add its content to the selection array
  102868. * @param ray defines the ray to test with
  102869. * @param selection defines the array to store current content if selection is positive
  102870. */
  102871. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  102872. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  102873. if (this.blocks) {
  102874. for (var index = 0; index < this.blocks.length; index++) {
  102875. var block = this.blocks[index];
  102876. block.intersectsRay(ray, selection);
  102877. }
  102878. return;
  102879. }
  102880. selection.concatWithNoDuplicate(this.entries);
  102881. }
  102882. };
  102883. /**
  102884. * Subdivide the content into child blocks (this block will then be empty)
  102885. */
  102886. OctreeBlock.prototype.createInnerBlocks = function () {
  102887. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  102888. };
  102889. return OctreeBlock;
  102890. }());
  102891. BABYLON.OctreeBlock = OctreeBlock;
  102892. })(BABYLON || (BABYLON = {}));
  102893. //# sourceMappingURL=babylon.octreeBlock.js.map
  102894. var BABYLON;
  102895. (function (BABYLON) {
  102896. BABYLON.Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  102897. if (maxCapacity === void 0) { maxCapacity = 64; }
  102898. if (maxDepth === void 0) { maxDepth = 2; }
  102899. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  102900. if (!component) {
  102901. component = new OctreeSceneComponent(this);
  102902. this._addComponent(component);
  102903. }
  102904. if (!this._selectionOctree) {
  102905. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  102906. }
  102907. var worldExtends = this.getWorldExtends();
  102908. // Update octree
  102909. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  102910. return this._selectionOctree;
  102911. };
  102912. Object.defineProperty(BABYLON.Scene.prototype, "selectionOctree", {
  102913. get: function () {
  102914. return this._selectionOctree;
  102915. },
  102916. enumerable: true,
  102917. configurable: true
  102918. });
  102919. /**
  102920. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  102921. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  102922. * @param maxCapacity defines the maximum size of each block (64 by default)
  102923. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  102924. * @returns the new octree
  102925. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  102926. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  102927. */
  102928. BABYLON.AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  102929. if (maxCapacity === void 0) { maxCapacity = 64; }
  102930. if (maxDepth === void 0) { maxDepth = 2; }
  102931. var scene = this.getScene();
  102932. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  102933. if (!component) {
  102934. component = new OctreeSceneComponent(scene);
  102935. scene._addComponent(component);
  102936. }
  102937. if (!this._submeshesOctree) {
  102938. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  102939. }
  102940. this.computeWorldMatrix(true);
  102941. var boundingInfo = this.getBoundingInfo();
  102942. // Update octree
  102943. var bbox = boundingInfo.boundingBox;
  102944. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  102945. return this._submeshesOctree;
  102946. };
  102947. /**
  102948. * Defines the octree scene component responsible to manage any octrees
  102949. * in a given scene.
  102950. */
  102951. var OctreeSceneComponent = /** @class */ (function () {
  102952. /**
  102953. * Creates a new instance of the component for the given scene
  102954. * @param scene Defines the scene to register the component in
  102955. */
  102956. function OctreeSceneComponent(scene) {
  102957. /**
  102958. * The component name helpfull to identify the component in the list of scene components.
  102959. */
  102960. this.name = BABYLON.SceneComponentConstants.NAME_OCTREE;
  102961. /**
  102962. * Indicates if the meshes have been checked to make sure they are isEnabled()
  102963. */
  102964. this.checksIsEnabled = true;
  102965. this._tempRay = new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(1, 1, 1));
  102966. this.scene = scene;
  102967. this.scene.getActiveMeshCandidates = this.getActiveMeshCandidates.bind(this);
  102968. this.scene.getActiveSubMeshCandidates = this.getActiveSubMeshCandidates.bind(this);
  102969. this.scene.getCollidingSubMeshCandidates = this.getCollidingSubMeshCandidates.bind(this);
  102970. this.scene.getIntersectingSubMeshCandidates = this.getIntersectingSubMeshCandidates.bind(this);
  102971. }
  102972. /**
  102973. * Registers the component in a given scene
  102974. */
  102975. OctreeSceneComponent.prototype.register = function () {
  102976. var _this = this;
  102977. this.scene.onMeshRemovedObservable.add(function (mesh) {
  102978. var sceneOctree = _this.scene.selectionOctree;
  102979. if (sceneOctree !== undefined && sceneOctree !== null) {
  102980. var index = sceneOctree.dynamicContent.indexOf(mesh);
  102981. if (index !== -1) {
  102982. sceneOctree.dynamicContent.splice(index, 1);
  102983. }
  102984. }
  102985. });
  102986. this.scene.onMeshImportedObservable.add(function (mesh) {
  102987. var sceneOctree = _this.scene.selectionOctree;
  102988. if (sceneOctree !== undefined && sceneOctree !== null) {
  102989. sceneOctree.addMesh(mesh);
  102990. }
  102991. });
  102992. };
  102993. /**
  102994. * Return the list of active meshes
  102995. * @returns the list of active meshes
  102996. */
  102997. OctreeSceneComponent.prototype.getActiveMeshCandidates = function () {
  102998. if (this.scene._selectionOctree) {
  102999. var selection = this.scene._selectionOctree.select(this.scene.frustumPlanes);
  103000. return selection;
  103001. }
  103002. return this.scene._getDefaultMeshCandidates();
  103003. };
  103004. /**
  103005. * Return the list of active sub meshes
  103006. * @param mesh The mesh to get the candidates sub meshes from
  103007. * @returns the list of active sub meshes
  103008. */
  103009. OctreeSceneComponent.prototype.getActiveSubMeshCandidates = function (mesh) {
  103010. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  103011. var intersections = mesh._submeshesOctree.select(this.scene.frustumPlanes);
  103012. return intersections;
  103013. }
  103014. return this.scene._getDefaultSubMeshCandidates(mesh);
  103015. };
  103016. /**
  103017. * Return the list of sub meshes intersecting with a given local ray
  103018. * @param mesh defines the mesh to find the submesh for
  103019. * @param localRay defines the ray in local space
  103020. * @returns the list of intersecting sub meshes
  103021. */
  103022. OctreeSceneComponent.prototype.getIntersectingSubMeshCandidates = function (mesh, localRay) {
  103023. if (mesh._submeshesOctree && mesh.useOctreeForPicking) {
  103024. BABYLON.Ray.TransformToRef(localRay, mesh.getWorldMatrix(), this._tempRay);
  103025. var intersections = mesh._submeshesOctree.intersectsRay(this._tempRay);
  103026. return intersections;
  103027. }
  103028. return this.scene._getDefaultSubMeshCandidates(mesh);
  103029. };
  103030. /**
  103031. * Return the list of sub meshes colliding with a collider
  103032. * @param mesh defines the mesh to find the submesh for
  103033. * @param collider defines the collider to evaluate the collision against
  103034. * @returns the list of colliding sub meshes
  103035. */
  103036. OctreeSceneComponent.prototype.getCollidingSubMeshCandidates = function (mesh, collider) {
  103037. if (mesh._submeshesOctree && mesh.useOctreeForCollisions) {
  103038. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  103039. var intersections = mesh._submeshesOctree.intersects(collider._basePointWorld, radius);
  103040. return intersections;
  103041. }
  103042. return this.scene._getDefaultSubMeshCandidates(mesh);
  103043. };
  103044. /**
  103045. * Rebuilds the elements related to this component in case of
  103046. * context lost for instance.
  103047. */
  103048. OctreeSceneComponent.prototype.rebuild = function () {
  103049. // Nothing to do here.
  103050. };
  103051. /**
  103052. * Disposes the component and the associated ressources.
  103053. */
  103054. OctreeSceneComponent.prototype.dispose = function () {
  103055. // Nothing to do here.
  103056. };
  103057. return OctreeSceneComponent;
  103058. }());
  103059. BABYLON.OctreeSceneComponent = OctreeSceneComponent;
  103060. })(BABYLON || (BABYLON = {}));
  103061. //# sourceMappingURL=babylon.octreeSceneComponent.js.map
  103062. var BABYLON;
  103063. (function (BABYLON) {
  103064. /**
  103065. * Postprocess used to generate anaglyphic rendering
  103066. */
  103067. var AnaglyphPostProcess = /** @class */ (function (_super) {
  103068. __extends(AnaglyphPostProcess, _super);
  103069. /**
  103070. * Creates a new AnaglyphPostProcess
  103071. * @param name defines postprocess name
  103072. * @param options defines creation options or target ratio scale
  103073. * @param rigCameras defines cameras using this postprocess
  103074. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  103075. * @param engine defines hosting engine
  103076. * @param reusable defines if the postprocess will be reused multiple times per frame
  103077. */
  103078. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  103079. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  103080. _this._passedProcess = rigCameras[0]._rigPostProcess;
  103081. _this.onApplyObservable.add(function (effect) {
  103082. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  103083. });
  103084. return _this;
  103085. }
  103086. return AnaglyphPostProcess;
  103087. }(BABYLON.PostProcess));
  103088. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  103089. })(BABYLON || (BABYLON = {}));
  103090. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  103091. var BABYLON;
  103092. (function (BABYLON) {
  103093. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  103094. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  103095. });
  103096. /**
  103097. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  103098. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  103099. */
  103100. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  103101. __extends(AnaglyphArcRotateCamera, _super);
  103102. /**
  103103. * Creates a new AnaglyphArcRotateCamera
  103104. * @param name defines camera name
  103105. * @param alpha defines alpha angle (in radians)
  103106. * @param beta defines beta angle (in radians)
  103107. * @param radius defines radius
  103108. * @param target defines camera target
  103109. * @param interaxialDistance defines distance between each color axis
  103110. * @param scene defines the hosting scene
  103111. */
  103112. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  103113. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  103114. _this.interaxialDistance = interaxialDistance;
  103115. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  103116. return _this;
  103117. }
  103118. /**
  103119. * Gets camera class name
  103120. * @returns AnaglyphArcRotateCamera
  103121. */
  103122. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  103123. return "AnaglyphArcRotateCamera";
  103124. };
  103125. return AnaglyphArcRotateCamera;
  103126. }(BABYLON.ArcRotateCamera));
  103127. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  103128. })(BABYLON || (BABYLON = {}));
  103129. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  103130. var BABYLON;
  103131. (function (BABYLON) {
  103132. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  103133. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  103134. });
  103135. /**
  103136. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  103137. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  103138. */
  103139. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  103140. __extends(AnaglyphFreeCamera, _super);
  103141. /**
  103142. * Creates a new AnaglyphFreeCamera
  103143. * @param name defines camera name
  103144. * @param position defines initial position
  103145. * @param interaxialDistance defines distance between each color axis
  103146. * @param scene defines the hosting scene
  103147. */
  103148. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  103149. var _this = _super.call(this, name, position, scene) || this;
  103150. _this.interaxialDistance = interaxialDistance;
  103151. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  103152. return _this;
  103153. }
  103154. /**
  103155. * Gets camera class name
  103156. * @returns AnaglyphFreeCamera
  103157. */
  103158. AnaglyphFreeCamera.prototype.getClassName = function () {
  103159. return "AnaglyphFreeCamera";
  103160. };
  103161. return AnaglyphFreeCamera;
  103162. }(BABYLON.FreeCamera));
  103163. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  103164. })(BABYLON || (BABYLON = {}));
  103165. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  103166. var BABYLON;
  103167. (function (BABYLON) {
  103168. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  103169. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  103170. });
  103171. /**
  103172. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  103173. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  103174. */
  103175. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  103176. __extends(AnaglyphGamepadCamera, _super);
  103177. /**
  103178. * Creates a new AnaglyphGamepadCamera
  103179. * @param name defines camera name
  103180. * @param position defines initial position
  103181. * @param interaxialDistance defines distance between each color axis
  103182. * @param scene defines the hosting scene
  103183. */
  103184. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  103185. var _this = _super.call(this, name, position, scene) || this;
  103186. _this.interaxialDistance = interaxialDistance;
  103187. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  103188. return _this;
  103189. }
  103190. /**
  103191. * Gets camera class name
  103192. * @returns AnaglyphGamepadCamera
  103193. */
  103194. AnaglyphGamepadCamera.prototype.getClassName = function () {
  103195. return "AnaglyphGamepadCamera";
  103196. };
  103197. return AnaglyphGamepadCamera;
  103198. }(BABYLON.GamepadCamera));
  103199. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  103200. })(BABYLON || (BABYLON = {}));
  103201. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  103202. var BABYLON;
  103203. (function (BABYLON) {
  103204. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  103205. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  103206. });
  103207. /**
  103208. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  103209. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  103210. */
  103211. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  103212. __extends(AnaglyphUniversalCamera, _super);
  103213. /**
  103214. * Creates a new AnaglyphUniversalCamera
  103215. * @param name defines camera name
  103216. * @param position defines initial position
  103217. * @param interaxialDistance defines distance between each color axis
  103218. * @param scene defines the hosting scene
  103219. */
  103220. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  103221. var _this = _super.call(this, name, position, scene) || this;
  103222. _this.interaxialDistance = interaxialDistance;
  103223. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  103224. return _this;
  103225. }
  103226. /**
  103227. * Gets camera class name
  103228. * @returns AnaglyphUniversalCamera
  103229. */
  103230. AnaglyphUniversalCamera.prototype.getClassName = function () {
  103231. return "AnaglyphUniversalCamera";
  103232. };
  103233. return AnaglyphUniversalCamera;
  103234. }(BABYLON.UniversalCamera));
  103235. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  103236. })(BABYLON || (BABYLON = {}));
  103237. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  103238. var BABYLON;
  103239. (function (BABYLON) {
  103240. /**
  103241. * StereoscopicInterlacePostProcess used to render stereo views from a rigged camera
  103242. */
  103243. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  103244. __extends(StereoscopicInterlacePostProcess, _super);
  103245. /**
  103246. * Initializes a StereoscopicInterlacePostProcess
  103247. * @param name The name of the effect.
  103248. * @param rigCameras The rig cameras to be appled to the post process
  103249. * @param isStereoscopicHoriz If the rendered results are horizontal or verticle
  103250. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  103251. * @param engine The engine which the post process will be applied. (default: current engine)
  103252. * @param reusable If the post process can be reused on the same frame. (default: false)
  103253. */
  103254. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  103255. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  103256. _this._passedProcess = rigCameras[0]._rigPostProcess;
  103257. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  103258. _this.onSizeChangedObservable.add(function () {
  103259. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  103260. });
  103261. _this.onApplyObservable.add(function (effect) {
  103262. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  103263. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  103264. });
  103265. return _this;
  103266. }
  103267. return StereoscopicInterlacePostProcess;
  103268. }(BABYLON.PostProcess));
  103269. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  103270. })(BABYLON || (BABYLON = {}));
  103271. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  103272. var BABYLON;
  103273. (function (BABYLON) {
  103274. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  103275. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  103276. });
  103277. /**
  103278. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  103279. * @see http://doc.babylonjs.com/features/cameras
  103280. */
  103281. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  103282. __extends(StereoscopicArcRotateCamera, _super);
  103283. /**
  103284. * Creates a new StereoscopicArcRotateCamera
  103285. * @param name defines camera name
  103286. * @param alpha defines alpha angle (in radians)
  103287. * @param beta defines beta angle (in radians)
  103288. * @param radius defines radius
  103289. * @param target defines camera target
  103290. * @param interaxialDistance defines distance between each color axis
  103291. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  103292. * @param scene defines the hosting scene
  103293. */
  103294. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  103295. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  103296. _this.interaxialDistance = interaxialDistance;
  103297. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  103298. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  103299. return _this;
  103300. }
  103301. /**
  103302. * Gets camera class name
  103303. * @returns StereoscopicArcRotateCamera
  103304. */
  103305. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  103306. return "StereoscopicArcRotateCamera";
  103307. };
  103308. return StereoscopicArcRotateCamera;
  103309. }(BABYLON.ArcRotateCamera));
  103310. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  103311. })(BABYLON || (BABYLON = {}));
  103312. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  103313. var BABYLON;
  103314. (function (BABYLON) {
  103315. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  103316. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  103317. });
  103318. /**
  103319. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  103320. * @see http://doc.babylonjs.com/features/cameras
  103321. */
  103322. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  103323. __extends(StereoscopicFreeCamera, _super);
  103324. /**
  103325. * Creates a new StereoscopicFreeCamera
  103326. * @param name defines camera name
  103327. * @param position defines initial position
  103328. * @param interaxialDistance defines distance between each color axis
  103329. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  103330. * @param scene defines the hosting scene
  103331. */
  103332. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  103333. var _this = _super.call(this, name, position, scene) || this;
  103334. _this.interaxialDistance = interaxialDistance;
  103335. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  103336. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  103337. return _this;
  103338. }
  103339. /**
  103340. * Gets camera class name
  103341. * @returns StereoscopicFreeCamera
  103342. */
  103343. StereoscopicFreeCamera.prototype.getClassName = function () {
  103344. return "StereoscopicFreeCamera";
  103345. };
  103346. return StereoscopicFreeCamera;
  103347. }(BABYLON.FreeCamera));
  103348. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  103349. })(BABYLON || (BABYLON = {}));
  103350. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  103351. var BABYLON;
  103352. (function (BABYLON) {
  103353. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  103354. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  103355. });
  103356. /**
  103357. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  103358. * @see http://doc.babylonjs.com/features/cameras
  103359. */
  103360. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  103361. __extends(StereoscopicGamepadCamera, _super);
  103362. /**
  103363. * Creates a new StereoscopicGamepadCamera
  103364. * @param name defines camera name
  103365. * @param position defines initial position
  103366. * @param interaxialDistance defines distance between each color axis
  103367. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  103368. * @param scene defines the hosting scene
  103369. */
  103370. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  103371. var _this = _super.call(this, name, position, scene) || this;
  103372. _this.interaxialDistance = interaxialDistance;
  103373. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  103374. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  103375. return _this;
  103376. }
  103377. /**
  103378. * Gets camera class name
  103379. * @returns StereoscopicGamepadCamera
  103380. */
  103381. StereoscopicGamepadCamera.prototype.getClassName = function () {
  103382. return "StereoscopicGamepadCamera";
  103383. };
  103384. return StereoscopicGamepadCamera;
  103385. }(BABYLON.GamepadCamera));
  103386. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  103387. })(BABYLON || (BABYLON = {}));
  103388. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  103389. var BABYLON;
  103390. (function (BABYLON) {
  103391. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  103392. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  103393. });
  103394. /**
  103395. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  103396. * @see http://doc.babylonjs.com/features/cameras
  103397. */
  103398. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  103399. __extends(StereoscopicUniversalCamera, _super);
  103400. /**
  103401. * Creates a new StereoscopicUniversalCamera
  103402. * @param name defines camera name
  103403. * @param position defines initial position
  103404. * @param interaxialDistance defines distance between each color axis
  103405. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  103406. * @param scene defines the hosting scene
  103407. */
  103408. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  103409. var _this = _super.call(this, name, position, scene) || this;
  103410. _this.interaxialDistance = interaxialDistance;
  103411. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  103412. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  103413. return _this;
  103414. }
  103415. /**
  103416. * Gets camera class name
  103417. * @returns StereoscopicUniversalCamera
  103418. */
  103419. StereoscopicUniversalCamera.prototype.getClassName = function () {
  103420. return "StereoscopicUniversalCamera";
  103421. };
  103422. return StereoscopicUniversalCamera;
  103423. }(BABYLON.UniversalCamera));
  103424. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  103425. })(BABYLON || (BABYLON = {}));
  103426. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  103427. var BABYLON;
  103428. (function (BABYLON) {
  103429. /**
  103430. * VRDistortionCorrectionPostProcess used for mobile VR
  103431. */
  103432. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  103433. __extends(VRDistortionCorrectionPostProcess, _super);
  103434. /**
  103435. * Initializes the VRDistortionCorrectionPostProcess
  103436. * @param name The name of the effect.
  103437. * @param camera The camera to apply the render pass to.
  103438. * @param isRightEye If this is for the right eye distortion
  103439. * @param vrMetrics All the required metrics for the VR camera
  103440. */
  103441. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  103442. var _this = _super.call(this, name, "vrDistortionCorrection", [
  103443. 'LensCenter',
  103444. 'Scale',
  103445. 'ScaleIn',
  103446. 'HmdWarpParam'
  103447. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  103448. _this._isRightEye = isRightEye;
  103449. _this._distortionFactors = vrMetrics.distortionK;
  103450. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  103451. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  103452. _this.adaptScaleToCurrentViewport = true;
  103453. _this.onSizeChangedObservable.add(function () {
  103454. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  103455. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  103456. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  103457. });
  103458. _this.onApplyObservable.add(function (effect) {
  103459. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  103460. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  103461. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  103462. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  103463. });
  103464. return _this;
  103465. }
  103466. return VRDistortionCorrectionPostProcess;
  103467. }(BABYLON.PostProcess));
  103468. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  103469. })(BABYLON || (BABYLON = {}));
  103470. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  103471. var BABYLON;
  103472. (function (BABYLON) {
  103473. /**
  103474. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  103475. * Screen rotation is taken into account.
  103476. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  103477. */
  103478. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  103479. /**
  103480. * Instantiates a new input
  103481. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  103482. */
  103483. function FreeCameraDeviceOrientationInput() {
  103484. var _this = this;
  103485. this._screenOrientationAngle = 0;
  103486. this._screenQuaternion = new BABYLON.Quaternion();
  103487. this._alpha = 0;
  103488. this._beta = 0;
  103489. this._gamma = 0;
  103490. this._orientationChanged = function () {
  103491. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  103492. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  103493. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  103494. };
  103495. this._deviceOrientation = function (evt) {
  103496. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  103497. _this._beta = evt.beta !== null ? evt.beta : 0;
  103498. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  103499. };
  103500. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  103501. this._orientationChanged();
  103502. }
  103503. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  103504. /**
  103505. * Define the camera controlled by the input.
  103506. */
  103507. get: function () {
  103508. return this._camera;
  103509. },
  103510. set: function (camera) {
  103511. this._camera = camera;
  103512. if (this._camera != null && !this._camera.rotationQuaternion) {
  103513. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  103514. }
  103515. },
  103516. enumerable: true,
  103517. configurable: true
  103518. });
  103519. /**
  103520. * Attach the input controls to a specific dom element to get the input from.
  103521. * @param element Defines the element the controls should be listened from
  103522. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  103523. */
  103524. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  103525. window.addEventListener("orientationchange", this._orientationChanged);
  103526. window.addEventListener("deviceorientation", this._deviceOrientation);
  103527. //In certain cases, the attach control is called AFTER orientation was changed,
  103528. //So this is needed.
  103529. this._orientationChanged();
  103530. };
  103531. /**
  103532. * Detach the current controls from the specified dom element.
  103533. * @param element Defines the element to stop listening the inputs from
  103534. */
  103535. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  103536. window.removeEventListener("orientationchange", this._orientationChanged);
  103537. window.removeEventListener("deviceorientation", this._deviceOrientation);
  103538. };
  103539. /**
  103540. * Update the current camera state depending on the inputs that have been used this frame.
  103541. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  103542. */
  103543. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  103544. //if no device orientation provided, don't update the rotation.
  103545. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  103546. if (!this._alpha) {
  103547. return;
  103548. }
  103549. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  103550. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  103551. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  103552. //Mirror on XY Plane
  103553. this._camera.rotationQuaternion.z *= -1;
  103554. this._camera.rotationQuaternion.w *= -1;
  103555. };
  103556. /**
  103557. * Gets the class name of the current intput.
  103558. * @returns the class name
  103559. */
  103560. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  103561. return "FreeCameraDeviceOrientationInput";
  103562. };
  103563. /**
  103564. * Get the friendly name associated with the input class.
  103565. * @returns the input friendly name
  103566. */
  103567. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  103568. return "deviceOrientation";
  103569. };
  103570. return FreeCameraDeviceOrientationInput;
  103571. }());
  103572. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  103573. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  103574. })(BABYLON || (BABYLON = {}));
  103575. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  103576. var BABYLON;
  103577. (function (BABYLON) {
  103578. /**
  103579. * Manage the device orientation inputs (gyroscope) to control an arc rotate camera.
  103580. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  103581. */
  103582. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  103583. /**
  103584. * Instantiate a new ArcRotateCameraVRDeviceOrientationInput.
  103585. */
  103586. function ArcRotateCameraVRDeviceOrientationInput() {
  103587. /**
  103588. * Defines a correction factor applied on the alpha value retrieved from the orientation events.
  103589. */
  103590. this.alphaCorrection = 1;
  103591. /**
  103592. * Defines a correction factor applied on the beta value retrieved from the orientation events.
  103593. */
  103594. this.betaCorrection = 1;
  103595. /**
  103596. * Defines a correction factor applied on the gamma value retrieved from the orientation events.
  103597. */
  103598. this.gammaCorrection = 1;
  103599. this._alpha = 0;
  103600. this._gamma = 0;
  103601. this._dirty = false;
  103602. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  103603. }
  103604. /**
  103605. * Attach the input controls to a specific dom element to get the input from.
  103606. * @param element Defines the element the controls should be listened from
  103607. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  103608. */
  103609. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  103610. this.camera.attachControl(element, noPreventDefault);
  103611. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  103612. };
  103613. /** @hidden */
  103614. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  103615. if (evt.alpha !== null) {
  103616. this._alpha = +evt.alpha | 0;
  103617. }
  103618. if (evt.gamma !== null) {
  103619. this._gamma = +evt.gamma | 0;
  103620. }
  103621. this._dirty = true;
  103622. };
  103623. /**
  103624. * Update the current camera state depending on the inputs that have been used this frame.
  103625. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  103626. */
  103627. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  103628. if (this._dirty) {
  103629. this._dirty = false;
  103630. if (this._gamma < 0) {
  103631. this._gamma = 180 + this._gamma;
  103632. }
  103633. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  103634. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  103635. }
  103636. };
  103637. /**
  103638. * Detach the current controls from the specified dom element.
  103639. * @param element Defines the element to stop listening the inputs from
  103640. */
  103641. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  103642. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  103643. };
  103644. /**
  103645. * Gets the class name of the current intput.
  103646. * @returns the class name
  103647. */
  103648. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  103649. return "ArcRotateCameraVRDeviceOrientationInput";
  103650. };
  103651. /**
  103652. * Get the friendly name associated with the input class.
  103653. * @returns the input friendly name
  103654. */
  103655. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  103656. return "VRDeviceOrientation";
  103657. };
  103658. return ArcRotateCameraVRDeviceOrientationInput;
  103659. }());
  103660. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  103661. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  103662. })(BABYLON || (BABYLON = {}));
  103663. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  103664. var BABYLON;
  103665. (function (BABYLON) {
  103666. /**
  103667. * This represents all the required metrics to create a VR camera.
  103668. * @see http://doc.babylonjs.com/babylon101/cameras#device-orientation-camera
  103669. */
  103670. var VRCameraMetrics = /** @class */ (function () {
  103671. function VRCameraMetrics() {
  103672. /**
  103673. * Define if the current vr camera should compensate the distortion of the lense or not.
  103674. */
  103675. this.compensateDistortion = true;
  103676. }
  103677. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  103678. /**
  103679. * Gets the rendering aspect ratio based on the provided resolutions.
  103680. */
  103681. get: function () {
  103682. return this.hResolution / (2 * this.vResolution);
  103683. },
  103684. enumerable: true,
  103685. configurable: true
  103686. });
  103687. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  103688. /**
  103689. * Gets the aspect ratio based on the FOV, scale factors, and real screen sizes.
  103690. */
  103691. get: function () {
  103692. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  103693. },
  103694. enumerable: true,
  103695. configurable: true
  103696. });
  103697. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  103698. /**
  103699. * @hidden
  103700. */
  103701. get: function () {
  103702. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  103703. var h = (4 * meters) / this.hScreenSize;
  103704. return BABYLON.Matrix.Translation(h, 0, 0);
  103705. },
  103706. enumerable: true,
  103707. configurable: true
  103708. });
  103709. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  103710. /**
  103711. * @hidden
  103712. */
  103713. get: function () {
  103714. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  103715. var h = (4 * meters) / this.hScreenSize;
  103716. return BABYLON.Matrix.Translation(-h, 0, 0);
  103717. },
  103718. enumerable: true,
  103719. configurable: true
  103720. });
  103721. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  103722. /**
  103723. * @hidden
  103724. */
  103725. get: function () {
  103726. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  103727. },
  103728. enumerable: true,
  103729. configurable: true
  103730. });
  103731. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  103732. /**
  103733. * @hidden
  103734. */
  103735. get: function () {
  103736. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  103737. },
  103738. enumerable: true,
  103739. configurable: true
  103740. });
  103741. /**
  103742. * Get the default VRMetrics based on the most generic setup.
  103743. * @returns the default vr metrics
  103744. */
  103745. VRCameraMetrics.GetDefault = function () {
  103746. var result = new VRCameraMetrics();
  103747. result.hResolution = 1280;
  103748. result.vResolution = 800;
  103749. result.hScreenSize = 0.149759993;
  103750. result.vScreenSize = 0.0935999975;
  103751. result.vScreenCenter = 0.0467999987;
  103752. result.eyeToScreenDistance = 0.0410000011;
  103753. result.lensSeparationDistance = 0.0635000020;
  103754. result.interpupillaryDistance = 0.0640000030;
  103755. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  103756. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  103757. result.postProcessScaleFactor = 1.714605507808412;
  103758. result.lensCenterOffset = 0.151976421;
  103759. return result;
  103760. };
  103761. return VRCameraMetrics;
  103762. }());
  103763. BABYLON.VRCameraMetrics = VRCameraMetrics;
  103764. })(BABYLON || (BABYLON = {}));
  103765. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  103766. var BABYLON;
  103767. (function (BABYLON) {
  103768. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  103769. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  103770. });
  103771. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  103772. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  103773. });
  103774. /**
  103775. * This represents a WebVR camera.
  103776. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  103777. * @example http://doc.babylonjs.com/how_to/webvr_camera
  103778. */
  103779. var WebVRFreeCamera = /** @class */ (function (_super) {
  103780. __extends(WebVRFreeCamera, _super);
  103781. /**
  103782. * Instantiates a WebVRFreeCamera.
  103783. * @param name The name of the WebVRFreeCamera
  103784. * @param position The starting anchor position for the camera
  103785. * @param scene The scene the camera belongs to
  103786. * @param webVROptions a set of customizable options for the webVRCamera
  103787. */
  103788. function WebVRFreeCamera(name, position, scene, webVROptions) {
  103789. if (webVROptions === void 0) { webVROptions = {}; }
  103790. var _this = _super.call(this, name, position, scene) || this;
  103791. _this.webVROptions = webVROptions;
  103792. /**
  103793. * @hidden
  103794. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  103795. */
  103796. _this._vrDevice = null;
  103797. /**
  103798. * The rawPose of the vrDevice.
  103799. */
  103800. _this.rawPose = null;
  103801. _this._specsVersion = "1.1";
  103802. _this._attached = false;
  103803. _this._descendants = [];
  103804. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  103805. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  103806. /** @hidden */
  103807. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  103808. _this._standingMatrix = null;
  103809. /**
  103810. * Represents device position in babylon space.
  103811. */
  103812. _this.devicePosition = BABYLON.Vector3.Zero();
  103813. /**
  103814. * Represents device rotation in babylon space.
  103815. */
  103816. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  103817. /**
  103818. * The scale of the device to be used when translating from device space to babylon space.
  103819. */
  103820. _this.deviceScaleFactor = 1;
  103821. _this._deviceToWorld = BABYLON.Matrix.Identity();
  103822. _this._worldToDevice = BABYLON.Matrix.Identity();
  103823. /**
  103824. * References to the webVR controllers for the vrDevice.
  103825. */
  103826. _this.controllers = [];
  103827. /**
  103828. * Emits an event when a controller is attached.
  103829. */
  103830. _this.onControllersAttachedObservable = new BABYLON.Observable();
  103831. /**
  103832. * Emits an event when a controller's mesh has been loaded;
  103833. */
  103834. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  103835. /**
  103836. * Emits an event when the HMD's pose has been updated.
  103837. */
  103838. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  103839. _this._poseSet = false;
  103840. /**
  103841. * If the rig cameras be used as parent instead of this camera.
  103842. */
  103843. _this.rigParenting = true;
  103844. _this._defaultHeight = undefined;
  103845. _this._htmlElementAttached = null;
  103846. _this._detachIfAttached = function () {
  103847. var vrDisplay = _this.getEngine().getVRDevice();
  103848. if (vrDisplay && !vrDisplay.isPresenting && _this._htmlElementAttached) {
  103849. _this.detachControl(_this._htmlElementAttached);
  103850. }
  103851. };
  103852. _this._workingVector = BABYLON.Vector3.Zero();
  103853. _this._oneVector = BABYLON.Vector3.One();
  103854. _this._workingMatrix = BABYLON.Matrix.Identity();
  103855. _this._tmpMatrix = new BABYLON.Matrix();
  103856. _this._cache.position = BABYLON.Vector3.Zero();
  103857. if (webVROptions.defaultHeight) {
  103858. _this._defaultHeight = webVROptions.defaultHeight;
  103859. _this.position.y = _this._defaultHeight;
  103860. }
  103861. _this.minZ = 0.1;
  103862. //legacy support - the compensation boolean was removed.
  103863. if (arguments.length === 5) {
  103864. _this.webVROptions = arguments[4];
  103865. }
  103866. // default webVR options
  103867. if (_this.webVROptions.trackPosition == undefined) {
  103868. _this.webVROptions.trackPosition = true;
  103869. }
  103870. if (_this.webVROptions.controllerMeshes == undefined) {
  103871. _this.webVROptions.controllerMeshes = true;
  103872. }
  103873. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  103874. _this.webVROptions.defaultLightingOnControllers = true;
  103875. }
  103876. _this.rotationQuaternion = new BABYLON.Quaternion();
  103877. if (_this.webVROptions && _this.webVROptions.positionScale) {
  103878. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  103879. }
  103880. //enable VR
  103881. var engine = _this.getEngine();
  103882. _this._onVREnabled = function (success) { if (success) {
  103883. _this.initControllers();
  103884. } };
  103885. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  103886. engine.initWebVR().add(function (event) {
  103887. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  103888. return;
  103889. }
  103890. _this._vrDevice = event.vrDisplay;
  103891. //reset the rig parameters.
  103892. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  103893. if (_this._attached) {
  103894. _this.getEngine().enableVR();
  103895. }
  103896. });
  103897. if (typeof (VRFrameData) !== "undefined") {
  103898. _this._frameData = new VRFrameData();
  103899. }
  103900. /**
  103901. * The idea behind the following lines:
  103902. * objects that have the camera as parent should actually have the rig cameras as a parent.
  103903. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  103904. * the second will not show it correctly.
  103905. *
  103906. * To solve this - each object that has the camera as parent will be added to a protected array.
  103907. * When the rig camera renders, it will take this array and set all of those to be its children.
  103908. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  103909. * Amazing!
  103910. */
  103911. scene.onBeforeCameraRenderObservable.add(function (camera) {
  103912. if (camera.parent === _this && _this.rigParenting) {
  103913. _this._descendants = _this.getDescendants(true, function (n) {
  103914. // don't take the cameras or the controllers!
  103915. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  103916. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  103917. return !isController && !isRigCamera;
  103918. });
  103919. _this._descendants.forEach(function (node) {
  103920. node.parent = camera;
  103921. });
  103922. }
  103923. });
  103924. scene.onAfterCameraRenderObservable.add(function (camera) {
  103925. if (camera.parent === _this && _this.rigParenting) {
  103926. _this._descendants.forEach(function (node) {
  103927. node.parent = _this;
  103928. });
  103929. }
  103930. });
  103931. return _this;
  103932. }
  103933. /**
  103934. * Gets the device distance from the ground in meters.
  103935. * @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.
  103936. */
  103937. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  103938. if (this._standingMatrix) {
  103939. // Add standing matrix offset to get real offset from ground in room
  103940. this._standingMatrix.getTranslationToRef(this._workingVector);
  103941. return this._deviceRoomPosition.y + this._workingVector.y;
  103942. }
  103943. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  103944. return this._defaultHeight || 0;
  103945. };
  103946. /**
  103947. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  103948. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  103949. */
  103950. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  103951. var _this = this;
  103952. if (callback === void 0) { callback = function (bool) { }; }
  103953. // Use standing matrix if available
  103954. this.getEngine().initWebVRAsync().then(function (result) {
  103955. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform || !_this.webVROptions.trackPosition) {
  103956. callback(false);
  103957. }
  103958. else {
  103959. _this._standingMatrix = new BABYLON.Matrix();
  103960. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  103961. if (!_this.getScene().useRightHandedSystem) {
  103962. [2, 6, 8, 9, 14].forEach(function (num) {
  103963. if (_this._standingMatrix) {
  103964. _this._standingMatrix.m[num] *= -1;
  103965. }
  103966. });
  103967. }
  103968. callback(true);
  103969. }
  103970. });
  103971. };
  103972. /**
  103973. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  103974. * @returns A promise with a boolean set to if the standing matrix is supported.
  103975. */
  103976. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  103977. var _this = this;
  103978. return new Promise(function (res, rej) {
  103979. _this.useStandingMatrix(function (supported) {
  103980. res(supported);
  103981. });
  103982. });
  103983. };
  103984. /**
  103985. * Disposes the camera
  103986. */
  103987. WebVRFreeCamera.prototype.dispose = function () {
  103988. this._detachIfAttached();
  103989. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  103990. if (this._updateCacheWhenTrackingDisabledObserver) {
  103991. this._scene.onBeforeRenderObservable.remove(this._updateCacheWhenTrackingDisabledObserver);
  103992. }
  103993. _super.prototype.dispose.call(this);
  103994. };
  103995. /**
  103996. * Gets a vrController by name.
  103997. * @param name The name of the controller to retreive
  103998. * @returns the controller matching the name specified or null if not found
  103999. */
  104000. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  104001. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  104002. var gp = _a[_i];
  104003. if (gp.hand === name) {
  104004. return gp;
  104005. }
  104006. }
  104007. return null;
  104008. };
  104009. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  104010. /**
  104011. * The controller corrisponding to the users left hand.
  104012. */
  104013. get: function () {
  104014. if (!this._leftController) {
  104015. this._leftController = this.getControllerByName("left");
  104016. }
  104017. return this._leftController;
  104018. },
  104019. enumerable: true,
  104020. configurable: true
  104021. });
  104022. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  104023. /**
  104024. * The controller corrisponding to the users right hand.
  104025. */
  104026. get: function () {
  104027. if (!this._rightController) {
  104028. this._rightController = this.getControllerByName("right");
  104029. }
  104030. return this._rightController;
  104031. },
  104032. enumerable: true,
  104033. configurable: true
  104034. });
  104035. /**
  104036. * Casts a ray forward from the vrCamera's gaze.
  104037. * @param length Length of the ray (default: 100)
  104038. * @returns the ray corrisponding to the gaze
  104039. */
  104040. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  104041. if (length === void 0) { length = 100; }
  104042. if (this.leftCamera) {
  104043. // Use left eye to avoid computation to compute center on every call
  104044. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  104045. }
  104046. else {
  104047. return _super.prototype.getForwardRay.call(this, length);
  104048. }
  104049. };
  104050. /**
  104051. * @hidden
  104052. * Updates the camera based on device's frame data
  104053. */
  104054. WebVRFreeCamera.prototype._checkInputs = function () {
  104055. if (this._vrDevice && this._vrDevice.isPresenting) {
  104056. this._vrDevice.getFrameData(this._frameData);
  104057. this.updateFromDevice(this._frameData.pose);
  104058. }
  104059. _super.prototype._checkInputs.call(this);
  104060. };
  104061. /**
  104062. * Updates the poseControlled values based on the input device pose.
  104063. * @param poseData Pose coming from the device
  104064. */
  104065. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  104066. if (poseData && poseData.orientation) {
  104067. this.rawPose = poseData;
  104068. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  104069. if (this.getScene().useRightHandedSystem) {
  104070. this._deviceRoomRotationQuaternion.z *= -1;
  104071. this._deviceRoomRotationQuaternion.w *= -1;
  104072. }
  104073. if (this.webVROptions.trackPosition && this.rawPose.position) {
  104074. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  104075. if (this.getScene().useRightHandedSystem) {
  104076. this._deviceRoomPosition.z *= -1;
  104077. }
  104078. }
  104079. this._poseSet = true;
  104080. }
  104081. };
  104082. /**
  104083. * WebVR's attach control will start broadcasting frames to the device.
  104084. * Note that in certain browsers (chrome for example) this function must be called
  104085. * within a user-interaction callback. Example:
  104086. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  104087. *
  104088. * @param element html element to attach the vrDevice to
  104089. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  104090. */
  104091. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  104092. _super.prototype.attachControl.call(this, element, noPreventDefault);
  104093. this._attached = true;
  104094. this._htmlElementAttached = element;
  104095. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  104096. if (this._vrDevice) {
  104097. this.getEngine().enableVR();
  104098. }
  104099. window.addEventListener('vrdisplaypresentchange', this._detachIfAttached);
  104100. };
  104101. /**
  104102. * Detaches the camera from the html element and disables VR
  104103. *
  104104. * @param element html element to detach from
  104105. */
  104106. WebVRFreeCamera.prototype.detachControl = function (element) {
  104107. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  104108. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  104109. _super.prototype.detachControl.call(this, element);
  104110. this._attached = false;
  104111. this.getEngine().disableVR();
  104112. window.removeEventListener('vrdisplaypresentchange', this._detachIfAttached);
  104113. };
  104114. /**
  104115. * @returns the name of this class
  104116. */
  104117. WebVRFreeCamera.prototype.getClassName = function () {
  104118. return "WebVRFreeCamera";
  104119. };
  104120. /**
  104121. * Calls resetPose on the vrDisplay
  104122. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  104123. */
  104124. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  104125. //uses the vrDisplay's "resetPose()".
  104126. //pitch and roll won't be affected.
  104127. this._vrDevice.resetPose();
  104128. };
  104129. /**
  104130. * @hidden
  104131. * Updates the rig cameras (left and right eye)
  104132. */
  104133. WebVRFreeCamera.prototype._updateRigCameras = function () {
  104134. var camLeft = this._rigCameras[0];
  104135. var camRight = this._rigCameras[1];
  104136. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  104137. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  104138. camLeft.position.copyFrom(this._deviceRoomPosition);
  104139. camRight.position.copyFrom(this._deviceRoomPosition);
  104140. };
  104141. // Remove translation from 6dof headset if trackposition is set to false
  104142. WebVRFreeCamera.prototype._correctPositionIfNotTrackPosition = function (matrix, isViewMatrix) {
  104143. if (isViewMatrix === void 0) { isViewMatrix = false; }
  104144. if (this.rawPose && this.rawPose.position && !this.webVROptions.trackPosition) {
  104145. BABYLON.Matrix.TranslationToRef(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2], this._tmpMatrix);
  104146. if (!isViewMatrix) {
  104147. this._tmpMatrix.invert();
  104148. }
  104149. this._tmpMatrix.multiplyToRef(matrix, matrix);
  104150. }
  104151. };
  104152. /**
  104153. * @hidden
  104154. * Updates the cached values of the camera
  104155. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  104156. */
  104157. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  104158. var _this = this;
  104159. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  104160. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  104161. if (!this.updateCacheCalled) {
  104162. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  104163. this.updateCacheCalled = true;
  104164. this.update();
  104165. }
  104166. // Set working vector to the device position in room space rotated by the new rotation
  104167. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  104168. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  104169. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  104170. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  104171. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  104172. // Add translation from anchor position
  104173. this._deviceToWorld.getTranslationToRef(this._workingVector);
  104174. this._workingVector.addInPlace(this.position);
  104175. this._workingVector.subtractInPlace(this._cache.position);
  104176. this._deviceToWorld.setTranslation(this._workingVector);
  104177. // Set an inverted matrix to be used when updating the camera
  104178. this._deviceToWorld.invertToRef(this._worldToDevice);
  104179. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  104180. this.controllers.forEach(function (controller) {
  104181. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  104182. _this._correctPositionIfNotTrackPosition(controller._deviceToWorld);
  104183. controller.update();
  104184. });
  104185. }
  104186. if (!ignoreParentClass) {
  104187. _super.prototype._updateCache.call(this);
  104188. }
  104189. this.updateCacheCalled = false;
  104190. };
  104191. /**
  104192. * @hidden
  104193. * Get current device position in babylon world
  104194. */
  104195. WebVRFreeCamera.prototype._computeDevicePosition = function () {
  104196. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  104197. };
  104198. /**
  104199. * Updates the current device position and rotation in the babylon world
  104200. */
  104201. WebVRFreeCamera.prototype.update = function () {
  104202. this._computeDevicePosition();
  104203. // Get current device rotation in babylon world
  104204. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  104205. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  104206. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  104207. if (this._poseSet) {
  104208. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  104209. }
  104210. _super.prototype.update.call(this);
  104211. };
  104212. /**
  104213. * @hidden
  104214. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  104215. * @returns an identity matrix
  104216. */
  104217. WebVRFreeCamera.prototype._getViewMatrix = function () {
  104218. return BABYLON.Matrix.Identity();
  104219. };
  104220. /**
  104221. * This function is called by the two RIG cameras.
  104222. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  104223. */
  104224. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  104225. var _this = this;
  104226. // Update the parent camera prior to using a child camera to avoid desynchronization
  104227. var parentCamera = this._cameraRigParams["parentCamera"];
  104228. parentCamera._updateCache();
  104229. //WebVR 1.1
  104230. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  104231. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  104232. if (!this.getScene().useRightHandedSystem) {
  104233. [2, 6, 8, 9, 14].forEach(function (num) {
  104234. _this._webvrViewMatrix.m[num] *= -1;
  104235. });
  104236. }
  104237. // update the camera rotation matrix
  104238. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  104239. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  104240. // Computing target and final matrix
  104241. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  104242. // should the view matrix be updated with scale and position offset?
  104243. if (parentCamera.deviceScaleFactor !== 1) {
  104244. this._webvrViewMatrix.invert();
  104245. // scale the position, if set
  104246. if (parentCamera.deviceScaleFactor) {
  104247. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  104248. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  104249. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  104250. }
  104251. this._webvrViewMatrix.invert();
  104252. }
  104253. // Remove translation from 6dof headset if trackposition is set to false
  104254. parentCamera._correctPositionIfNotTrackPosition(this._webvrViewMatrix, true);
  104255. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  104256. // Compute global position
  104257. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  104258. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  104259. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  104260. this._workingMatrix.getTranslationToRef(this._globalPosition);
  104261. this._markSyncedWithParent();
  104262. return this._webvrViewMatrix;
  104263. };
  104264. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  104265. var _this = this;
  104266. var parentCamera = this.parent;
  104267. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  104268. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  104269. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  104270. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  104271. //babylon compatible matrix
  104272. if (!this.getScene().useRightHandedSystem) {
  104273. [8, 9, 10, 11].forEach(function (num) {
  104274. _this._projectionMatrix.m[num] *= -1;
  104275. });
  104276. }
  104277. return this._projectionMatrix;
  104278. };
  104279. /**
  104280. * Initializes the controllers and their meshes
  104281. */
  104282. WebVRFreeCamera.prototype.initControllers = function () {
  104283. var _this = this;
  104284. this.controllers = [];
  104285. var manager = this.getScene().gamepadManager;
  104286. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  104287. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  104288. var webVrController = gamepad;
  104289. if (webVrController.defaultModel) {
  104290. webVrController.defaultModel.setEnabled(false);
  104291. }
  104292. if (webVrController.hand === "right") {
  104293. _this._rightController = null;
  104294. }
  104295. if (webVrController.hand === "left") {
  104296. _this._leftController = null;
  104297. }
  104298. var controllerIndex = _this.controllers.indexOf(webVrController);
  104299. if (controllerIndex !== -1) {
  104300. _this.controllers.splice(controllerIndex, 1);
  104301. }
  104302. }
  104303. });
  104304. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  104305. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  104306. var webVrController_1 = gamepad;
  104307. if (!_this.webVROptions.trackPosition) {
  104308. webVrController_1._disableTrackPosition(new BABYLON.Vector3(webVrController_1.hand == "left" ? -0.15 : 0.15, -0.5, 0.25));
  104309. // Cache must be updated before rendering controllers to avoid them being one frame behind
  104310. if (!_this._updateCacheWhenTrackingDisabledObserver) {
  104311. _this._updateCacheWhenTrackingDisabledObserver = _this._scene.onBeforeRenderObservable.add(function () {
  104312. _this._updateCache();
  104313. });
  104314. }
  104315. }
  104316. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  104317. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  104318. _this._correctPositionIfNotTrackPosition(webVrController_1._deviceToWorld);
  104319. if (_this.webVROptions.controllerMeshes) {
  104320. if (webVrController_1.defaultModel) {
  104321. webVrController_1.defaultModel.setEnabled(true);
  104322. }
  104323. else {
  104324. // Load the meshes
  104325. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  104326. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  104327. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  104328. if (_this.webVROptions.defaultLightingOnControllers) {
  104329. if (!_this._lightOnControllers) {
  104330. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  104331. }
  104332. var activateLightOnSubMeshes_1 = function (mesh, light) {
  104333. var children = mesh.getChildren();
  104334. if (children && children.length !== 0) {
  104335. children.forEach(function (mesh) {
  104336. light.includedOnlyMeshes.push(mesh);
  104337. activateLightOnSubMeshes_1(mesh, light);
  104338. });
  104339. }
  104340. };
  104341. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  104342. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  104343. }
  104344. });
  104345. }
  104346. }
  104347. webVrController_1.attachToPoseControlledCamera(_this);
  104348. // since this is async - sanity check. Is the controller already stored?
  104349. if (_this.controllers.indexOf(webVrController_1) === -1) {
  104350. //add to the controllers array
  104351. _this.controllers.push(webVrController_1);
  104352. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  104353. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  104354. // So we're overriding setting left & right manually to be sure
  104355. var firstViveWandDetected = false;
  104356. for (var i = 0; i < _this.controllers.length; i++) {
  104357. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  104358. if (!firstViveWandDetected) {
  104359. firstViveWandDetected = true;
  104360. _this.controllers[i].hand = "left";
  104361. }
  104362. else {
  104363. _this.controllers[i].hand = "right";
  104364. }
  104365. }
  104366. }
  104367. //did we find enough controllers? Great! let the developer know.
  104368. if (_this.controllers.length >= 2) {
  104369. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  104370. }
  104371. }
  104372. }
  104373. });
  104374. };
  104375. return WebVRFreeCamera;
  104376. }(BABYLON.FreeCamera));
  104377. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  104378. })(BABYLON || (BABYLON = {}));
  104379. //# sourceMappingURL=babylon.webVRCamera.js.map
  104380. var BABYLON;
  104381. (function (BABYLON) {
  104382. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  104383. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  104384. });
  104385. // We're mainly based on the logic defined into the FreeCamera code
  104386. /**
  104387. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  104388. * being tilted forward or back and left or right.
  104389. */
  104390. var DeviceOrientationCamera = /** @class */ (function (_super) {
  104391. __extends(DeviceOrientationCamera, _super);
  104392. /**
  104393. * Creates a new device orientation camera
  104394. * @param name The name of the camera
  104395. * @param position The start position camera
  104396. * @param scene The scene the camera belongs to
  104397. */
  104398. function DeviceOrientationCamera(name, position, scene) {
  104399. var _this = _super.call(this, name, position, scene) || this;
  104400. _this._quaternionCache = new BABYLON.Quaternion();
  104401. _this.inputs.addDeviceOrientation();
  104402. return _this;
  104403. }
  104404. /**
  104405. * Gets the current instance class name ("DeviceOrientationCamera").
  104406. * This helps avoiding instanceof at run time.
  104407. * @returns the class name
  104408. */
  104409. DeviceOrientationCamera.prototype.getClassName = function () {
  104410. return "DeviceOrientationCamera";
  104411. };
  104412. /**
  104413. * @hidden
  104414. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  104415. */
  104416. DeviceOrientationCamera.prototype._checkInputs = function () {
  104417. _super.prototype._checkInputs.call(this);
  104418. this._quaternionCache.copyFrom(this.rotationQuaternion);
  104419. if (this._initialQuaternion) {
  104420. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  104421. }
  104422. };
  104423. /**
  104424. * Reset the camera to its default orientation on the specified axis only.
  104425. * @param axis The axis to reset
  104426. */
  104427. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  104428. var _this = this;
  104429. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  104430. //can only work if this camera has a rotation quaternion already.
  104431. if (!this.rotationQuaternion) {
  104432. return;
  104433. }
  104434. if (!this._initialQuaternion) {
  104435. this._initialQuaternion = new BABYLON.Quaternion();
  104436. }
  104437. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  104438. ['x', 'y', 'z'].forEach(function (axisName) {
  104439. if (!axis[axisName]) {
  104440. _this._initialQuaternion[axisName] = 0;
  104441. }
  104442. else {
  104443. _this._initialQuaternion[axisName] *= -1;
  104444. }
  104445. });
  104446. this._initialQuaternion.normalize();
  104447. //force rotation update
  104448. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  104449. };
  104450. return DeviceOrientationCamera;
  104451. }(BABYLON.FreeCamera));
  104452. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  104453. })(BABYLON || (BABYLON = {}));
  104454. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  104455. var BABYLON;
  104456. (function (BABYLON) {
  104457. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  104458. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  104459. });
  104460. /**
  104461. * Camera used to simulate VR rendering (based on FreeCamera)
  104462. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  104463. */
  104464. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  104465. __extends(VRDeviceOrientationFreeCamera, _super);
  104466. /**
  104467. * Creates a new VRDeviceOrientationFreeCamera
  104468. * @param name defines camera name
  104469. * @param position defines the start position of the camera
  104470. * @param scene defines the scene the camera belongs to
  104471. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  104472. * @param vrCameraMetrics defines the vr metrics associated to the camera
  104473. */
  104474. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  104475. if (compensateDistortion === void 0) { compensateDistortion = true; }
  104476. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  104477. var _this = _super.call(this, name, position, scene) || this;
  104478. vrCameraMetrics.compensateDistortion = compensateDistortion;
  104479. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  104480. return _this;
  104481. }
  104482. /**
  104483. * Gets camera class name
  104484. * @returns VRDeviceOrientationFreeCamera
  104485. */
  104486. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  104487. return "VRDeviceOrientationFreeCamera";
  104488. };
  104489. return VRDeviceOrientationFreeCamera;
  104490. }(BABYLON.DeviceOrientationCamera));
  104491. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  104492. })(BABYLON || (BABYLON = {}));
  104493. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  104494. var BABYLON;
  104495. (function (BABYLON) {
  104496. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  104497. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  104498. });
  104499. /**
  104500. * Camera used to simulate VR rendering (based on ArcRotateCamera)
  104501. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  104502. */
  104503. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  104504. __extends(VRDeviceOrientationArcRotateCamera, _super);
  104505. /**
  104506. * Creates a new VRDeviceOrientationArcRotateCamera
  104507. * @param name defines camera name
  104508. * @param alpha defines the camera rotation along the logitudinal axis
  104509. * @param beta defines the camera rotation along the latitudinal axis
  104510. * @param radius defines the camera distance from its target
  104511. * @param target defines the camera target
  104512. * @param scene defines the scene the camera belongs to
  104513. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  104514. * @param vrCameraMetrics defines the vr metrics associated to the camera
  104515. */
  104516. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  104517. if (compensateDistortion === void 0) { compensateDistortion = true; }
  104518. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  104519. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  104520. vrCameraMetrics.compensateDistortion = compensateDistortion;
  104521. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  104522. _this.inputs.addVRDeviceOrientation();
  104523. return _this;
  104524. }
  104525. /**
  104526. * Gets camera class name
  104527. * @returns VRDeviceOrientationArcRotateCamera
  104528. */
  104529. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  104530. return "VRDeviceOrientationArcRotateCamera";
  104531. };
  104532. return VRDeviceOrientationArcRotateCamera;
  104533. }(BABYLON.ArcRotateCamera));
  104534. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  104535. })(BABYLON || (BABYLON = {}));
  104536. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  104537. var BABYLON;
  104538. (function (BABYLON) {
  104539. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  104540. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  104541. });
  104542. /**
  104543. * Camera used to simulate VR rendering (based on VRDeviceOrientationFreeCamera)
  104544. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  104545. */
  104546. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  104547. __extends(VRDeviceOrientationGamepadCamera, _super);
  104548. /**
  104549. * Creates a new VRDeviceOrientationGamepadCamera
  104550. * @param name defines camera name
  104551. * @param position defines the start position of the camera
  104552. * @param scene defines the scene the camera belongs to
  104553. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  104554. * @param vrCameraMetrics defines the vr metrics associated to the camera
  104555. */
  104556. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  104557. if (compensateDistortion === void 0) { compensateDistortion = true; }
  104558. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  104559. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  104560. _this.inputs.addGamepad();
  104561. return _this;
  104562. }
  104563. /**
  104564. * Gets camera class name
  104565. * @returns VRDeviceOrientationGamepadCamera
  104566. */
  104567. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  104568. return "VRDeviceOrientationGamepadCamera";
  104569. };
  104570. return VRDeviceOrientationGamepadCamera;
  104571. }(BABYLON.VRDeviceOrientationFreeCamera));
  104572. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  104573. })(BABYLON || (BABYLON = {}));
  104574. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  104575. var BABYLON;
  104576. (function (BABYLON) {
  104577. var VRExperienceHelperGazer = /** @class */ (function () {
  104578. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  104579. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  104580. this.scene = scene;
  104581. /** @hidden */
  104582. this._pointerDownOnMeshAsked = false;
  104583. /** @hidden */
  104584. this._isActionableMesh = false;
  104585. /** @hidden */
  104586. this._teleportationRequestInitiated = false;
  104587. /** @hidden */
  104588. this._teleportationBackRequestInitiated = false;
  104589. /** @hidden */
  104590. this._rotationRightAsked = false;
  104591. /** @hidden */
  104592. this._rotationLeftAsked = false;
  104593. /** @hidden */
  104594. this._dpadPressed = true;
  104595. /** @hidden */
  104596. this._activePointer = false;
  104597. this._id = VRExperienceHelperGazer._idCounter++;
  104598. // Gaze tracker
  104599. if (!gazeTrackerToClone) {
  104600. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  104601. this._gazeTracker.bakeCurrentTransformIntoVertices();
  104602. this._gazeTracker.isPickable = false;
  104603. this._gazeTracker.isVisible = false;
  104604. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  104605. targetMat.specularColor = BABYLON.Color3.Black();
  104606. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  104607. targetMat.backFaceCulling = false;
  104608. this._gazeTracker.material = targetMat;
  104609. }
  104610. else {
  104611. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  104612. }
  104613. }
  104614. /** @hidden */
  104615. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  104616. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  104617. };
  104618. /** @hidden */
  104619. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  104620. this._pointerDownOnMeshAsked = true;
  104621. if (this._currentHit) {
  104622. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  104623. }
  104624. };
  104625. /** @hidden */
  104626. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  104627. if (this._currentHit) {
  104628. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  104629. }
  104630. this._pointerDownOnMeshAsked = false;
  104631. };
  104632. /** @hidden */
  104633. VRExperienceHelperGazer.prototype._activatePointer = function () {
  104634. this._activePointer = true;
  104635. };
  104636. /** @hidden */
  104637. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  104638. this._activePointer = false;
  104639. };
  104640. /** @hidden */
  104641. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  104642. if (distance === void 0) { distance = 100; }
  104643. };
  104644. VRExperienceHelperGazer.prototype.dispose = function () {
  104645. this._interactionsEnabled = false;
  104646. this._teleportationEnabled = false;
  104647. if (this._gazeTracker) {
  104648. this._gazeTracker.dispose();
  104649. }
  104650. };
  104651. VRExperienceHelperGazer._idCounter = 0;
  104652. return VRExperienceHelperGazer;
  104653. }());
  104654. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  104655. __extends(VRExperienceHelperControllerGazer, _super);
  104656. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  104657. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  104658. _this.webVRController = webVRController;
  104659. // Laser pointer
  104660. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  104661. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  104662. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  104663. laserPointerMaterial.alpha = 0.6;
  104664. _this._laserPointer.material = laserPointerMaterial;
  104665. _this._laserPointer.rotation.x = Math.PI / 2;
  104666. _this._laserPointer.position.z = -0.5;
  104667. _this._laserPointer.isVisible = false;
  104668. _this._laserPointer.isPickable = false;
  104669. if (!webVRController.mesh) {
  104670. // Create an empty mesh that is used prior to loading the high quality model
  104671. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  104672. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  104673. preloadPointerPose.rotation.x = -0.7;
  104674. preloadMesh.addChild(preloadPointerPose);
  104675. webVRController.attachToMesh(preloadMesh);
  104676. }
  104677. _this._setLaserPointerParent(webVRController.mesh);
  104678. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  104679. _this._setLaserPointerParent(mesh);
  104680. });
  104681. return _this;
  104682. }
  104683. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  104684. return this.webVRController.getForwardRay(length);
  104685. };
  104686. /** @hidden */
  104687. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  104688. _super.prototype._activatePointer.call(this);
  104689. this._laserPointer.isVisible = true;
  104690. };
  104691. /** @hidden */
  104692. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  104693. _super.prototype._deactivatePointer.call(this);
  104694. this._laserPointer.isVisible = false;
  104695. };
  104696. /** @hidden */
  104697. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  104698. this._laserPointer.material.emissiveColor = color;
  104699. };
  104700. /** @hidden */
  104701. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  104702. var makeNotPick = function (root) {
  104703. root.isPickable = false;
  104704. root.getChildMeshes().forEach(function (c) {
  104705. makeNotPick(c);
  104706. });
  104707. };
  104708. makeNotPick(mesh);
  104709. var childMeshes = mesh.getChildMeshes();
  104710. this.webVRController._pointingPoseNode = null;
  104711. for (var i = 0; i < childMeshes.length; i++) {
  104712. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  104713. mesh = childMeshes[i];
  104714. this.webVRController._pointingPoseNode = mesh;
  104715. break;
  104716. }
  104717. }
  104718. this._laserPointer.parent = mesh;
  104719. };
  104720. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  104721. if (distance === void 0) { distance = 100; }
  104722. this._laserPointer.scaling.y = distance;
  104723. this._laserPointer.position.z = -distance / 2;
  104724. };
  104725. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  104726. _super.prototype.dispose.call(this);
  104727. this._laserPointer.dispose();
  104728. if (this._meshAttachedObserver) {
  104729. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  104730. }
  104731. };
  104732. return VRExperienceHelperControllerGazer;
  104733. }(VRExperienceHelperGazer));
  104734. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  104735. __extends(VRExperienceHelperCameraGazer, _super);
  104736. function VRExperienceHelperCameraGazer(getCamera, scene) {
  104737. var _this = _super.call(this, scene) || this;
  104738. _this.getCamera = getCamera;
  104739. return _this;
  104740. }
  104741. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  104742. var camera = this.getCamera();
  104743. if (camera) {
  104744. return camera.getForwardRay(length);
  104745. }
  104746. else {
  104747. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  104748. }
  104749. };
  104750. return VRExperienceHelperCameraGazer;
  104751. }(VRExperienceHelperGazer));
  104752. /**
  104753. * Helps to quickly add VR support to an existing scene.
  104754. * See http://doc.babylonjs.com/how_to/webvr_helper
  104755. */
  104756. var VRExperienceHelper = /** @class */ (function () {
  104757. /**
  104758. * Instantiates a VRExperienceHelper.
  104759. * Helps to quickly add VR support to an existing scene.
  104760. * @param scene The scene the VRExperienceHelper belongs to.
  104761. * @param webVROptions Options to modify the vr experience helper's behavior.
  104762. */
  104763. function VRExperienceHelper(scene,
  104764. /** Options to modify the vr experience helper's behavior. */
  104765. webVROptions) {
  104766. if (webVROptions === void 0) { webVROptions = {}; }
  104767. var _this = this;
  104768. this.webVROptions = webVROptions;
  104769. // Can the system support WebVR, even if a headset isn't plugged in?
  104770. this._webVRsupported = false;
  104771. // If WebVR is supported, is a headset plugged in and are we ready to present?
  104772. this._webVRready = false;
  104773. // Are we waiting for the requestPresent callback to complete?
  104774. this._webVRrequesting = false;
  104775. // Are we presenting to the headset right now? (this is the vrDevice state)
  104776. this._webVRpresenting = false;
  104777. // Are we presenting in the fullscreen fallback?
  104778. this._fullscreenVRpresenting = false;
  104779. /**
  104780. * Observable raised when entering VR.
  104781. */
  104782. this.onEnteringVRObservable = new BABYLON.Observable();
  104783. /**
  104784. * Observable raised when exiting VR.
  104785. */
  104786. this.onExitingVRObservable = new BABYLON.Observable();
  104787. /**
  104788. * Observable raised when controller mesh is loaded.
  104789. */
  104790. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  104791. this._useCustomVRButton = false;
  104792. this._teleportationRequested = false;
  104793. this._teleportActive = false;
  104794. this._floorMeshesCollection = [];
  104795. this._rotationAllowed = true;
  104796. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  104797. this._isDefaultTeleportationTarget = true;
  104798. this._teleportationFillColor = "#444444";
  104799. this._teleportationBorderColor = "#FFFFFF";
  104800. this._rotationAngle = 0;
  104801. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  104802. this._padSensibilityUp = 0.65;
  104803. this._padSensibilityDown = 0.35;
  104804. this._leftController = null;
  104805. this._rightController = null;
  104806. /**
  104807. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  104808. */
  104809. this.onNewMeshSelected = new BABYLON.Observable();
  104810. /**
  104811. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  104812. */
  104813. this.onNewMeshPicked = new BABYLON.Observable();
  104814. /**
  104815. * Observable raised before camera teleportation
  104816. */
  104817. this.onBeforeCameraTeleport = new BABYLON.Observable();
  104818. /**
  104819. * Observable raised after camera teleportation
  104820. */
  104821. this.onAfterCameraTeleport = new BABYLON.Observable();
  104822. /**
  104823. * Observable raised when current selected mesh gets unselected
  104824. */
  104825. this.onSelectedMeshUnselected = new BABYLON.Observable();
  104826. /**
  104827. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  104828. */
  104829. this.teleportationEnabled = true;
  104830. this._teleportationInitialized = false;
  104831. this._interactionsEnabled = false;
  104832. this._interactionsRequested = false;
  104833. this._displayGaze = true;
  104834. this._displayLaserPointer = true;
  104835. /**
  104836. * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes
  104837. */
  104838. this.updateGazeTrackerScale = true;
  104839. this._onResize = function () {
  104840. _this.moveButtonToBottomRight();
  104841. if (_this._fullscreenVRpresenting && _this._webVRready) {
  104842. _this.exitVR();
  104843. }
  104844. };
  104845. this._onFullscreenChange = function () {
  104846. if (document.fullscreen !== undefined) {
  104847. _this._fullscreenVRpresenting = document.fullscreen;
  104848. }
  104849. else if (document.mozFullScreen !== undefined) {
  104850. _this._fullscreenVRpresenting = document.mozFullScreen;
  104851. }
  104852. else if (document.webkitIsFullScreen !== undefined) {
  104853. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  104854. }
  104855. else if (document.msIsFullScreen !== undefined) {
  104856. _this._fullscreenVRpresenting = document.msIsFullScreen;
  104857. }
  104858. else if (document.msFullscreenElement !== undefined) {
  104859. _this._fullscreenVRpresenting = document.msFullscreenElement;
  104860. }
  104861. if (!_this._fullscreenVRpresenting && _this._canvas) {
  104862. _this.exitVR();
  104863. if (!_this._useCustomVRButton) {
  104864. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  104865. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  104866. }
  104867. }
  104868. };
  104869. this.beforeRender = function () {
  104870. if (_this._leftController && _this._leftController._activePointer) {
  104871. _this._castRayAndSelectObject(_this._leftController);
  104872. }
  104873. if (_this._rightController && _this._rightController._activePointer) {
  104874. _this._castRayAndSelectObject(_this._rightController);
  104875. }
  104876. if (_this._noControllerIsActive) {
  104877. _this._castRayAndSelectObject(_this._cameraGazer);
  104878. }
  104879. else {
  104880. _this._cameraGazer._gazeTracker.isVisible = false;
  104881. }
  104882. };
  104883. this._onNewGamepadConnected = function (gamepad) {
  104884. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  104885. if (gamepad.leftStick) {
  104886. gamepad.onleftstickchanged(function (stickValues) {
  104887. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  104888. // Listening to classic/xbox gamepad only if no VR controller is active
  104889. if ((!_this._leftController && !_this._rightController) ||
  104890. ((_this._leftController && !_this._leftController._activePointer) &&
  104891. (_this._rightController && !_this._rightController._activePointer))) {
  104892. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  104893. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  104894. }
  104895. }
  104896. });
  104897. }
  104898. if (gamepad.rightStick) {
  104899. gamepad.onrightstickchanged(function (stickValues) {
  104900. if (_this._teleportationInitialized) {
  104901. _this._checkRotate(stickValues, _this._cameraGazer);
  104902. }
  104903. });
  104904. }
  104905. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  104906. gamepad.onbuttondown(function (buttonPressed) {
  104907. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  104908. _this._cameraGazer._selectionPointerDown();
  104909. }
  104910. });
  104911. gamepad.onbuttonup(function (buttonPressed) {
  104912. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  104913. _this._cameraGazer._selectionPointerUp();
  104914. }
  104915. });
  104916. }
  104917. }
  104918. else {
  104919. var webVRController = gamepad;
  104920. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  104921. if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) {
  104922. _this._rightController = controller;
  104923. }
  104924. else {
  104925. _this._leftController = controller;
  104926. }
  104927. _this._tryEnableInteractionOnController(controller);
  104928. }
  104929. };
  104930. // 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
  104931. this._tryEnableInteractionOnController = function (controller) {
  104932. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  104933. _this._enableInteractionOnController(controller);
  104934. }
  104935. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  104936. _this._enableTeleportationOnController(controller);
  104937. }
  104938. };
  104939. this._onNewGamepadDisconnected = function (gamepad) {
  104940. if (gamepad instanceof BABYLON.WebVRController) {
  104941. if (gamepad.hand === "left" && _this._leftController != null) {
  104942. _this._leftController.dispose();
  104943. _this._leftController = null;
  104944. }
  104945. if (gamepad.hand === "right" && _this._rightController != null) {
  104946. _this._rightController.dispose();
  104947. _this._rightController = null;
  104948. }
  104949. }
  104950. };
  104951. this._workingVector = BABYLON.Vector3.Zero();
  104952. this._workingQuaternion = BABYLON.Quaternion.Identity();
  104953. this._workingMatrix = BABYLON.Matrix.Identity();
  104954. this._scene = scene;
  104955. this._canvas = scene.getEngine().getRenderingCanvas();
  104956. // Parse options
  104957. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  104958. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  104959. }
  104960. if (webVROptions.createDeviceOrientationCamera === undefined) {
  104961. webVROptions.createDeviceOrientationCamera = true;
  104962. }
  104963. if (webVROptions.laserToggle === undefined) {
  104964. webVROptions.laserToggle = true;
  104965. }
  104966. if (webVROptions.defaultHeight === undefined) {
  104967. webVROptions.defaultHeight = 1.7;
  104968. }
  104969. if (webVROptions.useCustomVRButton) {
  104970. this._useCustomVRButton = true;
  104971. if (webVROptions.customVRButton) {
  104972. this._btnVR = webVROptions.customVRButton;
  104973. }
  104974. }
  104975. if (webVROptions.rayLength) {
  104976. this._rayLength = webVROptions.rayLength;
  104977. }
  104978. this._defaultHeight = webVROptions.defaultHeight;
  104979. if (webVROptions.positionScale) {
  104980. this._rayLength *= webVROptions.positionScale;
  104981. this._defaultHeight *= webVROptions.positionScale;
  104982. }
  104983. this._hasEnteredVR = false;
  104984. // Set position
  104985. if (this._scene.activeCamera) {
  104986. this._position = this._scene.activeCamera.position.clone();
  104987. }
  104988. else {
  104989. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  104990. }
  104991. // Set non-vr camera
  104992. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  104993. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  104994. // Copy data from existing camera
  104995. if (this._scene.activeCamera) {
  104996. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  104997. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  104998. // Set rotation from previous camera
  104999. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  105000. var targetCamera = this._scene.activeCamera;
  105001. if (targetCamera.rotationQuaternion) {
  105002. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  105003. }
  105004. else {
  105005. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  105006. }
  105007. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  105008. }
  105009. }
  105010. this._scene.activeCamera = this._deviceOrientationCamera;
  105011. if (this._canvas) {
  105012. this._scene.activeCamera.attachControl(this._canvas);
  105013. }
  105014. }
  105015. else {
  105016. this._existingCamera = this._scene.activeCamera;
  105017. }
  105018. // Create VR cameras
  105019. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  105020. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  105021. }
  105022. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  105023. this._webVRCamera.useStandingMatrix();
  105024. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  105025. // Create default button
  105026. if (!this._useCustomVRButton) {
  105027. this._btnVR = document.createElement("BUTTON");
  105028. this._btnVR.className = "babylonVRicon";
  105029. this._btnVR.id = "babylonVRiconbtn";
  105030. this._btnVR.title = "Click to switch to VR";
  105031. 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) }";
  105032. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  105033. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  105034. // css += ".babylonVRicon.vrdisplaysupported { }";
  105035. // css += ".babylonVRicon.vrdisplayready { }";
  105036. // css += ".babylonVRicon.vrdisplayrequesting { }";
  105037. var style = document.createElement('style');
  105038. style.appendChild(document.createTextNode(css));
  105039. document.getElementsByTagName('head')[0].appendChild(style);
  105040. this.moveButtonToBottomRight();
  105041. }
  105042. // VR button click event
  105043. if (this._btnVR) {
  105044. this._btnVR.addEventListener("click", function () {
  105045. if (!_this.isInVRMode) {
  105046. _this.enterVR();
  105047. }
  105048. else {
  105049. _this.exitVR();
  105050. }
  105051. });
  105052. }
  105053. // Window events
  105054. window.addEventListener("resize", this._onResize);
  105055. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  105056. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  105057. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  105058. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  105059. document.onmsfullscreenchange = this._onFullscreenChange;
  105060. // Display vr button when headset is connected
  105061. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  105062. this.displayVRButton();
  105063. }
  105064. else {
  105065. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  105066. if (e.vrDisplay) {
  105067. _this.displayVRButton();
  105068. }
  105069. });
  105070. }
  105071. // Exiting VR mode using 'ESC' key on desktop
  105072. this._onKeyDown = function (event) {
  105073. if (event.keyCode === 27 && _this.isInVRMode) {
  105074. _this.exitVR();
  105075. }
  105076. };
  105077. document.addEventListener("keydown", this._onKeyDown);
  105078. // Exiting VR mode double tapping the touch screen
  105079. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  105080. if (_this.isInVRMode) {
  105081. _this.exitVR();
  105082. if (_this._fullscreenVRpresenting) {
  105083. _this._scene.getEngine().switchFullscreen(true);
  105084. }
  105085. }
  105086. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  105087. // Listen for WebVR display changes
  105088. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  105089. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  105090. this._onVRRequestPresentStart = function () {
  105091. _this._webVRrequesting = true;
  105092. _this.updateButtonVisibility();
  105093. };
  105094. this._onVRRequestPresentComplete = function (success) {
  105095. _this._webVRrequesting = false;
  105096. _this.updateButtonVisibility();
  105097. };
  105098. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  105099. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  105100. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  105101. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  105102. scene.onDisposeObservable.add(function () {
  105103. _this.dispose();
  105104. });
  105105. // Gamepad connection events
  105106. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  105107. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  105108. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  105109. this.updateButtonVisibility();
  105110. //create easing functions
  105111. this._circleEase = new BABYLON.CircleEase();
  105112. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  105113. if (this.webVROptions.floorMeshes) {
  105114. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  105115. }
  105116. }
  105117. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  105118. /** Return this.onEnteringVRObservable
  105119. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  105120. */
  105121. get: function () {
  105122. return this.onEnteringVRObservable;
  105123. },
  105124. enumerable: true,
  105125. configurable: true
  105126. });
  105127. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  105128. /** Return this.onExitingVRObservable
  105129. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  105130. */
  105131. get: function () {
  105132. return this.onExitingVRObservable;
  105133. },
  105134. enumerable: true,
  105135. configurable: true
  105136. });
  105137. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  105138. /** Return this.onControllerMeshLoadedObservable
  105139. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  105140. */
  105141. get: function () {
  105142. return this.onControllerMeshLoadedObservable;
  105143. },
  105144. enumerable: true,
  105145. configurable: true
  105146. });
  105147. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  105148. /**
  105149. * The mesh used to display where the user is going to teleport.
  105150. */
  105151. get: function () {
  105152. return this._teleportationTarget;
  105153. },
  105154. /**
  105155. * Sets the mesh to be used to display where the user is going to teleport.
  105156. */
  105157. set: function (value) {
  105158. if (value) {
  105159. value.name = "teleportationTarget";
  105160. this._isDefaultTeleportationTarget = false;
  105161. this._teleportationTarget = value;
  105162. }
  105163. },
  105164. enumerable: true,
  105165. configurable: true
  105166. });
  105167. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  105168. /**
  105169. * 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
  105170. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  105171. * See http://doc.babylonjs.com/resources/baking_transformations
  105172. */
  105173. get: function () {
  105174. return this._cameraGazer._gazeTracker;
  105175. },
  105176. set: function (value) {
  105177. if (value) {
  105178. // Dispose of existing meshes
  105179. if (this._cameraGazer._gazeTracker) {
  105180. this._cameraGazer._gazeTracker.dispose();
  105181. }
  105182. if (this._leftController && this._leftController._gazeTracker) {
  105183. this._leftController._gazeTracker.dispose();
  105184. }
  105185. if (this._rightController && this._rightController._gazeTracker) {
  105186. this._rightController._gazeTracker.dispose();
  105187. }
  105188. // Set and create gaze trackers on head and controllers
  105189. this._cameraGazer._gazeTracker = value;
  105190. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  105191. this._cameraGazer._gazeTracker.isPickable = false;
  105192. this._cameraGazer._gazeTracker.isVisible = false;
  105193. this._cameraGazer._gazeTracker.name = "gazeTracker";
  105194. if (this._leftController) {
  105195. this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  105196. }
  105197. if (this._rightController) {
  105198. this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  105199. }
  105200. }
  105201. },
  105202. enumerable: true,
  105203. configurable: true
  105204. });
  105205. Object.defineProperty(VRExperienceHelper.prototype, "leftControllerGazeTrackerMesh", {
  105206. /**
  105207. * The gaze tracking mesh corresponding to the left controller
  105208. */
  105209. get: function () {
  105210. if (this._leftController) {
  105211. return this._leftController._gazeTracker;
  105212. }
  105213. return null;
  105214. },
  105215. enumerable: true,
  105216. configurable: true
  105217. });
  105218. Object.defineProperty(VRExperienceHelper.prototype, "rightControllerGazeTrackerMesh", {
  105219. /**
  105220. * The gaze tracking mesh corresponding to the right controller
  105221. */
  105222. get: function () {
  105223. if (this._rightController) {
  105224. return this._rightController._gazeTracker;
  105225. }
  105226. return null;
  105227. },
  105228. enumerable: true,
  105229. configurable: true
  105230. });
  105231. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  105232. /**
  105233. * If the ray of the gaze should be displayed.
  105234. */
  105235. get: function () {
  105236. return this._displayGaze;
  105237. },
  105238. /**
  105239. * Sets if the ray of the gaze should be displayed.
  105240. */
  105241. set: function (value) {
  105242. this._displayGaze = value;
  105243. if (!value) {
  105244. this._cameraGazer._gazeTracker.isVisible = false;
  105245. if (this._leftController) {
  105246. this._leftController._gazeTracker.isVisible = false;
  105247. }
  105248. if (this._rightController) {
  105249. this._rightController._gazeTracker.isVisible = false;
  105250. }
  105251. }
  105252. },
  105253. enumerable: true,
  105254. configurable: true
  105255. });
  105256. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  105257. /**
  105258. * If the ray of the LaserPointer should be displayed.
  105259. */
  105260. get: function () {
  105261. return this._displayLaserPointer;
  105262. },
  105263. /**
  105264. * Sets if the ray of the LaserPointer should be displayed.
  105265. */
  105266. set: function (value) {
  105267. this._displayLaserPointer = value;
  105268. if (!value) {
  105269. if (this._rightController) {
  105270. this._rightController._deactivatePointer();
  105271. this._rightController._gazeTracker.isVisible = false;
  105272. }
  105273. if (this._leftController) {
  105274. this._leftController._deactivatePointer();
  105275. this._leftController._gazeTracker.isVisible = false;
  105276. }
  105277. }
  105278. else {
  105279. if (this._rightController) {
  105280. this._rightController._activatePointer();
  105281. }
  105282. if (this._leftController) {
  105283. this._leftController._activatePointer();
  105284. }
  105285. }
  105286. },
  105287. enumerable: true,
  105288. configurable: true
  105289. });
  105290. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  105291. /**
  105292. * The deviceOrientationCamera used as the camera when not in VR.
  105293. */
  105294. get: function () {
  105295. return this._deviceOrientationCamera;
  105296. },
  105297. enumerable: true,
  105298. configurable: true
  105299. });
  105300. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  105301. /**
  105302. * Based on the current WebVR support, returns the current VR camera used.
  105303. */
  105304. get: function () {
  105305. if (this._webVRready) {
  105306. return this._webVRCamera;
  105307. }
  105308. else {
  105309. return this._scene.activeCamera;
  105310. }
  105311. },
  105312. enumerable: true,
  105313. configurable: true
  105314. });
  105315. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  105316. /**
  105317. * The webVRCamera which is used when in VR.
  105318. */
  105319. get: function () {
  105320. return this._webVRCamera;
  105321. },
  105322. enumerable: true,
  105323. configurable: true
  105324. });
  105325. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  105326. /**
  105327. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  105328. */
  105329. get: function () {
  105330. return this._vrDeviceOrientationCamera;
  105331. },
  105332. enumerable: true,
  105333. configurable: true
  105334. });
  105335. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  105336. get: function () {
  105337. var result = this._cameraGazer._teleportationRequestInitiated
  105338. || (this._leftController !== null && this._leftController._teleportationRequestInitiated)
  105339. || (this._rightController !== null && this._rightController._teleportationRequestInitiated);
  105340. return result;
  105341. },
  105342. enumerable: true,
  105343. configurable: true
  105344. });
  105345. // Raised when one of the controller has loaded successfully its associated default mesh
  105346. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  105347. if (this._leftController && this._leftController.webVRController == webVRController) {
  105348. if (webVRController.mesh) {
  105349. this._leftController._setLaserPointerParent(webVRController.mesh);
  105350. }
  105351. }
  105352. if (this._rightController && this._rightController.webVRController == webVRController) {
  105353. if (webVRController.mesh) {
  105354. this._rightController._setLaserPointerParent(webVRController.mesh);
  105355. }
  105356. }
  105357. try {
  105358. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  105359. }
  105360. catch (err) {
  105361. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  105362. }
  105363. };
  105364. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  105365. /**
  105366. * Gets a value indicating if we are currently in VR mode.
  105367. */
  105368. get: function () {
  105369. return this._webVRpresenting || this._fullscreenVRpresenting;
  105370. },
  105371. enumerable: true,
  105372. configurable: true
  105373. });
  105374. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  105375. var vrDisplay = this._scene.getEngine().getVRDevice();
  105376. if (vrDisplay) {
  105377. var wasPresenting = this._webVRpresenting;
  105378. this._webVRpresenting = vrDisplay.isPresenting;
  105379. if (wasPresenting && !this._webVRpresenting) {
  105380. this.exitVR();
  105381. }
  105382. }
  105383. else {
  105384. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  105385. }
  105386. this.updateButtonVisibility();
  105387. };
  105388. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  105389. this._webVRsupported = eventArgs.vrSupported;
  105390. this._webVRready = !!eventArgs.vrDisplay;
  105391. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  105392. this.updateButtonVisibility();
  105393. };
  105394. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  105395. if (this._canvas && !this._useCustomVRButton) {
  105396. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  105397. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  105398. }
  105399. };
  105400. VRExperienceHelper.prototype.displayVRButton = function () {
  105401. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  105402. document.body.appendChild(this._btnVR);
  105403. this._btnVRDisplayed = true;
  105404. }
  105405. };
  105406. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  105407. if (!this._btnVR || this._useCustomVRButton) {
  105408. return;
  105409. }
  105410. this._btnVR.className = "babylonVRicon";
  105411. if (this.isInVRMode) {
  105412. this._btnVR.className += " vrdisplaypresenting";
  105413. }
  105414. else {
  105415. if (this._webVRready) {
  105416. this._btnVR.className += " vrdisplayready";
  105417. }
  105418. if (this._webVRsupported) {
  105419. this._btnVR.className += " vrdisplaysupported";
  105420. }
  105421. if (this._webVRrequesting) {
  105422. this._btnVR.className += " vrdisplayrequesting";
  105423. }
  105424. }
  105425. };
  105426. /**
  105427. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  105428. * Otherwise, will use the fullscreen API.
  105429. */
  105430. VRExperienceHelper.prototype.enterVR = function () {
  105431. if (this.onEnteringVRObservable) {
  105432. try {
  105433. this.onEnteringVRObservable.notifyObservers(this);
  105434. }
  105435. catch (err) {
  105436. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  105437. }
  105438. }
  105439. if (this._scene.activeCamera) {
  105440. this._position = this._scene.activeCamera.position.clone();
  105441. // make sure that we return to the last active camera
  105442. this._existingCamera = this._scene.activeCamera;
  105443. }
  105444. if (this._webVRrequesting) {
  105445. return;
  105446. }
  105447. // If WebVR is supported and a headset is connected
  105448. if (this._webVRready) {
  105449. if (!this._webVRpresenting) {
  105450. this._webVRCamera.position = this._position;
  105451. this._scene.activeCamera = this._webVRCamera;
  105452. }
  105453. }
  105454. else if (this._vrDeviceOrientationCamera) {
  105455. this._vrDeviceOrientationCamera.position = this._position;
  105456. if (this._scene.activeCamera) {
  105457. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  105458. }
  105459. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  105460. this._scene.getEngine().switchFullscreen(true);
  105461. this.updateButtonVisibility();
  105462. }
  105463. if (this._scene.activeCamera && this._canvas) {
  105464. this._scene.activeCamera.attachControl(this._canvas);
  105465. }
  105466. if (this._interactionsEnabled) {
  105467. this._scene.registerBeforeRender(this.beforeRender);
  105468. }
  105469. this._hasEnteredVR = true;
  105470. };
  105471. /**
  105472. * Attempt to exit VR, or fullscreen.
  105473. */
  105474. VRExperienceHelper.prototype.exitVR = function () {
  105475. if (this._hasEnteredVR) {
  105476. if (this.onExitingVRObservable) {
  105477. try {
  105478. this.onExitingVRObservable.notifyObservers(this);
  105479. }
  105480. catch (err) {
  105481. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  105482. }
  105483. }
  105484. if (this._webVRpresenting) {
  105485. this._scene.getEngine().disableVR();
  105486. }
  105487. if (this._scene.activeCamera) {
  105488. this._position = this._scene.activeCamera.position.clone();
  105489. }
  105490. if (this._deviceOrientationCamera) {
  105491. this._deviceOrientationCamera.position = this._position;
  105492. this._scene.activeCamera = this._deviceOrientationCamera;
  105493. if (this._canvas) {
  105494. this._scene.activeCamera.attachControl(this._canvas);
  105495. }
  105496. }
  105497. else if (this._existingCamera) {
  105498. this._existingCamera.position = this._position;
  105499. this._scene.activeCamera = this._existingCamera;
  105500. }
  105501. this.updateButtonVisibility();
  105502. if (this._interactionsEnabled) {
  105503. this._scene.unregisterBeforeRender(this.beforeRender);
  105504. this._cameraGazer._gazeTracker.isVisible = false;
  105505. if (this._leftController) {
  105506. this._leftController._gazeTracker.isVisible = false;
  105507. }
  105508. if (this._rightController) {
  105509. this._rightController._gazeTracker.isVisible = false;
  105510. }
  105511. }
  105512. // resize to update width and height when exiting vr exits fullscreen
  105513. this._scene.getEngine().resize();
  105514. this._hasEnteredVR = false;
  105515. }
  105516. };
  105517. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  105518. /**
  105519. * The position of the vr experience helper.
  105520. */
  105521. get: function () {
  105522. return this._position;
  105523. },
  105524. /**
  105525. * Sets the position of the vr experience helper.
  105526. */
  105527. set: function (value) {
  105528. this._position = value;
  105529. if (this._scene.activeCamera) {
  105530. this._scene.activeCamera.position = value;
  105531. }
  105532. },
  105533. enumerable: true,
  105534. configurable: true
  105535. });
  105536. /**
  105537. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  105538. */
  105539. VRExperienceHelper.prototype.enableInteractions = function () {
  105540. var _this = this;
  105541. if (!this._interactionsEnabled) {
  105542. this._interactionsRequested = true;
  105543. if (this._leftController) {
  105544. this._enableInteractionOnController(this._leftController);
  105545. }
  105546. if (this._rightController) {
  105547. this._enableInteractionOnController(this._rightController);
  105548. }
  105549. this.raySelectionPredicate = function (mesh) {
  105550. return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName);
  105551. };
  105552. this.meshSelectionPredicate = function (mesh) {
  105553. return true;
  105554. };
  105555. this._raySelectionPredicate = function (mesh) {
  105556. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  105557. && mesh.name.indexOf("teleportationTarget") === -1
  105558. && mesh.name.indexOf("torusTeleportation") === -1)) {
  105559. return _this.raySelectionPredicate(mesh);
  105560. }
  105561. return false;
  105562. };
  105563. this._interactionsEnabled = true;
  105564. }
  105565. };
  105566. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  105567. get: function () {
  105568. return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer);
  105569. },
  105570. enumerable: true,
  105571. configurable: true
  105572. });
  105573. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  105574. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  105575. if (this._floorMeshesCollection[i].id === mesh.id) {
  105576. return true;
  105577. }
  105578. }
  105579. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  105580. return true;
  105581. }
  105582. return false;
  105583. };
  105584. /**
  105585. * Adds a floor mesh to be used for teleportation.
  105586. * @param floorMesh the mesh to be used for teleportation.
  105587. */
  105588. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  105589. if (!this._floorMeshesCollection) {
  105590. return;
  105591. }
  105592. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  105593. return;
  105594. }
  105595. this._floorMeshesCollection.push(floorMesh);
  105596. };
  105597. /**
  105598. * Removes a floor mesh from being used for teleportation.
  105599. * @param floorMesh the mesh to be removed.
  105600. */
  105601. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  105602. if (!this._floorMeshesCollection) {
  105603. return;
  105604. }
  105605. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  105606. if (meshIndex !== -1) {
  105607. this._floorMeshesCollection.splice(meshIndex, 1);
  105608. }
  105609. };
  105610. /**
  105611. * Enables interactions and teleportation using the VR controllers and gaze.
  105612. * @param vrTeleportationOptions options to modify teleportation behavior.
  105613. */
  105614. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  105615. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  105616. if (!this._teleportationInitialized) {
  105617. this._teleportationRequested = true;
  105618. this.enableInteractions();
  105619. if (vrTeleportationOptions.floorMeshName) {
  105620. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  105621. }
  105622. if (vrTeleportationOptions.floorMeshes) {
  105623. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  105624. }
  105625. if (this._leftController != null) {
  105626. this._enableTeleportationOnController(this._leftController);
  105627. }
  105628. if (this._rightController != null) {
  105629. this._enableTeleportationOnController(this._rightController);
  105630. }
  105631. // Creates an image processing post process for the vignette not relying
  105632. // on the main scene configuration for image processing to reduce setup and spaces
  105633. // (gamma/linear) conflicts.
  105634. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  105635. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  105636. imageProcessingConfiguration.vignetteEnabled = true;
  105637. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  105638. this._webVRCamera.detachPostProcess(this._postProcessMove);
  105639. this._teleportationInitialized = true;
  105640. if (this._isDefaultTeleportationTarget) {
  105641. this._createTeleportationCircles();
  105642. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  105643. }
  105644. }
  105645. };
  105646. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  105647. var _this = this;
  105648. var controllerMesh = controller.webVRController.mesh;
  105649. if (controllerMesh) {
  105650. controller._interactionsEnabled = true;
  105651. controller._activatePointer();
  105652. if (this.webVROptions.laserToggle) {
  105653. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  105654. // Enabling / disabling laserPointer
  105655. if (_this._displayLaserPointer && stateObject.value === 1) {
  105656. if (controller._activePointer) {
  105657. controller._deactivatePointer();
  105658. }
  105659. else {
  105660. controller._activatePointer();
  105661. }
  105662. if (_this.displayGaze) {
  105663. controller._gazeTracker.isVisible = controller._activePointer;
  105664. }
  105665. }
  105666. });
  105667. }
  105668. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  105669. var gazer = controller;
  105670. if (_this._noControllerIsActive) {
  105671. gazer = _this._cameraGazer;
  105672. }
  105673. if (!gazer._pointerDownOnMeshAsked) {
  105674. if (stateObject.value > _this._padSensibilityUp) {
  105675. gazer._selectionPointerDown();
  105676. }
  105677. }
  105678. else if (stateObject.value < _this._padSensibilityDown) {
  105679. gazer._selectionPointerUp();
  105680. }
  105681. });
  105682. }
  105683. };
  105684. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  105685. // Dont teleport if another gaze already requested teleportation
  105686. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  105687. return;
  105688. }
  105689. if (!gazer._teleportationRequestInitiated) {
  105690. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  105691. gazer._activatePointer();
  105692. gazer._teleportationRequestInitiated = true;
  105693. }
  105694. }
  105695. else {
  105696. // Listening to the proper controller values changes to confirm teleportation
  105697. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  105698. if (this._teleportActive) {
  105699. this.teleportCamera(this._haloCenter);
  105700. }
  105701. gazer._teleportationRequestInitiated = false;
  105702. }
  105703. }
  105704. };
  105705. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  105706. // Only rotate when user is not currently selecting a teleportation location
  105707. if (gazer._teleportationRequestInitiated) {
  105708. return;
  105709. }
  105710. if (!gazer._rotationLeftAsked) {
  105711. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  105712. gazer._rotationLeftAsked = true;
  105713. if (this._rotationAllowed) {
  105714. this._rotateCamera(false);
  105715. }
  105716. }
  105717. }
  105718. else {
  105719. if (stateObject.x > -this._padSensibilityDown) {
  105720. gazer._rotationLeftAsked = false;
  105721. }
  105722. }
  105723. if (!gazer._rotationRightAsked) {
  105724. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  105725. gazer._rotationRightAsked = true;
  105726. if (this._rotationAllowed) {
  105727. this._rotateCamera(true);
  105728. }
  105729. }
  105730. }
  105731. else {
  105732. if (stateObject.x < this._padSensibilityDown) {
  105733. gazer._rotationRightAsked = false;
  105734. }
  105735. }
  105736. };
  105737. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  105738. // Only teleport backwards when user is not currently selecting a teleportation location
  105739. if (gazer._teleportationRequestInitiated) {
  105740. return;
  105741. }
  105742. // Teleport backwards
  105743. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  105744. if (!gazer._teleportationBackRequestInitiated) {
  105745. if (!this.currentVRCamera) {
  105746. return;
  105747. }
  105748. // Get rotation and position of the current camera
  105749. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  105750. var position = this.currentVRCamera.position;
  105751. // If the camera has device position, use that instead
  105752. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  105753. rotation = this.currentVRCamera.deviceRotationQuaternion;
  105754. position = this.currentVRCamera.devicePosition;
  105755. }
  105756. // Get matrix with only the y rotation of the device rotation
  105757. rotation.toEulerAnglesToRef(this._workingVector);
  105758. this._workingVector.z = 0;
  105759. this._workingVector.x = 0;
  105760. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  105761. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  105762. // Rotate backwards ray by device rotation to cast at the ground behind the user
  105763. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  105764. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  105765. var ray = new BABYLON.Ray(position, this._workingVector);
  105766. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  105767. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  105768. this.teleportCamera(hit.pickedPoint);
  105769. }
  105770. gazer._teleportationBackRequestInitiated = true;
  105771. }
  105772. }
  105773. else {
  105774. gazer._teleportationBackRequestInitiated = false;
  105775. }
  105776. };
  105777. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  105778. var _this = this;
  105779. var controllerMesh = controller.webVRController.mesh;
  105780. if (controllerMesh) {
  105781. if (!controller._interactionsEnabled) {
  105782. this._enableInteractionOnController(controller);
  105783. }
  105784. controller._interactionsEnabled = true;
  105785. controller._teleportationEnabled = true;
  105786. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  105787. controller._dpadPressed = false;
  105788. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  105789. controller._dpadPressed = stateObject.pressed;
  105790. if (!controller._dpadPressed) {
  105791. controller._rotationLeftAsked = false;
  105792. controller._rotationRightAsked = false;
  105793. controller._teleportationBackRequestInitiated = false;
  105794. }
  105795. });
  105796. }
  105797. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  105798. if (_this.teleportationEnabled) {
  105799. _this._checkTeleportBackwards(stateObject, controller);
  105800. _this._checkTeleportWithRay(stateObject, controller);
  105801. }
  105802. _this._checkRotate(stateObject, controller);
  105803. });
  105804. }
  105805. };
  105806. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  105807. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  105808. this._teleportationTarget.isPickable = false;
  105809. var length = 512;
  105810. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  105811. dynamicTexture.hasAlpha = true;
  105812. var context = dynamicTexture.getContext();
  105813. var centerX = length / 2;
  105814. var centerY = length / 2;
  105815. var radius = 200;
  105816. context.beginPath();
  105817. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  105818. context.fillStyle = this._teleportationFillColor;
  105819. context.fill();
  105820. context.lineWidth = 10;
  105821. context.strokeStyle = this._teleportationBorderColor;
  105822. context.stroke();
  105823. context.closePath();
  105824. dynamicTexture.update();
  105825. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  105826. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  105827. this._teleportationTarget.material = teleportationCircleMaterial;
  105828. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  105829. torus.isPickable = false;
  105830. torus.parent = this._teleportationTarget;
  105831. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  105832. var keys = [];
  105833. keys.push({
  105834. frame: 0,
  105835. value: 0
  105836. });
  105837. keys.push({
  105838. frame: 30,
  105839. value: 0.4
  105840. });
  105841. keys.push({
  105842. frame: 60,
  105843. value: 0
  105844. });
  105845. animationInnerCircle.setKeys(keys);
  105846. var easingFunction = new BABYLON.SineEase();
  105847. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  105848. animationInnerCircle.setEasingFunction(easingFunction);
  105849. torus.animations = [];
  105850. torus.animations.push(animationInnerCircle);
  105851. this._scene.beginAnimation(torus, 0, 60, true);
  105852. this._hideTeleportationTarget();
  105853. };
  105854. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  105855. this._teleportActive = true;
  105856. if (this._teleportationInitialized) {
  105857. this._teleportationTarget.isVisible = true;
  105858. if (this._isDefaultTeleportationTarget) {
  105859. this._teleportationTarget.getChildren()[0].isVisible = true;
  105860. }
  105861. }
  105862. };
  105863. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  105864. this._teleportActive = false;
  105865. if (this._teleportationInitialized) {
  105866. this._teleportationTarget.isVisible = false;
  105867. if (this._isDefaultTeleportationTarget) {
  105868. this._teleportationTarget.getChildren()[0].isVisible = false;
  105869. }
  105870. }
  105871. };
  105872. VRExperienceHelper.prototype._rotateCamera = function (right) {
  105873. var _this = this;
  105874. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  105875. return;
  105876. }
  105877. if (right) {
  105878. this._rotationAngle++;
  105879. }
  105880. else {
  105881. this._rotationAngle--;
  105882. }
  105883. this.currentVRCamera.animations = [];
  105884. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  105885. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  105886. var animationRotationKeys = [];
  105887. animationRotationKeys.push({
  105888. frame: 0,
  105889. value: this.currentVRCamera.rotationQuaternion
  105890. });
  105891. animationRotationKeys.push({
  105892. frame: 6,
  105893. value: target
  105894. });
  105895. animationRotation.setKeys(animationRotationKeys);
  105896. animationRotation.setEasingFunction(this._circleEase);
  105897. this.currentVRCamera.animations.push(animationRotation);
  105898. this._postProcessMove.animations = [];
  105899. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  105900. var vignetteWeightKeys = [];
  105901. vignetteWeightKeys.push({
  105902. frame: 0,
  105903. value: 0
  105904. });
  105905. vignetteWeightKeys.push({
  105906. frame: 3,
  105907. value: 4
  105908. });
  105909. vignetteWeightKeys.push({
  105910. frame: 6,
  105911. value: 0
  105912. });
  105913. animationPP.setKeys(vignetteWeightKeys);
  105914. animationPP.setEasingFunction(this._circleEase);
  105915. this._postProcessMove.animations.push(animationPP);
  105916. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  105917. var vignetteStretchKeys = [];
  105918. vignetteStretchKeys.push({
  105919. frame: 0,
  105920. value: 0
  105921. });
  105922. vignetteStretchKeys.push({
  105923. frame: 3,
  105924. value: 10
  105925. });
  105926. vignetteStretchKeys.push({
  105927. frame: 6,
  105928. value: 0
  105929. });
  105930. animationPP2.setKeys(vignetteStretchKeys);
  105931. animationPP2.setEasingFunction(this._circleEase);
  105932. this._postProcessMove.animations.push(animationPP2);
  105933. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  105934. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  105935. this._postProcessMove.samples = 4;
  105936. this._webVRCamera.attachPostProcess(this._postProcessMove);
  105937. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  105938. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  105939. });
  105940. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  105941. };
  105942. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  105943. if (hit.pickedPoint) {
  105944. if (gazer._teleportationRequestInitiated) {
  105945. this._displayTeleportationTarget();
  105946. this._haloCenter.copyFrom(hit.pickedPoint);
  105947. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  105948. }
  105949. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  105950. if (pickNormal) {
  105951. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  105952. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  105953. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  105954. }
  105955. this._teleportationTarget.position.y += 0.1;
  105956. }
  105957. };
  105958. /**
  105959. * Teleports the users feet to the desired location
  105960. * @param location The location where the user's feet should be placed
  105961. */
  105962. VRExperienceHelper.prototype.teleportCamera = function (location) {
  105963. var _this = this;
  105964. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  105965. return;
  105966. }
  105967. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  105968. // offset of the headset from the anchor.
  105969. if (this.webVRCamera.leftCamera) {
  105970. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  105971. this._workingVector.subtractInPlace(this.webVRCamera.position);
  105972. location.subtractToRef(this._workingVector, this._workingVector);
  105973. }
  105974. else {
  105975. this._workingVector.copyFrom(location);
  105976. }
  105977. // Add height to account for user's height offset
  105978. if (this.isInVRMode) {
  105979. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  105980. }
  105981. else {
  105982. this._workingVector.y += this._defaultHeight;
  105983. }
  105984. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  105985. // Create animation from the camera's position to the new location
  105986. this.currentVRCamera.animations = [];
  105987. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  105988. var animationCameraTeleportationKeys = [{
  105989. frame: 0,
  105990. value: this.currentVRCamera.position
  105991. },
  105992. {
  105993. frame: 11,
  105994. value: this._workingVector
  105995. }
  105996. ];
  105997. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  105998. animationCameraTeleportation.setEasingFunction(this._circleEase);
  105999. this.currentVRCamera.animations.push(animationCameraTeleportation);
  106000. this._postProcessMove.animations = [];
  106001. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  106002. var vignetteWeightKeys = [];
  106003. vignetteWeightKeys.push({
  106004. frame: 0,
  106005. value: 0
  106006. });
  106007. vignetteWeightKeys.push({
  106008. frame: 5,
  106009. value: 8
  106010. });
  106011. vignetteWeightKeys.push({
  106012. frame: 11,
  106013. value: 0
  106014. });
  106015. animationPP.setKeys(vignetteWeightKeys);
  106016. this._postProcessMove.animations.push(animationPP);
  106017. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  106018. var vignetteStretchKeys = [];
  106019. vignetteStretchKeys.push({
  106020. frame: 0,
  106021. value: 0
  106022. });
  106023. vignetteStretchKeys.push({
  106024. frame: 5,
  106025. value: 10
  106026. });
  106027. vignetteStretchKeys.push({
  106028. frame: 11,
  106029. value: 0
  106030. });
  106031. animationPP2.setKeys(vignetteStretchKeys);
  106032. this._postProcessMove.animations.push(animationPP2);
  106033. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  106034. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  106035. this._webVRCamera.attachPostProcess(this._postProcessMove);
  106036. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  106037. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  106038. });
  106039. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  106040. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  106041. });
  106042. this._hideTeleportationTarget();
  106043. };
  106044. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  106045. if (normal) {
  106046. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  106047. if (angle < Math.PI / 2) {
  106048. normal.scaleInPlace(-1);
  106049. }
  106050. }
  106051. return normal;
  106052. };
  106053. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  106054. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  106055. return;
  106056. }
  106057. var ray = gazer._getForwardRay(this._rayLength);
  106058. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  106059. if (hit) {
  106060. // Populate the contrllers mesh that can be used for drag/drop
  106061. if (gazer._laserPointer) {
  106062. hit.originMesh = gazer._laserPointer.parent;
  106063. }
  106064. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  106065. }
  106066. gazer._currentHit = hit;
  106067. // Moving the gazeTracker on the mesh face targetted
  106068. if (hit && hit.pickedPoint) {
  106069. if (this._displayGaze) {
  106070. var multiplier = 1;
  106071. gazer._gazeTracker.isVisible = true;
  106072. if (gazer._isActionableMesh) {
  106073. multiplier = 3;
  106074. }
  106075. if (this.updateGazeTrackerScale) {
  106076. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  106077. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  106078. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  106079. }
  106080. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  106081. // To avoid z-fighting
  106082. var deltaFighting = 0.002;
  106083. if (pickNormal) {
  106084. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  106085. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  106086. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  106087. }
  106088. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  106089. if (gazer._gazeTracker.position.x < 0) {
  106090. gazer._gazeTracker.position.x += deltaFighting;
  106091. }
  106092. else {
  106093. gazer._gazeTracker.position.x -= deltaFighting;
  106094. }
  106095. if (gazer._gazeTracker.position.y < 0) {
  106096. gazer._gazeTracker.position.y += deltaFighting;
  106097. }
  106098. else {
  106099. gazer._gazeTracker.position.y -= deltaFighting;
  106100. }
  106101. if (gazer._gazeTracker.position.z < 0) {
  106102. gazer._gazeTracker.position.z += deltaFighting;
  106103. }
  106104. else {
  106105. gazer._gazeTracker.position.z -= deltaFighting;
  106106. }
  106107. }
  106108. // Changing the size of the laser pointer based on the distance from the targetted point
  106109. gazer._updatePointerDistance(hit.distance);
  106110. }
  106111. else {
  106112. gazer._updatePointerDistance();
  106113. gazer._gazeTracker.isVisible = false;
  106114. }
  106115. if (hit && hit.pickedMesh) {
  106116. // The object selected is the floor, we're in a teleportation scenario
  106117. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  106118. // Moving the teleportation area to this targetted point
  106119. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  106120. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  106121. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  106122. }
  106123. gazer._currentMeshSelected = null;
  106124. if (gazer._teleportationRequestInitiated) {
  106125. this._moveTeleportationSelectorTo(hit, gazer, ray);
  106126. }
  106127. return;
  106128. }
  106129. // If not, we're in a selection scenario
  106130. //this._teleportationAllowed = false;
  106131. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  106132. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  106133. this.onNewMeshPicked.notifyObservers(hit);
  106134. gazer._currentMeshSelected = hit.pickedMesh;
  106135. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  106136. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  106137. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  106138. gazer._isActionableMesh = true;
  106139. }
  106140. else {
  106141. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  106142. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  106143. gazer._isActionableMesh = false;
  106144. }
  106145. try {
  106146. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  106147. }
  106148. catch (err) {
  106149. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  106150. }
  106151. }
  106152. else {
  106153. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  106154. gazer._currentMeshSelected = null;
  106155. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  106156. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  106157. }
  106158. }
  106159. }
  106160. else {
  106161. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  106162. gazer._currentMeshSelected = null;
  106163. //this._teleportationAllowed = false;
  106164. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  106165. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  106166. }
  106167. };
  106168. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  106169. if (mesh) {
  106170. this.onSelectedMeshUnselected.notifyObservers(mesh);
  106171. }
  106172. };
  106173. /**
  106174. * Sets the color of the laser ray from the vr controllers.
  106175. * @param color new color for the ray.
  106176. */
  106177. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  106178. if (this._leftController) {
  106179. this._leftController._setLaserPointerColor(color);
  106180. }
  106181. if (this._rightController) {
  106182. this._rightController._setLaserPointerColor(color);
  106183. }
  106184. };
  106185. /**
  106186. * Sets the color of the ray from the vr headsets gaze.
  106187. * @param color new color for the ray.
  106188. */
  106189. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  106190. if (!this._cameraGazer._gazeTracker.material) {
  106191. return;
  106192. }
  106193. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  106194. if (this._leftController) {
  106195. this._leftController._gazeTracker.material.emissiveColor = color;
  106196. }
  106197. if (this._rightController) {
  106198. this._rightController._gazeTracker.material.emissiveColor = color;
  106199. }
  106200. };
  106201. /**
  106202. * Exits VR and disposes of the vr experience helper
  106203. */
  106204. VRExperienceHelper.prototype.dispose = function () {
  106205. if (this.isInVRMode) {
  106206. this.exitVR();
  106207. }
  106208. if (this._postProcessMove) {
  106209. this._postProcessMove.dispose();
  106210. }
  106211. if (this._webVRCamera) {
  106212. this._webVRCamera.dispose();
  106213. }
  106214. if (this._vrDeviceOrientationCamera) {
  106215. this._vrDeviceOrientationCamera.dispose();
  106216. }
  106217. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  106218. document.body.removeChild(this._btnVR);
  106219. }
  106220. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  106221. this._deviceOrientationCamera.dispose();
  106222. }
  106223. if (this._cameraGazer) {
  106224. this._cameraGazer.dispose();
  106225. }
  106226. if (this._leftController) {
  106227. this._leftController.dispose();
  106228. }
  106229. if (this._rightController) {
  106230. this._rightController.dispose();
  106231. }
  106232. if (this._teleportationTarget) {
  106233. this._teleportationTarget.dispose();
  106234. }
  106235. this._floorMeshesCollection = [];
  106236. document.removeEventListener("keydown", this._onKeyDown);
  106237. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  106238. window.removeEventListener("resize", this._onResize);
  106239. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  106240. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  106241. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  106242. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  106243. document.onmsfullscreenchange = null;
  106244. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  106245. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  106246. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  106247. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  106248. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  106249. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  106250. this._scene.unregisterBeforeRender(this.beforeRender);
  106251. };
  106252. /**
  106253. * Gets the name of the VRExperienceHelper class
  106254. * @returns "VRExperienceHelper"
  106255. */
  106256. VRExperienceHelper.prototype.getClassName = function () {
  106257. return "VRExperienceHelper";
  106258. };
  106259. return VRExperienceHelper;
  106260. }());
  106261. BABYLON.VRExperienceHelper = VRExperienceHelper;
  106262. })(BABYLON || (BABYLON = {}));
  106263. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  106264. // Mainly based on these 2 articles :
  106265. // 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
  106266. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  106267. var BABYLON;
  106268. (function (BABYLON) {
  106269. /**
  106270. * Defines the potential axis of a Joystick
  106271. */
  106272. var JoystickAxis;
  106273. (function (JoystickAxis) {
  106274. /** X axis */
  106275. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  106276. /** Y axis */
  106277. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  106278. /** Z axis */
  106279. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  106280. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  106281. /**
  106282. * Class used to define virtual joystick (used in touch mode)
  106283. */
  106284. var VirtualJoystick = /** @class */ (function () {
  106285. /**
  106286. * Creates a new virtual joystick
  106287. * @param leftJoystick defines that the joystick is for left hand (false by default)
  106288. */
  106289. function VirtualJoystick(leftJoystick) {
  106290. var _this = this;
  106291. if (leftJoystick) {
  106292. this._leftJoystick = true;
  106293. }
  106294. else {
  106295. this._leftJoystick = false;
  106296. }
  106297. VirtualJoystick._globalJoystickIndex++;
  106298. // By default left & right arrow keys are moving the X
  106299. // and up & down keys are moving the Y
  106300. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  106301. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  106302. this.reverseLeftRight = false;
  106303. this.reverseUpDown = false;
  106304. // collections of pointers
  106305. this._touches = new BABYLON.StringDictionary();
  106306. this.deltaPosition = BABYLON.Vector3.Zero();
  106307. this._joystickSensibility = 25;
  106308. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  106309. this._onResize = function (evt) {
  106310. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  106311. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  106312. if (VirtualJoystick.vjCanvas) {
  106313. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  106314. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  106315. }
  106316. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  106317. };
  106318. // injecting a canvas element on top of the canvas 3D game
  106319. if (!VirtualJoystick.vjCanvas) {
  106320. window.addEventListener("resize", this._onResize, false);
  106321. VirtualJoystick.vjCanvas = document.createElement("canvas");
  106322. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  106323. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  106324. VirtualJoystick.vjCanvas.width = window.innerWidth;
  106325. VirtualJoystick.vjCanvas.height = window.innerHeight;
  106326. VirtualJoystick.vjCanvas.style.width = "100%";
  106327. VirtualJoystick.vjCanvas.style.height = "100%";
  106328. VirtualJoystick.vjCanvas.style.position = "absolute";
  106329. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  106330. VirtualJoystick.vjCanvas.style.top = "0px";
  106331. VirtualJoystick.vjCanvas.style.left = "0px";
  106332. VirtualJoystick.vjCanvas.style.zIndex = "5";
  106333. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  106334. // Support for jQuery PEP polyfill
  106335. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  106336. var context = VirtualJoystick.vjCanvas.getContext('2d');
  106337. if (!context) {
  106338. throw new Error("Unable to create canvas for virtual joystick");
  106339. }
  106340. VirtualJoystick.vjCanvasContext = context;
  106341. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  106342. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  106343. document.body.appendChild(VirtualJoystick.vjCanvas);
  106344. }
  106345. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  106346. this.pressed = false;
  106347. // default joystick color
  106348. this._joystickColor = "cyan";
  106349. this._joystickPointerID = -1;
  106350. // current joystick position
  106351. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  106352. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  106353. // origin joystick position
  106354. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  106355. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  106356. this._onPointerDownHandlerRef = function (evt) {
  106357. _this._onPointerDown(evt);
  106358. };
  106359. this._onPointerMoveHandlerRef = function (evt) {
  106360. _this._onPointerMove(evt);
  106361. };
  106362. this._onPointerUpHandlerRef = function (evt) {
  106363. _this._onPointerUp(evt);
  106364. };
  106365. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  106366. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  106367. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  106368. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  106369. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  106370. evt.preventDefault(); // Disables system menu
  106371. }, false);
  106372. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  106373. }
  106374. /**
  106375. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  106376. * @param newJoystickSensibility defines the new sensibility
  106377. */
  106378. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  106379. this._joystickSensibility = newJoystickSensibility;
  106380. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  106381. };
  106382. VirtualJoystick.prototype._onPointerDown = function (e) {
  106383. var positionOnScreenCondition;
  106384. e.preventDefault();
  106385. if (this._leftJoystick === true) {
  106386. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  106387. }
  106388. else {
  106389. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  106390. }
  106391. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  106392. // First contact will be dedicated to the virtual joystick
  106393. this._joystickPointerID = e.pointerId;
  106394. this._joystickPointerStartPos.x = e.clientX;
  106395. this._joystickPointerStartPos.y = e.clientY;
  106396. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  106397. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  106398. this._deltaJoystickVector.x = 0;
  106399. this._deltaJoystickVector.y = 0;
  106400. this.pressed = true;
  106401. this._touches.add(e.pointerId.toString(), e);
  106402. }
  106403. else {
  106404. // You can only trigger the action buttons with a joystick declared
  106405. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  106406. this._action();
  106407. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  106408. }
  106409. }
  106410. };
  106411. VirtualJoystick.prototype._onPointerMove = function (e) {
  106412. // If the current pointer is the one associated to the joystick (first touch contact)
  106413. if (this._joystickPointerID == e.pointerId) {
  106414. this._joystickPointerPos.x = e.clientX;
  106415. this._joystickPointerPos.y = e.clientY;
  106416. this._deltaJoystickVector = this._joystickPointerPos.clone();
  106417. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  106418. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  106419. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  106420. switch (this._axisTargetedByLeftAndRight) {
  106421. case JoystickAxis.X:
  106422. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  106423. break;
  106424. case JoystickAxis.Y:
  106425. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  106426. break;
  106427. case JoystickAxis.Z:
  106428. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  106429. break;
  106430. }
  106431. var directionUpDown = this.reverseUpDown ? 1 : -1;
  106432. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  106433. switch (this._axisTargetedByUpAndDown) {
  106434. case JoystickAxis.X:
  106435. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  106436. break;
  106437. case JoystickAxis.Y:
  106438. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  106439. break;
  106440. case JoystickAxis.Z:
  106441. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  106442. break;
  106443. }
  106444. }
  106445. else {
  106446. var data = this._touches.get(e.pointerId.toString());
  106447. if (data) {
  106448. data.x = e.clientX;
  106449. data.y = e.clientY;
  106450. }
  106451. }
  106452. };
  106453. VirtualJoystick.prototype._onPointerUp = function (e) {
  106454. if (this._joystickPointerID == e.pointerId) {
  106455. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  106456. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  106457. this._joystickPointerID = -1;
  106458. this.pressed = false;
  106459. }
  106460. else {
  106461. var touch = this._touches.get(e.pointerId.toString());
  106462. if (touch) {
  106463. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  106464. }
  106465. }
  106466. this._deltaJoystickVector.x = 0;
  106467. this._deltaJoystickVector.y = 0;
  106468. this._touches.remove(e.pointerId.toString());
  106469. };
  106470. /**
  106471. * Change the color of the virtual joystick
  106472. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  106473. */
  106474. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  106475. this._joystickColor = newColor;
  106476. };
  106477. /**
  106478. * Defines a callback to call when the joystick is touched
  106479. * @param action defines the callback
  106480. */
  106481. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  106482. this._action = action;
  106483. };
  106484. /**
  106485. * Defines which axis you'd like to control for left & right
  106486. * @param axis defines the axis to use
  106487. */
  106488. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  106489. switch (axis) {
  106490. case JoystickAxis.X:
  106491. case JoystickAxis.Y:
  106492. case JoystickAxis.Z:
  106493. this._axisTargetedByLeftAndRight = axis;
  106494. break;
  106495. default:
  106496. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  106497. break;
  106498. }
  106499. };
  106500. /**
  106501. * Defines which axis you'd like to control for up & down
  106502. * @param axis defines the axis to use
  106503. */
  106504. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  106505. switch (axis) {
  106506. case JoystickAxis.X:
  106507. case JoystickAxis.Y:
  106508. case JoystickAxis.Z:
  106509. this._axisTargetedByUpAndDown = axis;
  106510. break;
  106511. default:
  106512. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  106513. break;
  106514. }
  106515. };
  106516. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  106517. var _this = this;
  106518. if (this.pressed) {
  106519. this._touches.forEach(function (key, touch) {
  106520. if (touch.pointerId === _this._joystickPointerID) {
  106521. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  106522. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  106523. VirtualJoystick.vjCanvasContext.beginPath();
  106524. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  106525. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  106526. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  106527. VirtualJoystick.vjCanvasContext.stroke();
  106528. VirtualJoystick.vjCanvasContext.closePath();
  106529. VirtualJoystick.vjCanvasContext.beginPath();
  106530. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  106531. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  106532. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  106533. VirtualJoystick.vjCanvasContext.stroke();
  106534. VirtualJoystick.vjCanvasContext.closePath();
  106535. VirtualJoystick.vjCanvasContext.beginPath();
  106536. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  106537. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  106538. VirtualJoystick.vjCanvasContext.stroke();
  106539. VirtualJoystick.vjCanvasContext.closePath();
  106540. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  106541. }
  106542. else {
  106543. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  106544. VirtualJoystick.vjCanvasContext.beginPath();
  106545. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  106546. VirtualJoystick.vjCanvasContext.beginPath();
  106547. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  106548. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  106549. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  106550. VirtualJoystick.vjCanvasContext.stroke();
  106551. VirtualJoystick.vjCanvasContext.closePath();
  106552. touch.prevX = touch.x;
  106553. touch.prevY = touch.y;
  106554. }
  106555. });
  106556. }
  106557. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  106558. };
  106559. /**
  106560. * Release internal HTML canvas
  106561. */
  106562. VirtualJoystick.prototype.releaseCanvas = function () {
  106563. if (VirtualJoystick.vjCanvas) {
  106564. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  106565. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  106566. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  106567. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  106568. window.removeEventListener("resize", this._onResize);
  106569. document.body.removeChild(VirtualJoystick.vjCanvas);
  106570. VirtualJoystick.vjCanvas = null;
  106571. }
  106572. };
  106573. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  106574. VirtualJoystick._globalJoystickIndex = 0;
  106575. return VirtualJoystick;
  106576. }());
  106577. BABYLON.VirtualJoystick = VirtualJoystick;
  106578. })(BABYLON || (BABYLON = {}));
  106579. //# sourceMappingURL=babylon.virtualJoystick.js.map
  106580. var BABYLON;
  106581. (function (BABYLON) {
  106582. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  106583. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  106584. });
  106585. /**
  106586. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  106587. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  106588. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  106589. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  106590. */
  106591. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  106592. __extends(VirtualJoysticksCamera, _super);
  106593. /**
  106594. * Intantiates a VirtualJoysticksCamera. It can be usefull in First Person Shooter game for instance.
  106595. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  106596. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  106597. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  106598. * @param name Define the name of the camera in the scene
  106599. * @param position Define the start position of the camera in the scene
  106600. * @param scene Define the scene the camera belongs to
  106601. */
  106602. function VirtualJoysticksCamera(name, position, scene) {
  106603. var _this = _super.call(this, name, position, scene) || this;
  106604. _this.inputs.addVirtualJoystick();
  106605. return _this;
  106606. }
  106607. /**
  106608. * Gets the current object class name.
  106609. * @return the class name
  106610. */
  106611. VirtualJoysticksCamera.prototype.getClassName = function () {
  106612. return "VirtualJoysticksCamera";
  106613. };
  106614. return VirtualJoysticksCamera;
  106615. }(BABYLON.FreeCamera));
  106616. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  106617. })(BABYLON || (BABYLON = {}));
  106618. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  106619. var BABYLON;
  106620. (function (BABYLON) {
  106621. /**
  106622. * Manage the Virtual Joystick inputs to control the movement of a free camera.
  106623. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  106624. */
  106625. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  106626. function FreeCameraVirtualJoystickInput() {
  106627. }
  106628. /**
  106629. * Gets the left stick of the virtual joystick.
  106630. * @returns The virtual Joystick
  106631. */
  106632. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  106633. return this._leftjoystick;
  106634. };
  106635. /**
  106636. * Gets the right stick of the virtual joystick.
  106637. * @returns The virtual Joystick
  106638. */
  106639. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  106640. return this._rightjoystick;
  106641. };
  106642. /**
  106643. * Update the current camera state depending on the inputs that have been used this frame.
  106644. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  106645. */
  106646. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  106647. if (this._leftjoystick) {
  106648. var camera = this.camera;
  106649. var speed = camera._computeLocalCameraSpeed() * 50;
  106650. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  106651. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  106652. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  106653. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  106654. if (!this._leftjoystick.pressed) {
  106655. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  106656. }
  106657. if (!this._rightjoystick.pressed) {
  106658. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  106659. }
  106660. }
  106661. };
  106662. /**
  106663. * Attach the input controls to a specific dom element to get the input from.
  106664. * @param element Defines the element the controls should be listened from
  106665. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  106666. */
  106667. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  106668. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  106669. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  106670. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  106671. this._leftjoystick.setJoystickSensibility(0.15);
  106672. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  106673. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  106674. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  106675. this._rightjoystick.reverseUpDown = true;
  106676. this._rightjoystick.setJoystickSensibility(0.05);
  106677. this._rightjoystick.setJoystickColor("yellow");
  106678. };
  106679. /**
  106680. * Detach the current controls from the specified dom element.
  106681. * @param element Defines the element to stop listening the inputs from
  106682. */
  106683. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  106684. this._leftjoystick.releaseCanvas();
  106685. this._rightjoystick.releaseCanvas();
  106686. };
  106687. /**
  106688. * Gets the class name of the current intput.
  106689. * @returns the class name
  106690. */
  106691. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  106692. return "FreeCameraVirtualJoystickInput";
  106693. };
  106694. /**
  106695. * Get the friendly name associated with the input class.
  106696. * @returns the input friendly name
  106697. */
  106698. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  106699. return "virtualJoystick";
  106700. };
  106701. return FreeCameraVirtualJoystickInput;
  106702. }());
  106703. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  106704. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  106705. })(BABYLON || (BABYLON = {}));
  106706. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  106707. var BABYLON;
  106708. (function (BABYLON) {
  106709. /**
  106710. * Class used to specify simplification options
  106711. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  106712. */
  106713. var SimplificationSettings = /** @class */ (function () {
  106714. /**
  106715. * Creates a SimplificationSettings
  106716. * @param quality expected quality
  106717. * @param distance distance when this optimized version should be used
  106718. * @param optimizeMesh already optimized mesh
  106719. */
  106720. function SimplificationSettings(
  106721. /** expected quality */
  106722. quality,
  106723. /** distance when this optimized version should be used */
  106724. distance,
  106725. /** already optimized mesh */
  106726. optimizeMesh) {
  106727. this.quality = quality;
  106728. this.distance = distance;
  106729. this.optimizeMesh = optimizeMesh;
  106730. }
  106731. return SimplificationSettings;
  106732. }());
  106733. BABYLON.SimplificationSettings = SimplificationSettings;
  106734. /**
  106735. * Queue used to order the simplification tasks
  106736. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  106737. */
  106738. var SimplificationQueue = /** @class */ (function () {
  106739. /**
  106740. * Creates a new queue
  106741. */
  106742. function SimplificationQueue() {
  106743. this.running = false;
  106744. this._simplificationArray = [];
  106745. }
  106746. /**
  106747. * Adds a new simplification task
  106748. * @param task defines a task to add
  106749. */
  106750. SimplificationQueue.prototype.addTask = function (task) {
  106751. this._simplificationArray.push(task);
  106752. };
  106753. /**
  106754. * Execute next task
  106755. */
  106756. SimplificationQueue.prototype.executeNext = function () {
  106757. var task = this._simplificationArray.pop();
  106758. if (task) {
  106759. this.running = true;
  106760. this.runSimplification(task);
  106761. }
  106762. else {
  106763. this.running = false;
  106764. }
  106765. };
  106766. /**
  106767. * Execute a simplification task
  106768. * @param task defines the task to run
  106769. */
  106770. SimplificationQueue.prototype.runSimplification = function (task) {
  106771. var _this = this;
  106772. if (task.parallelProcessing) {
  106773. //parallel simplifier
  106774. task.settings.forEach(function (setting) {
  106775. var simplifier = _this.getSimplifier(task);
  106776. simplifier.simplify(setting, function (newMesh) {
  106777. task.mesh.addLODLevel(setting.distance, newMesh);
  106778. newMesh.isVisible = true;
  106779. //check if it is the last
  106780. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  106781. //all done, run the success callback.
  106782. task.successCallback();
  106783. }
  106784. _this.executeNext();
  106785. });
  106786. });
  106787. }
  106788. else {
  106789. //single simplifier.
  106790. var simplifier = this.getSimplifier(task);
  106791. var runDecimation = function (setting, callback) {
  106792. simplifier.simplify(setting, function (newMesh) {
  106793. task.mesh.addLODLevel(setting.distance, newMesh);
  106794. newMesh.isVisible = true;
  106795. //run the next quality level
  106796. callback();
  106797. });
  106798. };
  106799. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  106800. runDecimation(task.settings[loop.index], function () {
  106801. loop.executeNext();
  106802. });
  106803. }, function () {
  106804. //execution ended, run the success callback.
  106805. if (task.successCallback) {
  106806. task.successCallback();
  106807. }
  106808. _this.executeNext();
  106809. });
  106810. }
  106811. };
  106812. SimplificationQueue.prototype.getSimplifier = function (task) {
  106813. switch (task.simplificationType) {
  106814. case SimplificationType.QUADRATIC:
  106815. default:
  106816. return new QuadraticErrorSimplification(task.mesh);
  106817. }
  106818. };
  106819. return SimplificationQueue;
  106820. }());
  106821. BABYLON.SimplificationQueue = SimplificationQueue;
  106822. /**
  106823. * The implemented types of simplification
  106824. * At the moment only Quadratic Error Decimation is implemented
  106825. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  106826. */
  106827. var SimplificationType;
  106828. (function (SimplificationType) {
  106829. /** Quadratic error decimation */
  106830. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  106831. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  106832. var DecimationTriangle = /** @class */ (function () {
  106833. function DecimationTriangle(vertices) {
  106834. this.vertices = vertices;
  106835. this.error = new Array(4);
  106836. this.deleted = false;
  106837. this.isDirty = false;
  106838. this.deletePending = false;
  106839. this.borderFactor = 0;
  106840. }
  106841. return DecimationTriangle;
  106842. }());
  106843. var DecimationVertex = /** @class */ (function () {
  106844. function DecimationVertex(position, id) {
  106845. this.position = position;
  106846. this.id = id;
  106847. this.isBorder = true;
  106848. this.q = new QuadraticMatrix();
  106849. this.triangleCount = 0;
  106850. this.triangleStart = 0;
  106851. this.originalOffsets = [];
  106852. }
  106853. DecimationVertex.prototype.updatePosition = function (newPosition) {
  106854. this.position.copyFrom(newPosition);
  106855. };
  106856. return DecimationVertex;
  106857. }());
  106858. var QuadraticMatrix = /** @class */ (function () {
  106859. function QuadraticMatrix(data) {
  106860. this.data = new Array(10);
  106861. for (var i = 0; i < 10; ++i) {
  106862. if (data && data[i]) {
  106863. this.data[i] = data[i];
  106864. }
  106865. else {
  106866. this.data[i] = 0;
  106867. }
  106868. }
  106869. }
  106870. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  106871. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  106872. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  106873. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  106874. return det;
  106875. };
  106876. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  106877. for (var i = 0; i < 10; ++i) {
  106878. this.data[i] += matrix.data[i];
  106879. }
  106880. };
  106881. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  106882. for (var i = 0; i < 10; ++i) {
  106883. this.data[i] += data[i];
  106884. }
  106885. };
  106886. QuadraticMatrix.prototype.add = function (matrix) {
  106887. var m = new QuadraticMatrix();
  106888. for (var i = 0; i < 10; ++i) {
  106889. m.data[i] = this.data[i] + matrix.data[i];
  106890. }
  106891. return m;
  106892. };
  106893. QuadraticMatrix.FromData = function (a, b, c, d) {
  106894. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  106895. };
  106896. //returning an array to avoid garbage collection
  106897. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  106898. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  106899. };
  106900. return QuadraticMatrix;
  106901. }());
  106902. var Reference = /** @class */ (function () {
  106903. function Reference(vertexId, triangleId) {
  106904. this.vertexId = vertexId;
  106905. this.triangleId = triangleId;
  106906. }
  106907. return Reference;
  106908. }());
  106909. /**
  106910. * An implementation of the Quadratic Error simplification algorithm.
  106911. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  106912. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  106913. * @author RaananW
  106914. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  106915. */
  106916. var QuadraticErrorSimplification = /** @class */ (function () {
  106917. function QuadraticErrorSimplification(_mesh) {
  106918. this._mesh = _mesh;
  106919. this.syncIterations = 5000;
  106920. this.aggressiveness = 7;
  106921. this.decimationIterations = 100;
  106922. this.boundingBoxEpsilon = BABYLON.Epsilon;
  106923. }
  106924. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  106925. var _this = this;
  106926. this.initDecimatedMesh();
  106927. //iterating through the submeshes array, one after the other.
  106928. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  106929. _this.initWithMesh(loop.index, function () {
  106930. _this.runDecimation(settings, loop.index, function () {
  106931. loop.executeNext();
  106932. });
  106933. }, settings.optimizeMesh);
  106934. }, function () {
  106935. setTimeout(function () {
  106936. successCallback(_this._reconstructedMesh);
  106937. }, 0);
  106938. });
  106939. };
  106940. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  106941. var _this = this;
  106942. var targetCount = ~~(this.triangles.length * settings.quality);
  106943. var deletedTriangles = 0;
  106944. var triangleCount = this.triangles.length;
  106945. var iterationFunction = function (iteration, callback) {
  106946. setTimeout(function () {
  106947. if (iteration % 5 === 0) {
  106948. _this.updateMesh(iteration === 0);
  106949. }
  106950. for (var i = 0; i < _this.triangles.length; ++i) {
  106951. _this.triangles[i].isDirty = false;
  106952. }
  106953. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  106954. var trianglesIterator = function (i) {
  106955. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  106956. var t = _this.triangles[tIdx];
  106957. if (!t) {
  106958. return;
  106959. }
  106960. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  106961. return;
  106962. }
  106963. for (var j = 0; j < 3; ++j) {
  106964. if (t.error[j] < threshold) {
  106965. var deleted0 = [];
  106966. var deleted1 = [];
  106967. var v0 = t.vertices[j];
  106968. var v1 = t.vertices[(j + 1) % 3];
  106969. if (v0.isBorder || v1.isBorder) {
  106970. continue;
  106971. }
  106972. var p = BABYLON.Vector3.Zero();
  106973. var n = BABYLON.Vector3.Zero();
  106974. var uv = BABYLON.Vector2.Zero();
  106975. var color = new BABYLON.Color4(0, 0, 0, 1);
  106976. _this.calculateError(v0, v1, p, n, uv, color);
  106977. var delTr = new Array();
  106978. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr)) {
  106979. continue;
  106980. }
  106981. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr)) {
  106982. continue;
  106983. }
  106984. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0) {
  106985. continue;
  106986. }
  106987. var uniqueArray = new Array();
  106988. delTr.forEach(function (deletedT) {
  106989. if (uniqueArray.indexOf(deletedT) === -1) {
  106990. deletedT.deletePending = true;
  106991. uniqueArray.push(deletedT);
  106992. }
  106993. });
  106994. if (uniqueArray.length % 2 !== 0) {
  106995. continue;
  106996. }
  106997. v0.q = v1.q.add(v0.q);
  106998. v0.updatePosition(p);
  106999. var tStart = _this.references.length;
  107000. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  107001. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  107002. var tCount = _this.references.length - tStart;
  107003. if (tCount <= v0.triangleCount) {
  107004. if (tCount) {
  107005. for (var c = 0; c < tCount; c++) {
  107006. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  107007. }
  107008. }
  107009. }
  107010. else {
  107011. v0.triangleStart = tStart;
  107012. }
  107013. v0.triangleCount = tCount;
  107014. break;
  107015. }
  107016. }
  107017. };
  107018. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  107019. }, 0);
  107020. };
  107021. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  107022. if (triangleCount - deletedTriangles <= targetCount) {
  107023. loop.breakLoop();
  107024. }
  107025. else {
  107026. iterationFunction(loop.index, function () {
  107027. loop.executeNext();
  107028. });
  107029. }
  107030. }, function () {
  107031. setTimeout(function () {
  107032. //reconstruct this part of the mesh
  107033. _this.reconstructMesh(submeshIndex);
  107034. successCallback();
  107035. }, 0);
  107036. });
  107037. };
  107038. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  107039. var _this = this;
  107040. this.vertices = [];
  107041. this.triangles = [];
  107042. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  107043. var indices = this._mesh.getIndices();
  107044. var submesh = this._mesh.subMeshes[submeshIndex];
  107045. var findInVertices = function (positionToSearch) {
  107046. if (optimizeMesh) {
  107047. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  107048. if (_this.vertices[ii].position.equals(positionToSearch)) {
  107049. return _this.vertices[ii];
  107050. }
  107051. }
  107052. }
  107053. return null;
  107054. };
  107055. var vertexReferences = [];
  107056. var vertexInit = function (i) {
  107057. if (!positionData) {
  107058. return;
  107059. }
  107060. var offset = i + submesh.verticesStart;
  107061. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  107062. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  107063. vertex.originalOffsets.push(offset);
  107064. if (vertex.id === _this.vertices.length) {
  107065. _this.vertices.push(vertex);
  107066. }
  107067. vertexReferences.push(vertex.id);
  107068. };
  107069. //var totalVertices = mesh.getTotalVertices();
  107070. var totalVertices = submesh.verticesCount;
  107071. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  107072. var indicesInit = function (i) {
  107073. if (!indices) {
  107074. return;
  107075. }
  107076. var offset = (submesh.indexStart / 3) + i;
  107077. var pos = (offset * 3);
  107078. var i0 = indices[pos + 0];
  107079. var i1 = indices[pos + 1];
  107080. var i2 = indices[pos + 2];
  107081. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  107082. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  107083. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  107084. var triangle = new DecimationTriangle([v0, v1, v2]);
  107085. triangle.originalOffset = pos;
  107086. _this.triangles.push(triangle);
  107087. };
  107088. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  107089. _this.init(callback);
  107090. });
  107091. });
  107092. };
  107093. QuadraticErrorSimplification.prototype.init = function (callback) {
  107094. var _this = this;
  107095. var triangleInit1 = function (i) {
  107096. var t = _this.triangles[i];
  107097. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  107098. for (var j = 0; j < 3; j++) {
  107099. 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))));
  107100. }
  107101. };
  107102. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  107103. var triangleInit2 = function (i) {
  107104. var t = _this.triangles[i];
  107105. for (var j = 0; j < 3; ++j) {
  107106. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  107107. }
  107108. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  107109. };
  107110. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  107111. callback();
  107112. });
  107113. });
  107114. };
  107115. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  107116. var newTriangles = [];
  107117. var i;
  107118. for (i = 0; i < this.vertices.length; ++i) {
  107119. this.vertices[i].triangleCount = 0;
  107120. }
  107121. var t;
  107122. var j;
  107123. for (i = 0; i < this.triangles.length; ++i) {
  107124. if (!this.triangles[i].deleted) {
  107125. t = this.triangles[i];
  107126. for (j = 0; j < 3; ++j) {
  107127. t.vertices[j].triangleCount = 1;
  107128. }
  107129. newTriangles.push(t);
  107130. }
  107131. }
  107132. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  107133. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  107134. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  107135. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  107136. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  107137. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  107138. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  107139. var vertexCount = 0;
  107140. for (i = 0; i < this.vertices.length; ++i) {
  107141. var vertex = this.vertices[i];
  107142. vertex.id = vertexCount;
  107143. if (vertex.triangleCount) {
  107144. vertex.originalOffsets.forEach(function (originalOffset) {
  107145. if (!normalData) {
  107146. return;
  107147. }
  107148. newPositionData.push(vertex.position.x);
  107149. newPositionData.push(vertex.position.y);
  107150. newPositionData.push(vertex.position.z);
  107151. newNormalData.push(normalData[originalOffset * 3]);
  107152. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  107153. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  107154. if (uvs && uvs.length) {
  107155. newUVsData.push(uvs[(originalOffset * 2)]);
  107156. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  107157. }
  107158. else if (colorsData && colorsData.length) {
  107159. newColorsData.push(colorsData[(originalOffset * 4)]);
  107160. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  107161. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  107162. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  107163. }
  107164. ++vertexCount;
  107165. });
  107166. }
  107167. }
  107168. var startingIndex = this._reconstructedMesh.getTotalIndices();
  107169. var startingVertex = this._reconstructedMesh.getTotalVertices();
  107170. var submeshesArray = this._reconstructedMesh.subMeshes;
  107171. this._reconstructedMesh.subMeshes = [];
  107172. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  107173. var originalIndices = this._mesh.getIndices();
  107174. for (i = 0; i < newTriangles.length; ++i) {
  107175. t = newTriangles[i]; //now get the new referencing point for each vertex
  107176. [0, 1, 2].forEach(function (idx) {
  107177. var id = originalIndices[t.originalOffset + idx];
  107178. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  107179. if (offset < 0) {
  107180. offset = 0;
  107181. }
  107182. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  107183. });
  107184. }
  107185. //overwriting the old vertex buffers and indices.
  107186. this._reconstructedMesh.setIndices(newIndicesArray);
  107187. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  107188. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  107189. if (newUVsData.length > 0) {
  107190. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  107191. }
  107192. if (newColorsData.length > 0) {
  107193. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  107194. }
  107195. //create submesh
  107196. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  107197. if (submeshIndex > 0) {
  107198. this._reconstructedMesh.subMeshes = [];
  107199. submeshesArray.forEach(function (submesh) {
  107200. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  107201. });
  107202. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  107203. }
  107204. };
  107205. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  107206. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  107207. this._reconstructedMesh.material = this._mesh.material;
  107208. this._reconstructedMesh.parent = this._mesh.parent;
  107209. this._reconstructedMesh.isVisible = false;
  107210. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  107211. };
  107212. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  107213. for (var i = 0; i < vertex1.triangleCount; ++i) {
  107214. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  107215. if (t.deleted) {
  107216. continue;
  107217. }
  107218. var s = this.references[vertex1.triangleStart + i].vertexId;
  107219. var v1 = t.vertices[(s + 1) % 3];
  107220. var v2 = t.vertices[(s + 2) % 3];
  107221. if ((v1 === vertex2 || v2 === vertex2)) {
  107222. deletedArray[i] = true;
  107223. delTr.push(t);
  107224. continue;
  107225. }
  107226. var d1 = v1.position.subtract(point);
  107227. d1 = d1.normalize();
  107228. var d2 = v2.position.subtract(point);
  107229. d2 = d2.normalize();
  107230. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999) {
  107231. return true;
  107232. }
  107233. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  107234. deletedArray[i] = false;
  107235. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2) {
  107236. return true;
  107237. }
  107238. }
  107239. return false;
  107240. };
  107241. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  107242. var newDeleted = deletedTriangles;
  107243. for (var i = 0; i < vertex.triangleCount; ++i) {
  107244. var ref = this.references[vertex.triangleStart + i];
  107245. var t = this.triangles[ref.triangleId];
  107246. if (t.deleted) {
  107247. continue;
  107248. }
  107249. if (deletedArray[i] && t.deletePending) {
  107250. t.deleted = true;
  107251. newDeleted++;
  107252. continue;
  107253. }
  107254. t.vertices[ref.vertexId] = origVertex;
  107255. t.isDirty = true;
  107256. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  107257. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  107258. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  107259. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  107260. this.references.push(ref);
  107261. }
  107262. return newDeleted;
  107263. };
  107264. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  107265. for (var i = 0; i < this.vertices.length; ++i) {
  107266. var vCount = [];
  107267. var vId = [];
  107268. var v = this.vertices[i];
  107269. var j;
  107270. for (j = 0; j < v.triangleCount; ++j) {
  107271. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  107272. for (var ii = 0; ii < 3; ii++) {
  107273. var ofs = 0;
  107274. var vv = triangle.vertices[ii];
  107275. while (ofs < vCount.length) {
  107276. if (vId[ofs] === vv.id) {
  107277. break;
  107278. }
  107279. ++ofs;
  107280. }
  107281. if (ofs === vCount.length) {
  107282. vCount.push(1);
  107283. vId.push(vv.id);
  107284. }
  107285. else {
  107286. vCount[ofs]++;
  107287. }
  107288. }
  107289. }
  107290. for (j = 0; j < vCount.length; ++j) {
  107291. if (vCount[j] === 1) {
  107292. this.vertices[vId[j]].isBorder = true;
  107293. }
  107294. else {
  107295. this.vertices[vId[j]].isBorder = false;
  107296. }
  107297. }
  107298. }
  107299. };
  107300. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  107301. if (identifyBorders === void 0) { identifyBorders = false; }
  107302. var i;
  107303. if (!identifyBorders) {
  107304. var newTrianglesVector = [];
  107305. for (i = 0; i < this.triangles.length; ++i) {
  107306. if (!this.triangles[i].deleted) {
  107307. newTrianglesVector.push(this.triangles[i]);
  107308. }
  107309. }
  107310. this.triangles = newTrianglesVector;
  107311. }
  107312. for (i = 0; i < this.vertices.length; ++i) {
  107313. this.vertices[i].triangleCount = 0;
  107314. this.vertices[i].triangleStart = 0;
  107315. }
  107316. var t;
  107317. var j;
  107318. var v;
  107319. for (i = 0; i < this.triangles.length; ++i) {
  107320. t = this.triangles[i];
  107321. for (j = 0; j < 3; ++j) {
  107322. v = t.vertices[j];
  107323. v.triangleCount++;
  107324. }
  107325. }
  107326. var tStart = 0;
  107327. for (i = 0; i < this.vertices.length; ++i) {
  107328. this.vertices[i].triangleStart = tStart;
  107329. tStart += this.vertices[i].triangleCount;
  107330. this.vertices[i].triangleCount = 0;
  107331. }
  107332. var newReferences = new Array(this.triangles.length * 3);
  107333. for (i = 0; i < this.triangles.length; ++i) {
  107334. t = this.triangles[i];
  107335. for (j = 0; j < 3; ++j) {
  107336. v = t.vertices[j];
  107337. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  107338. v.triangleCount++;
  107339. }
  107340. }
  107341. this.references = newReferences;
  107342. if (identifyBorders) {
  107343. this.identifyBorder();
  107344. }
  107345. };
  107346. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  107347. var x = point.x;
  107348. var y = point.y;
  107349. var z = point.z;
  107350. 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
  107351. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  107352. };
  107353. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  107354. var q = vertex1.q.add(vertex2.q);
  107355. var border = vertex1.isBorder && vertex2.isBorder;
  107356. var error = 0;
  107357. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  107358. if (qDet !== 0 && !border) {
  107359. if (!pointResult) {
  107360. pointResult = BABYLON.Vector3.Zero();
  107361. }
  107362. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  107363. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  107364. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  107365. error = this.vertexError(q, pointResult);
  107366. }
  107367. else {
  107368. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  107369. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  107370. var error1 = this.vertexError(q, vertex1.position);
  107371. var error2 = this.vertexError(q, vertex2.position);
  107372. var error3 = this.vertexError(q, p3);
  107373. error = Math.min(error1, error2, error3);
  107374. if (error === error1) {
  107375. if (pointResult) {
  107376. pointResult.copyFrom(vertex1.position);
  107377. }
  107378. }
  107379. else if (error === error2) {
  107380. if (pointResult) {
  107381. pointResult.copyFrom(vertex2.position);
  107382. }
  107383. }
  107384. else {
  107385. if (pointResult) {
  107386. pointResult.copyFrom(p3);
  107387. }
  107388. }
  107389. }
  107390. return error;
  107391. };
  107392. return QuadraticErrorSimplification;
  107393. }());
  107394. })(BABYLON || (BABYLON = {}));
  107395. //# sourceMappingURL=babylon.meshSimplification.js.map
  107396. var BABYLON;
  107397. (function (BABYLON) {
  107398. Object.defineProperty(BABYLON.Scene.prototype, "simplificationQueue", {
  107399. get: function () {
  107400. if (!this._simplificationQueue) {
  107401. this._simplificationQueue = new BABYLON.SimplificationQueue();
  107402. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);
  107403. if (!component) {
  107404. component = new SimplicationQueueSceneComponent(this);
  107405. this._addComponent(component);
  107406. }
  107407. }
  107408. return this._simplificationQueue;
  107409. },
  107410. set: function (value) {
  107411. this._simplificationQueue = value;
  107412. },
  107413. enumerable: true,
  107414. configurable: true
  107415. });
  107416. BABYLON.Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  107417. if (parallelProcessing === void 0) { parallelProcessing = true; }
  107418. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  107419. this.getScene().simplificationQueue.addTask({
  107420. settings: settings,
  107421. parallelProcessing: parallelProcessing,
  107422. mesh: this,
  107423. simplificationType: simplificationType,
  107424. successCallback: successCallback
  107425. });
  107426. return this;
  107427. };
  107428. /**
  107429. * Defines the simplification queue scene component responsible to help scheduling the various simplification task
  107430. * created in a scene
  107431. */
  107432. var SimplicationQueueSceneComponent = /** @class */ (function () {
  107433. /**
  107434. * Creates a new instance of the component for the given scene
  107435. * @param scene Defines the scene to register the component in
  107436. */
  107437. function SimplicationQueueSceneComponent(scene) {
  107438. /**
  107439. * The component name helpfull to identify the component in the list of scene components.
  107440. */
  107441. this.name = BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;
  107442. this.scene = scene;
  107443. }
  107444. /**
  107445. * Registers the component in a given scene
  107446. */
  107447. SimplicationQueueSceneComponent.prototype.register = function () {
  107448. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);
  107449. };
  107450. /**
  107451. * Rebuilds the elements related to this component in case of
  107452. * context lost for instance.
  107453. */
  107454. SimplicationQueueSceneComponent.prototype.rebuild = function () {
  107455. // Nothing to do for this component
  107456. };
  107457. /**
  107458. * Disposes the component and the associated ressources
  107459. */
  107460. SimplicationQueueSceneComponent.prototype.dispose = function () {
  107461. // Nothing to do for this component
  107462. };
  107463. SimplicationQueueSceneComponent.prototype._beforeCameraUpdate = function () {
  107464. if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {
  107465. this.scene._simplificationQueue.executeNext();
  107466. }
  107467. };
  107468. return SimplicationQueueSceneComponent;
  107469. }());
  107470. BABYLON.SimplicationQueueSceneComponent = SimplicationQueueSceneComponent;
  107471. })(BABYLON || (BABYLON = {}));
  107472. //# sourceMappingURL=babylon.meshSimplificationSceneComponent.js.map
  107473. var BABYLON;
  107474. (function (BABYLON) {
  107475. /**
  107476. * Class used to represent a specific level of detail of a mesh
  107477. * @see http://doc.babylonjs.com/how_to/how_to_use_lod
  107478. */
  107479. var MeshLODLevel = /** @class */ (function () {
  107480. /**
  107481. * Creates a new LOD level
  107482. * @param distance defines the distance where this level should star being displayed
  107483. * @param mesh defines the mesh to use to render this level
  107484. */
  107485. function MeshLODLevel(
  107486. /** Defines the distance where this level should star being displayed */
  107487. distance,
  107488. /** Defines the mesh to use to render this level */
  107489. mesh) {
  107490. this.distance = distance;
  107491. this.mesh = mesh;
  107492. }
  107493. return MeshLODLevel;
  107494. }());
  107495. BABYLON.MeshLODLevel = MeshLODLevel;
  107496. })(BABYLON || (BABYLON = {}));
  107497. //# sourceMappingURL=babylon.meshLODLevel.js.map
  107498. var BABYLON;
  107499. (function (BABYLON) {
  107500. /**
  107501. * Defines the root class used to create scene optimization to use with SceneOptimizer
  107502. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107503. */
  107504. var SceneOptimization = /** @class */ (function () {
  107505. /**
  107506. * Creates the SceneOptimization object
  107507. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  107508. * @param desc defines the description associated with the optimization
  107509. */
  107510. function SceneOptimization(
  107511. /**
  107512. * Defines the priority of this optimization (0 by default which means first in the list)
  107513. */
  107514. priority) {
  107515. if (priority === void 0) { priority = 0; }
  107516. this.priority = priority;
  107517. }
  107518. /**
  107519. * Gets a string describing the action executed by the current optimization
  107520. * @returns description string
  107521. */
  107522. SceneOptimization.prototype.getDescription = function () {
  107523. return "";
  107524. };
  107525. /**
  107526. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107527. * @param scene defines the current scene where to apply this optimization
  107528. * @param optimizer defines the current optimizer
  107529. * @returns true if everything that can be done was applied
  107530. */
  107531. SceneOptimization.prototype.apply = function (scene, optimizer) {
  107532. return true;
  107533. };
  107534. return SceneOptimization;
  107535. }());
  107536. BABYLON.SceneOptimization = SceneOptimization;
  107537. /**
  107538. * Defines an optimization used to reduce the size of render target textures
  107539. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107540. */
  107541. var TextureOptimization = /** @class */ (function (_super) {
  107542. __extends(TextureOptimization, _super);
  107543. /**
  107544. * Creates the TextureOptimization object
  107545. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  107546. * @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
  107547. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  107548. */
  107549. function TextureOptimization(
  107550. /**
  107551. * Defines the priority of this optimization (0 by default which means first in the list)
  107552. */
  107553. priority,
  107554. /**
  107555. * 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
  107556. */
  107557. maximumSize,
  107558. /**
  107559. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  107560. */
  107561. step) {
  107562. if (priority === void 0) { priority = 0; }
  107563. if (maximumSize === void 0) { maximumSize = 1024; }
  107564. if (step === void 0) { step = 0.5; }
  107565. var _this = _super.call(this, priority) || this;
  107566. _this.priority = priority;
  107567. _this.maximumSize = maximumSize;
  107568. _this.step = step;
  107569. return _this;
  107570. }
  107571. /**
  107572. * Gets a string describing the action executed by the current optimization
  107573. * @returns description string
  107574. */
  107575. TextureOptimization.prototype.getDescription = function () {
  107576. return "Reducing render target texture size to " + this.maximumSize;
  107577. };
  107578. /**
  107579. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107580. * @param scene defines the current scene where to apply this optimization
  107581. * @param optimizer defines the current optimizer
  107582. * @returns true if everything that can be done was applied
  107583. */
  107584. TextureOptimization.prototype.apply = function (scene, optimizer) {
  107585. var allDone = true;
  107586. for (var index = 0; index < scene.textures.length; index++) {
  107587. var texture = scene.textures[index];
  107588. if (!texture.canRescale || texture.getContext) {
  107589. continue;
  107590. }
  107591. var currentSize = texture.getSize();
  107592. var maxDimension = Math.max(currentSize.width, currentSize.height);
  107593. if (maxDimension > this.maximumSize) {
  107594. texture.scale(this.step);
  107595. allDone = false;
  107596. }
  107597. }
  107598. return allDone;
  107599. };
  107600. return TextureOptimization;
  107601. }(SceneOptimization));
  107602. BABYLON.TextureOptimization = TextureOptimization;
  107603. /**
  107604. * Defines an optimization used to increase or decrease the rendering resolution
  107605. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107606. */
  107607. var HardwareScalingOptimization = /** @class */ (function (_super) {
  107608. __extends(HardwareScalingOptimization, _super);
  107609. /**
  107610. * Creates the HardwareScalingOptimization object
  107611. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  107612. * @param maximumScale defines the maximum scale to use (2 by default)
  107613. * @param step defines the step to use between two passes (0.5 by default)
  107614. */
  107615. function HardwareScalingOptimization(
  107616. /**
  107617. * Defines the priority of this optimization (0 by default which means first in the list)
  107618. */
  107619. priority,
  107620. /**
  107621. * Defines the maximum scale to use (2 by default)
  107622. */
  107623. maximumScale,
  107624. /**
  107625. * Defines the step to use between two passes (0.5 by default)
  107626. */
  107627. step) {
  107628. if (priority === void 0) { priority = 0; }
  107629. if (maximumScale === void 0) { maximumScale = 2; }
  107630. if (step === void 0) { step = 0.25; }
  107631. var _this = _super.call(this, priority) || this;
  107632. _this.priority = priority;
  107633. _this.maximumScale = maximumScale;
  107634. _this.step = step;
  107635. _this._currentScale = -1;
  107636. _this._directionOffset = 1;
  107637. return _this;
  107638. }
  107639. /**
  107640. * Gets a string describing the action executed by the current optimization
  107641. * @return description string
  107642. */
  107643. HardwareScalingOptimization.prototype.getDescription = function () {
  107644. return "Setting hardware scaling level to " + this._currentScale;
  107645. };
  107646. /**
  107647. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107648. * @param scene defines the current scene where to apply this optimization
  107649. * @param optimizer defines the current optimizer
  107650. * @returns true if everything that can be done was applied
  107651. */
  107652. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  107653. if (this._currentScale === -1) {
  107654. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  107655. if (this._currentScale > this.maximumScale) {
  107656. this._directionOffset = -1;
  107657. }
  107658. }
  107659. this._currentScale += this._directionOffset * this.step;
  107660. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  107661. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  107662. };
  107663. return HardwareScalingOptimization;
  107664. }(SceneOptimization));
  107665. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  107666. /**
  107667. * Defines an optimization used to remove shadows
  107668. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107669. */
  107670. var ShadowsOptimization = /** @class */ (function (_super) {
  107671. __extends(ShadowsOptimization, _super);
  107672. function ShadowsOptimization() {
  107673. return _super !== null && _super.apply(this, arguments) || this;
  107674. }
  107675. /**
  107676. * Gets a string describing the action executed by the current optimization
  107677. * @return description string
  107678. */
  107679. ShadowsOptimization.prototype.getDescription = function () {
  107680. return "Turning shadows on/off";
  107681. };
  107682. /**
  107683. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107684. * @param scene defines the current scene where to apply this optimization
  107685. * @param optimizer defines the current optimizer
  107686. * @returns true if everything that can be done was applied
  107687. */
  107688. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  107689. scene.shadowsEnabled = optimizer.isInImprovementMode;
  107690. return true;
  107691. };
  107692. return ShadowsOptimization;
  107693. }(SceneOptimization));
  107694. BABYLON.ShadowsOptimization = ShadowsOptimization;
  107695. /**
  107696. * Defines an optimization used to turn post-processes off
  107697. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107698. */
  107699. var PostProcessesOptimization = /** @class */ (function (_super) {
  107700. __extends(PostProcessesOptimization, _super);
  107701. function PostProcessesOptimization() {
  107702. return _super !== null && _super.apply(this, arguments) || this;
  107703. }
  107704. /**
  107705. * Gets a string describing the action executed by the current optimization
  107706. * @return description string
  107707. */
  107708. PostProcessesOptimization.prototype.getDescription = function () {
  107709. return "Turning post-processes on/off";
  107710. };
  107711. /**
  107712. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107713. * @param scene defines the current scene where to apply this optimization
  107714. * @param optimizer defines the current optimizer
  107715. * @returns true if everything that can be done was applied
  107716. */
  107717. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  107718. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  107719. return true;
  107720. };
  107721. return PostProcessesOptimization;
  107722. }(SceneOptimization));
  107723. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  107724. /**
  107725. * Defines an optimization used to turn lens flares off
  107726. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107727. */
  107728. var LensFlaresOptimization = /** @class */ (function (_super) {
  107729. __extends(LensFlaresOptimization, _super);
  107730. function LensFlaresOptimization() {
  107731. return _super !== null && _super.apply(this, arguments) || this;
  107732. }
  107733. /**
  107734. * Gets a string describing the action executed by the current optimization
  107735. * @return description string
  107736. */
  107737. LensFlaresOptimization.prototype.getDescription = function () {
  107738. return "Turning lens flares on/off";
  107739. };
  107740. /**
  107741. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107742. * @param scene defines the current scene where to apply this optimization
  107743. * @param optimizer defines the current optimizer
  107744. * @returns true if everything that can be done was applied
  107745. */
  107746. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  107747. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  107748. return true;
  107749. };
  107750. return LensFlaresOptimization;
  107751. }(SceneOptimization));
  107752. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  107753. /**
  107754. * Defines an optimization based on user defined callback.
  107755. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107756. */
  107757. var CustomOptimization = /** @class */ (function (_super) {
  107758. __extends(CustomOptimization, _super);
  107759. function CustomOptimization() {
  107760. return _super !== null && _super.apply(this, arguments) || this;
  107761. }
  107762. /**
  107763. * Gets a string describing the action executed by the current optimization
  107764. * @returns description string
  107765. */
  107766. CustomOptimization.prototype.getDescription = function () {
  107767. if (this.onGetDescription) {
  107768. return this.onGetDescription();
  107769. }
  107770. return "Running user defined callback";
  107771. };
  107772. /**
  107773. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107774. * @param scene defines the current scene where to apply this optimization
  107775. * @param optimizer defines the current optimizer
  107776. * @returns true if everything that can be done was applied
  107777. */
  107778. CustomOptimization.prototype.apply = function (scene, optimizer) {
  107779. if (this.onApply) {
  107780. return this.onApply(scene, optimizer);
  107781. }
  107782. return true;
  107783. };
  107784. return CustomOptimization;
  107785. }(SceneOptimization));
  107786. BABYLON.CustomOptimization = CustomOptimization;
  107787. /**
  107788. * Defines an optimization used to turn particles off
  107789. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107790. */
  107791. var ParticlesOptimization = /** @class */ (function (_super) {
  107792. __extends(ParticlesOptimization, _super);
  107793. function ParticlesOptimization() {
  107794. return _super !== null && _super.apply(this, arguments) || this;
  107795. }
  107796. /**
  107797. * Gets a string describing the action executed by the current optimization
  107798. * @return description string
  107799. */
  107800. ParticlesOptimization.prototype.getDescription = function () {
  107801. return "Turning particles on/off";
  107802. };
  107803. /**
  107804. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107805. * @param scene defines the current scene where to apply this optimization
  107806. * @param optimizer defines the current optimizer
  107807. * @returns true if everything that can be done was applied
  107808. */
  107809. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  107810. scene.particlesEnabled = optimizer.isInImprovementMode;
  107811. return true;
  107812. };
  107813. return ParticlesOptimization;
  107814. }(SceneOptimization));
  107815. BABYLON.ParticlesOptimization = ParticlesOptimization;
  107816. /**
  107817. * Defines an optimization used to turn render targets off
  107818. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107819. */
  107820. var RenderTargetsOptimization = /** @class */ (function (_super) {
  107821. __extends(RenderTargetsOptimization, _super);
  107822. function RenderTargetsOptimization() {
  107823. return _super !== null && _super.apply(this, arguments) || this;
  107824. }
  107825. /**
  107826. * Gets a string describing the action executed by the current optimization
  107827. * @return description string
  107828. */
  107829. RenderTargetsOptimization.prototype.getDescription = function () {
  107830. return "Turning render targets off";
  107831. };
  107832. /**
  107833. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107834. * @param scene defines the current scene where to apply this optimization
  107835. * @param optimizer defines the current optimizer
  107836. * @returns true if everything that can be done was applied
  107837. */
  107838. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  107839. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  107840. return true;
  107841. };
  107842. return RenderTargetsOptimization;
  107843. }(SceneOptimization));
  107844. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  107845. /**
  107846. * Defines an optimization used to merge meshes with compatible materials
  107847. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107848. */
  107849. var MergeMeshesOptimization = /** @class */ (function (_super) {
  107850. __extends(MergeMeshesOptimization, _super);
  107851. function MergeMeshesOptimization() {
  107852. var _this = _super !== null && _super.apply(this, arguments) || this;
  107853. _this._canBeMerged = function (abstractMesh) {
  107854. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  107855. return false;
  107856. }
  107857. var mesh = abstractMesh;
  107858. if (mesh.isDisposed()) {
  107859. return false;
  107860. }
  107861. if (!mesh.isVisible || !mesh.isEnabled()) {
  107862. return false;
  107863. }
  107864. if (mesh.instances.length > 0) {
  107865. return false;
  107866. }
  107867. if (mesh.skeleton || mesh.hasLODLevels) {
  107868. return false;
  107869. }
  107870. return true;
  107871. };
  107872. return _this;
  107873. }
  107874. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  107875. /**
  107876. * Gets or sets a boolean which defines if optimization octree has to be updated
  107877. */
  107878. get: function () {
  107879. return MergeMeshesOptimization._UpdateSelectionTree;
  107880. },
  107881. /**
  107882. * Gets or sets a boolean which defines if optimization octree has to be updated
  107883. */
  107884. set: function (value) {
  107885. MergeMeshesOptimization._UpdateSelectionTree = value;
  107886. },
  107887. enumerable: true,
  107888. configurable: true
  107889. });
  107890. /**
  107891. * Gets a string describing the action executed by the current optimization
  107892. * @return description string
  107893. */
  107894. MergeMeshesOptimization.prototype.getDescription = function () {
  107895. return "Merging similar meshes together";
  107896. };
  107897. /**
  107898. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107899. * @param scene defines the current scene where to apply this optimization
  107900. * @param optimizer defines the current optimizer
  107901. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  107902. * @returns true if everything that can be done was applied
  107903. */
  107904. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  107905. var globalPool = scene.meshes.slice(0);
  107906. var globalLength = globalPool.length;
  107907. for (var index = 0; index < globalLength; index++) {
  107908. var currentPool = new Array();
  107909. var current = globalPool[index];
  107910. // Checks
  107911. if (!this._canBeMerged(current)) {
  107912. continue;
  107913. }
  107914. currentPool.push(current);
  107915. // Find compatible meshes
  107916. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  107917. var otherMesh = globalPool[subIndex];
  107918. if (!this._canBeMerged(otherMesh)) {
  107919. continue;
  107920. }
  107921. if (otherMesh.material !== current.material) {
  107922. continue;
  107923. }
  107924. if (otherMesh.checkCollisions !== current.checkCollisions) {
  107925. continue;
  107926. }
  107927. currentPool.push(otherMesh);
  107928. globalLength--;
  107929. globalPool.splice(subIndex, 1);
  107930. subIndex--;
  107931. }
  107932. if (currentPool.length < 2) {
  107933. continue;
  107934. }
  107935. // Merge meshes
  107936. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  107937. }
  107938. // Call the octree system optimization if it is defined.
  107939. var sceneAsAny = scene;
  107940. if (sceneAsAny.createOrUpdateSelectionOctree) {
  107941. if (updateSelectionTree != undefined) {
  107942. if (updateSelectionTree) {
  107943. sceneAsAny.createOrUpdateSelectionOctree();
  107944. }
  107945. }
  107946. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  107947. sceneAsAny.createOrUpdateSelectionOctree();
  107948. }
  107949. }
  107950. return true;
  107951. };
  107952. MergeMeshesOptimization._UpdateSelectionTree = false;
  107953. return MergeMeshesOptimization;
  107954. }(SceneOptimization));
  107955. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  107956. /**
  107957. * Defines a list of options used by SceneOptimizer
  107958. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107959. */
  107960. var SceneOptimizerOptions = /** @class */ (function () {
  107961. /**
  107962. * Creates a new list of options used by SceneOptimizer
  107963. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  107964. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  107965. */
  107966. function SceneOptimizerOptions(
  107967. /**
  107968. * Defines the target frame rate to reach (60 by default)
  107969. */
  107970. targetFrameRate,
  107971. /**
  107972. * Defines the interval between two checkes (2000ms by default)
  107973. */
  107974. trackerDuration) {
  107975. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  107976. if (trackerDuration === void 0) { trackerDuration = 2000; }
  107977. this.targetFrameRate = targetFrameRate;
  107978. this.trackerDuration = trackerDuration;
  107979. /**
  107980. * Gets the list of optimizations to apply
  107981. */
  107982. this.optimizations = new Array();
  107983. }
  107984. /**
  107985. * Add a new optimization
  107986. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  107987. * @returns the current SceneOptimizerOptions
  107988. */
  107989. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  107990. this.optimizations.push(optimization);
  107991. return this;
  107992. };
  107993. /**
  107994. * Add a new custom optimization
  107995. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  107996. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  107997. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  107998. * @returns the current SceneOptimizerOptions
  107999. */
  108000. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  108001. if (priority === void 0) { priority = 0; }
  108002. var optimization = new CustomOptimization(priority);
  108003. optimization.onApply = onApply;
  108004. optimization.onGetDescription = onGetDescription;
  108005. this.optimizations.push(optimization);
  108006. return this;
  108007. };
  108008. /**
  108009. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  108010. * @param targetFrameRate defines the target frame rate (60 by default)
  108011. * @returns a SceneOptimizerOptions object
  108012. */
  108013. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  108014. var result = new SceneOptimizerOptions(targetFrameRate);
  108015. var priority = 0;
  108016. result.addOptimization(new MergeMeshesOptimization(priority));
  108017. result.addOptimization(new ShadowsOptimization(priority));
  108018. result.addOptimization(new LensFlaresOptimization(priority));
  108019. // Next priority
  108020. priority++;
  108021. result.addOptimization(new PostProcessesOptimization(priority));
  108022. result.addOptimization(new ParticlesOptimization(priority));
  108023. // Next priority
  108024. priority++;
  108025. result.addOptimization(new TextureOptimization(priority, 1024));
  108026. return result;
  108027. };
  108028. /**
  108029. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  108030. * @param targetFrameRate defines the target frame rate (60 by default)
  108031. * @returns a SceneOptimizerOptions object
  108032. */
  108033. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  108034. var result = new SceneOptimizerOptions(targetFrameRate);
  108035. var priority = 0;
  108036. result.addOptimization(new MergeMeshesOptimization(priority));
  108037. result.addOptimization(new ShadowsOptimization(priority));
  108038. result.addOptimization(new LensFlaresOptimization(priority));
  108039. // Next priority
  108040. priority++;
  108041. result.addOptimization(new PostProcessesOptimization(priority));
  108042. result.addOptimization(new ParticlesOptimization(priority));
  108043. // Next priority
  108044. priority++;
  108045. result.addOptimization(new TextureOptimization(priority, 512));
  108046. // Next priority
  108047. priority++;
  108048. result.addOptimization(new RenderTargetsOptimization(priority));
  108049. // Next priority
  108050. priority++;
  108051. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  108052. return result;
  108053. };
  108054. /**
  108055. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  108056. * @param targetFrameRate defines the target frame rate (60 by default)
  108057. * @returns a SceneOptimizerOptions object
  108058. */
  108059. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  108060. var result = new SceneOptimizerOptions(targetFrameRate);
  108061. var priority = 0;
  108062. result.addOptimization(new MergeMeshesOptimization(priority));
  108063. result.addOptimization(new ShadowsOptimization(priority));
  108064. result.addOptimization(new LensFlaresOptimization(priority));
  108065. // Next priority
  108066. priority++;
  108067. result.addOptimization(new PostProcessesOptimization(priority));
  108068. result.addOptimization(new ParticlesOptimization(priority));
  108069. // Next priority
  108070. priority++;
  108071. result.addOptimization(new TextureOptimization(priority, 256));
  108072. // Next priority
  108073. priority++;
  108074. result.addOptimization(new RenderTargetsOptimization(priority));
  108075. // Next priority
  108076. priority++;
  108077. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  108078. return result;
  108079. };
  108080. return SceneOptimizerOptions;
  108081. }());
  108082. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  108083. /**
  108084. * Class used to run optimizations in order to reach a target frame rate
  108085. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  108086. */
  108087. var SceneOptimizer = /** @class */ (function () {
  108088. /**
  108089. * Creates a new SceneOptimizer
  108090. * @param scene defines the scene to work on
  108091. * @param options defines the options to use with the SceneOptimizer
  108092. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  108093. * @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)
  108094. */
  108095. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  108096. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  108097. if (improvementMode === void 0) { improvementMode = false; }
  108098. var _this = this;
  108099. this._isRunning = false;
  108100. this._currentPriorityLevel = 0;
  108101. this._targetFrameRate = 60;
  108102. this._trackerDuration = 2000;
  108103. this._currentFrameRate = 0;
  108104. this._improvementMode = false;
  108105. /**
  108106. * Defines an observable called when the optimizer reaches the target frame rate
  108107. */
  108108. this.onSuccessObservable = new BABYLON.Observable();
  108109. /**
  108110. * Defines an observable called when the optimizer enables an optimization
  108111. */
  108112. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  108113. /**
  108114. * Defines an observable called when the optimizer is not able to reach the target frame rate
  108115. */
  108116. this.onFailureObservable = new BABYLON.Observable();
  108117. if (!options) {
  108118. this._options = new SceneOptimizerOptions();
  108119. }
  108120. else {
  108121. this._options = options;
  108122. }
  108123. if (this._options.targetFrameRate) {
  108124. this._targetFrameRate = this._options.targetFrameRate;
  108125. }
  108126. if (this._options.trackerDuration) {
  108127. this._trackerDuration = this._options.trackerDuration;
  108128. }
  108129. if (autoGeneratePriorities) {
  108130. var priority = 0;
  108131. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  108132. var optim = _a[_i];
  108133. optim.priority = priority++;
  108134. }
  108135. }
  108136. this._improvementMode = improvementMode;
  108137. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  108138. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  108139. _this._sceneDisposeObserver = null;
  108140. _this.dispose();
  108141. });
  108142. }
  108143. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  108144. /**
  108145. * Gets a boolean indicating if the optimizer is in improvement mode
  108146. */
  108147. get: function () {
  108148. return this._improvementMode;
  108149. },
  108150. enumerable: true,
  108151. configurable: true
  108152. });
  108153. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  108154. /**
  108155. * Gets the current priority level (0 at start)
  108156. */
  108157. get: function () {
  108158. return this._currentPriorityLevel;
  108159. },
  108160. enumerable: true,
  108161. configurable: true
  108162. });
  108163. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  108164. /**
  108165. * Gets the current frame rate checked by the SceneOptimizer
  108166. */
  108167. get: function () {
  108168. return this._currentFrameRate;
  108169. },
  108170. enumerable: true,
  108171. configurable: true
  108172. });
  108173. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  108174. /**
  108175. * Gets or sets the current target frame rate (60 by default)
  108176. */
  108177. get: function () {
  108178. return this._targetFrameRate;
  108179. },
  108180. /**
  108181. * Gets or sets the current target frame rate (60 by default)
  108182. */
  108183. set: function (value) {
  108184. this._targetFrameRate = value;
  108185. },
  108186. enumerable: true,
  108187. configurable: true
  108188. });
  108189. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  108190. /**
  108191. * Gets or sets the current interval between two checks (every 2000ms by default)
  108192. */
  108193. get: function () {
  108194. return this._trackerDuration;
  108195. },
  108196. /**
  108197. * Gets or sets the current interval between two checks (every 2000ms by default)
  108198. */
  108199. set: function (value) {
  108200. this._trackerDuration = value;
  108201. },
  108202. enumerable: true,
  108203. configurable: true
  108204. });
  108205. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  108206. /**
  108207. * Gets the list of active optimizations
  108208. */
  108209. get: function () {
  108210. return this._options.optimizations;
  108211. },
  108212. enumerable: true,
  108213. configurable: true
  108214. });
  108215. /**
  108216. * Stops the current optimizer
  108217. */
  108218. SceneOptimizer.prototype.stop = function () {
  108219. this._isRunning = false;
  108220. };
  108221. /**
  108222. * Reset the optimizer to initial step (current priority level = 0)
  108223. */
  108224. SceneOptimizer.prototype.reset = function () {
  108225. this._currentPriorityLevel = 0;
  108226. };
  108227. /**
  108228. * Start the optimizer. By default it will try to reach a specific framerate
  108229. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  108230. */
  108231. SceneOptimizer.prototype.start = function () {
  108232. var _this = this;
  108233. if (this._isRunning) {
  108234. return;
  108235. }
  108236. this._isRunning = true;
  108237. // Let's wait for the scene to be ready before running our check
  108238. this._scene.executeWhenReady(function () {
  108239. setTimeout(function () {
  108240. _this._checkCurrentState();
  108241. }, _this._trackerDuration);
  108242. });
  108243. };
  108244. SceneOptimizer.prototype._checkCurrentState = function () {
  108245. var _this = this;
  108246. if (!this._isRunning) {
  108247. return;
  108248. }
  108249. var scene = this._scene;
  108250. var options = this._options;
  108251. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  108252. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  108253. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  108254. this._isRunning = false;
  108255. this.onSuccessObservable.notifyObservers(this);
  108256. return;
  108257. }
  108258. // Apply current level of optimizations
  108259. var allDone = true;
  108260. var noOptimizationApplied = true;
  108261. for (var index = 0; index < options.optimizations.length; index++) {
  108262. var optimization = options.optimizations[index];
  108263. if (optimization.priority === this._currentPriorityLevel) {
  108264. noOptimizationApplied = false;
  108265. allDone = allDone && optimization.apply(scene, this);
  108266. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  108267. }
  108268. }
  108269. // If no optimization was applied, this is a failure :(
  108270. if (noOptimizationApplied) {
  108271. this._isRunning = false;
  108272. this.onFailureObservable.notifyObservers(this);
  108273. return;
  108274. }
  108275. // If all optimizations were done, move to next level
  108276. if (allDone) {
  108277. this._currentPriorityLevel++;
  108278. }
  108279. // Let's the system running for a specific amount of time before checking FPS
  108280. scene.executeWhenReady(function () {
  108281. setTimeout(function () {
  108282. _this._checkCurrentState();
  108283. }, _this._trackerDuration);
  108284. });
  108285. };
  108286. /**
  108287. * Release all resources
  108288. */
  108289. SceneOptimizer.prototype.dispose = function () {
  108290. this.stop();
  108291. this.onSuccessObservable.clear();
  108292. this.onFailureObservable.clear();
  108293. this.onNewOptimizationAppliedObservable.clear();
  108294. if (this._sceneDisposeObserver) {
  108295. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  108296. }
  108297. };
  108298. /**
  108299. * Helper function to create a SceneOptimizer with one single line of code
  108300. * @param scene defines the scene to work on
  108301. * @param options defines the options to use with the SceneOptimizer
  108302. * @param onSuccess defines a callback to call on success
  108303. * @param onFailure defines a callback to call on failure
  108304. * @returns the new SceneOptimizer object
  108305. */
  108306. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  108307. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  108308. if (onSuccess) {
  108309. optimizer.onSuccessObservable.add(function () {
  108310. onSuccess();
  108311. });
  108312. }
  108313. if (onFailure) {
  108314. optimizer.onFailureObservable.add(function () {
  108315. onFailure();
  108316. });
  108317. }
  108318. optimizer.start();
  108319. return optimizer;
  108320. };
  108321. return SceneOptimizer;
  108322. }());
  108323. BABYLON.SceneOptimizer = SceneOptimizer;
  108324. })(BABYLON || (BABYLON = {}));
  108325. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  108326. var BABYLON;
  108327. (function (BABYLON) {
  108328. /**
  108329. * Gets the outline renderer associated with the scene
  108330. * @returns a OutlineRenderer
  108331. */
  108332. BABYLON.Scene.prototype.getOutlineRenderer = function () {
  108333. if (!this._outlineRenderer) {
  108334. this._outlineRenderer = new OutlineRenderer(this);
  108335. }
  108336. return this._outlineRenderer;
  108337. };
  108338. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOutline", {
  108339. get: function () {
  108340. return this._renderOutline;
  108341. },
  108342. set: function (value) {
  108343. if (value) {
  108344. // Lazy Load the component.
  108345. this.getScene().getOutlineRenderer();
  108346. }
  108347. this._renderOutline = value;
  108348. },
  108349. enumerable: true,
  108350. configurable: true
  108351. });
  108352. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOverlay", {
  108353. get: function () {
  108354. return this._renderOverlay;
  108355. },
  108356. set: function (value) {
  108357. if (value) {
  108358. // Lazy Load the component.
  108359. this.getScene().getOutlineRenderer();
  108360. }
  108361. this._renderOverlay = value;
  108362. },
  108363. enumerable: true,
  108364. configurable: true
  108365. });
  108366. /**
  108367. * This class is responsible to draw bothe outline/overlay of meshes.
  108368. * It should not be used directly but through the available method on mesh.
  108369. */
  108370. var OutlineRenderer = /** @class */ (function () {
  108371. /**
  108372. * Instantiates a new outline renderer. (There could be only one per scene).
  108373. * @param scene Defines the scene it belongs to
  108374. */
  108375. function OutlineRenderer(scene) {
  108376. /**
  108377. * The name of the component. Each component must have a unique name.
  108378. */
  108379. this.name = BABYLON.SceneComponentConstants.NAME_OUTLINERENDERER;
  108380. /**
  108381. * Defines a zOffset to prevent zFighting between the overlay and the mesh.
  108382. */
  108383. this.zOffset = 1;
  108384. this.scene = scene;
  108385. this._engine = scene.getEngine();
  108386. this.scene._addComponent(this);
  108387. }
  108388. /**
  108389. * Register the component to one instance of a scene.
  108390. */
  108391. OutlineRenderer.prototype.register = function () {
  108392. this.scene._beforeRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE, this, this._beforeRenderingMesh);
  108393. this.scene._afterRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE, this, this._afterRenderingMesh);
  108394. };
  108395. /**
  108396. * Rebuilds the elements related to this component in case of
  108397. * context lost for instance.
  108398. */
  108399. OutlineRenderer.prototype.rebuild = function () {
  108400. // Nothing to do here.
  108401. };
  108402. /**
  108403. * Disposes the component and the associated ressources.
  108404. */
  108405. OutlineRenderer.prototype.dispose = function () {
  108406. // Nothing to do here.
  108407. };
  108408. /**
  108409. * Renders the outline in the canvas.
  108410. * @param subMesh Defines the sumesh to render
  108411. * @param batch Defines the batch of meshes in case of instances
  108412. * @param useOverlay Defines if the rendering is for the overlay or the outline
  108413. */
  108414. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  108415. var _this = this;
  108416. if (useOverlay === void 0) { useOverlay = false; }
  108417. var scene = this.scene;
  108418. var engine = scene.getEngine();
  108419. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  108420. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  108421. return;
  108422. }
  108423. var mesh = subMesh.getRenderingMesh();
  108424. var material = subMesh.getMaterial();
  108425. if (!material || !scene.activeCamera) {
  108426. return;
  108427. }
  108428. engine.enableEffect(this._effect);
  108429. // Logarithmic depth
  108430. if (material.useLogarithmicDepth) {
  108431. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  108432. }
  108433. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  108434. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  108435. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  108436. // Bones
  108437. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  108438. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  108439. }
  108440. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  108441. // Alpha test
  108442. if (material && material.needAlphaTesting()) {
  108443. var alphaTexture = material.getAlphaTestTexture();
  108444. if (alphaTexture) {
  108445. this._effect.setTexture("diffuseSampler", alphaTexture);
  108446. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  108447. }
  108448. }
  108449. engine.setZOffset(-this.zOffset);
  108450. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  108451. engine.setZOffset(0);
  108452. };
  108453. /**
  108454. * Returns whether or not the outline renderer is ready for a given submesh.
  108455. * All the dependencies e.g. submeshes, texture, effect... mus be ready
  108456. * @param subMesh Defines the submesh to check readyness for
  108457. * @param useInstances Defines wheter wee are trying to render instances or not
  108458. * @returns true if ready otherwise false
  108459. */
  108460. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  108461. var defines = [];
  108462. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  108463. var mesh = subMesh.getMesh();
  108464. var material = subMesh.getMaterial();
  108465. if (material) {
  108466. // Alpha test
  108467. if (material.needAlphaTesting()) {
  108468. defines.push("#define ALPHATEST");
  108469. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  108470. attribs.push(BABYLON.VertexBuffer.UVKind);
  108471. defines.push("#define UV1");
  108472. }
  108473. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  108474. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  108475. defines.push("#define UV2");
  108476. }
  108477. }
  108478. //Logarithmic depth
  108479. if (material.useLogarithmicDepth) {
  108480. defines.push("#define LOGARITHMICDEPTH");
  108481. }
  108482. }
  108483. // Bones
  108484. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  108485. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  108486. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  108487. if (mesh.numBoneInfluencers > 4) {
  108488. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  108489. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  108490. }
  108491. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  108492. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  108493. }
  108494. else {
  108495. defines.push("#define NUM_BONE_INFLUENCERS 0");
  108496. }
  108497. // Instances
  108498. if (useInstances) {
  108499. defines.push("#define INSTANCES");
  108500. attribs.push("world0");
  108501. attribs.push("world1");
  108502. attribs.push("world2");
  108503. attribs.push("world3");
  108504. }
  108505. // Get correct effect
  108506. var join = defines.join("\n");
  108507. if (this._cachedDefines !== join) {
  108508. this._cachedDefines = join;
  108509. this._effect = this.scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  108510. }
  108511. return this._effect.isReady();
  108512. };
  108513. OutlineRenderer.prototype._beforeRenderingMesh = function (mesh, subMesh, batch) {
  108514. // Outline - step 1
  108515. this._savedDepthWrite = this._engine.getDepthWrite();
  108516. if (mesh.renderOutline) {
  108517. this._engine.setDepthWrite(false);
  108518. this.render(subMesh, batch);
  108519. this._engine.setDepthWrite(this._savedDepthWrite);
  108520. }
  108521. };
  108522. OutlineRenderer.prototype._afterRenderingMesh = function (mesh, subMesh, batch) {
  108523. // Outline - step 2
  108524. if (mesh.renderOutline && this._savedDepthWrite) {
  108525. this._engine.setDepthWrite(true);
  108526. this._engine.setColorWrite(false);
  108527. this.render(subMesh, batch);
  108528. this._engine.setColorWrite(true);
  108529. }
  108530. // Overlay
  108531. if (mesh.renderOverlay) {
  108532. var currentMode = this._engine.getAlphaMode();
  108533. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  108534. this.render(subMesh, batch, true);
  108535. this._engine.setAlphaMode(currentMode);
  108536. }
  108537. };
  108538. return OutlineRenderer;
  108539. }());
  108540. BABYLON.OutlineRenderer = OutlineRenderer;
  108541. })(BABYLON || (BABYLON = {}));
  108542. //# sourceMappingURL=babylon.outlineRenderer.js.map
  108543. var BABYLON;
  108544. (function (BABYLON) {
  108545. BABYLON.AbstractMesh.prototype.disableEdgesRendering = function () {
  108546. if (this._edgesRenderer) {
  108547. this._edgesRenderer.dispose();
  108548. this._edgesRenderer = null;
  108549. }
  108550. return this;
  108551. };
  108552. BABYLON.AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  108553. if (epsilon === void 0) { epsilon = 0.95; }
  108554. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  108555. this.disableEdgesRendering();
  108556. this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  108557. return this;
  108558. };
  108559. Object.defineProperty(BABYLON.AbstractMesh.prototype, "edgesRenderer", {
  108560. get: function () {
  108561. return this._edgesRenderer;
  108562. },
  108563. enumerable: true,
  108564. configurable: true
  108565. });
  108566. BABYLON.LinesMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  108567. if (epsilon === void 0) { epsilon = 0.95; }
  108568. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  108569. this.disableEdgesRendering();
  108570. this._edgesRenderer = new BABYLON.LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  108571. return this;
  108572. };
  108573. /**
  108574. * FaceAdjacencies Helper class to generate edges
  108575. */
  108576. var FaceAdjacencies = /** @class */ (function () {
  108577. function FaceAdjacencies() {
  108578. this.edges = new Array();
  108579. this.edgesConnectedCount = 0;
  108580. }
  108581. return FaceAdjacencies;
  108582. }());
  108583. /**
  108584. * This class is used to generate edges of the mesh that could then easily be rendered in a scene.
  108585. */
  108586. var EdgesRenderer = /** @class */ (function () {
  108587. /**
  108588. * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh.
  108589. * Beware when you use this class with complex objects as the adjacencies computation can be really long
  108590. * @param source Mesh used to create edges
  108591. * @param epsilon sum of angles in adjacency to check for edge
  108592. * @param checkVerticesInsteadOfIndices
  108593. * @param generateEdgesLines - should generate Lines or only prepare resources.
  108594. */
  108595. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices, generateEdgesLines) {
  108596. if (epsilon === void 0) { epsilon = 0.95; }
  108597. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  108598. if (generateEdgesLines === void 0) { generateEdgesLines = true; }
  108599. var _this = this;
  108600. /**
  108601. * Define the size of the edges with an orthographic camera
  108602. */
  108603. this.edgesWidthScalerForOrthographic = 1000.0;
  108604. /**
  108605. * Define the size of the edges with a perspective camera
  108606. */
  108607. this.edgesWidthScalerForPerspective = 50.0;
  108608. this._linesPositions = new Array();
  108609. this._linesNormals = new Array();
  108610. this._linesIndices = new Array();
  108611. this._buffers = {};
  108612. this._checkVerticesInsteadOfIndices = false;
  108613. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  108614. this.isEnabled = true;
  108615. this._source = source;
  108616. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  108617. this._epsilon = epsilon;
  108618. this._prepareRessources();
  108619. if (generateEdgesLines) {
  108620. this._generateEdgesLines();
  108621. }
  108622. this._meshRebuildObserver = this._source.onRebuildObservable.add(function () {
  108623. _this._rebuild();
  108624. });
  108625. this._meshDisposeObserver = this._source.onDisposeObservable.add(function () {
  108626. _this.dispose();
  108627. });
  108628. }
  108629. EdgesRenderer.prototype._prepareRessources = function () {
  108630. if (this._lineShader) {
  108631. return;
  108632. }
  108633. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  108634. attributes: ["position", "normal"],
  108635. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  108636. });
  108637. this._lineShader.disableDepthWrite = true;
  108638. this._lineShader.backFaceCulling = false;
  108639. };
  108640. /** @hidden */
  108641. EdgesRenderer.prototype._rebuild = function () {
  108642. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  108643. if (buffer) {
  108644. buffer._rebuild();
  108645. }
  108646. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  108647. if (buffer) {
  108648. buffer._rebuild();
  108649. }
  108650. var scene = this._source.getScene();
  108651. var engine = scene.getEngine();
  108652. this._ib = engine.createIndexBuffer(this._linesIndices);
  108653. };
  108654. /**
  108655. * Releases the required resources for the edges renderer
  108656. */
  108657. EdgesRenderer.prototype.dispose = function () {
  108658. this._source.onRebuildObservable.remove(this._meshRebuildObserver);
  108659. this._source.onDisposeObservable.remove(this._meshDisposeObserver);
  108660. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  108661. if (buffer) {
  108662. buffer.dispose();
  108663. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  108664. }
  108665. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  108666. if (buffer) {
  108667. buffer.dispose();
  108668. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  108669. }
  108670. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  108671. this._lineShader.dispose();
  108672. };
  108673. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  108674. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  108675. return 0;
  108676. }
  108677. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  108678. return 1;
  108679. }
  108680. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  108681. return 2;
  108682. }
  108683. return -1;
  108684. };
  108685. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  108686. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  108687. return 0;
  108688. }
  108689. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  108690. return 1;
  108691. }
  108692. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  108693. return 2;
  108694. }
  108695. return -1;
  108696. };
  108697. /**
  108698. * Checks if the pair of p0 and p1 is en edge
  108699. * @param faceIndex
  108700. * @param edge
  108701. * @param faceNormals
  108702. * @param p0
  108703. * @param p1
  108704. * @private
  108705. */
  108706. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  108707. var needToCreateLine;
  108708. if (edge === undefined) {
  108709. needToCreateLine = true;
  108710. }
  108711. else {
  108712. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  108713. needToCreateLine = dotProduct < this._epsilon;
  108714. }
  108715. if (needToCreateLine) {
  108716. var offset = this._linesPositions.length / 3;
  108717. var normal = p0.subtract(p1);
  108718. normal.normalize();
  108719. // Positions
  108720. this._linesPositions.push(p0.x);
  108721. this._linesPositions.push(p0.y);
  108722. this._linesPositions.push(p0.z);
  108723. this._linesPositions.push(p0.x);
  108724. this._linesPositions.push(p0.y);
  108725. this._linesPositions.push(p0.z);
  108726. this._linesPositions.push(p1.x);
  108727. this._linesPositions.push(p1.y);
  108728. this._linesPositions.push(p1.z);
  108729. this._linesPositions.push(p1.x);
  108730. this._linesPositions.push(p1.y);
  108731. this._linesPositions.push(p1.z);
  108732. // Normals
  108733. this._linesNormals.push(p1.x);
  108734. this._linesNormals.push(p1.y);
  108735. this._linesNormals.push(p1.z);
  108736. this._linesNormals.push(-1);
  108737. this._linesNormals.push(p1.x);
  108738. this._linesNormals.push(p1.y);
  108739. this._linesNormals.push(p1.z);
  108740. this._linesNormals.push(1);
  108741. this._linesNormals.push(p0.x);
  108742. this._linesNormals.push(p0.y);
  108743. this._linesNormals.push(p0.z);
  108744. this._linesNormals.push(-1);
  108745. this._linesNormals.push(p0.x);
  108746. this._linesNormals.push(p0.y);
  108747. this._linesNormals.push(p0.z);
  108748. this._linesNormals.push(1);
  108749. // Indices
  108750. this._linesIndices.push(offset);
  108751. this._linesIndices.push(offset + 1);
  108752. this._linesIndices.push(offset + 2);
  108753. this._linesIndices.push(offset);
  108754. this._linesIndices.push(offset + 2);
  108755. this._linesIndices.push(offset + 3);
  108756. }
  108757. };
  108758. /**
  108759. * Generates lines edges from adjacencjes
  108760. * @private
  108761. */
  108762. EdgesRenderer.prototype._generateEdgesLines = function () {
  108763. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  108764. var indices = this._source.getIndices();
  108765. if (!indices || !positions) {
  108766. return;
  108767. }
  108768. // First let's find adjacencies
  108769. var adjacencies = new Array();
  108770. var faceNormals = new Array();
  108771. var index;
  108772. var faceAdjacencies;
  108773. // Prepare faces
  108774. for (index = 0; index < indices.length; index += 3) {
  108775. faceAdjacencies = new FaceAdjacencies();
  108776. var p0Index = indices[index];
  108777. var p1Index = indices[index + 1];
  108778. var p2Index = indices[index + 2];
  108779. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  108780. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  108781. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  108782. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  108783. faceNormal.normalize();
  108784. faceNormals.push(faceNormal);
  108785. adjacencies.push(faceAdjacencies);
  108786. }
  108787. // Scan
  108788. for (index = 0; index < adjacencies.length; index++) {
  108789. faceAdjacencies = adjacencies[index];
  108790. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  108791. var otherFaceAdjacencies = adjacencies[otherIndex];
  108792. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  108793. break;
  108794. }
  108795. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  108796. continue;
  108797. }
  108798. var otherP0 = indices[otherIndex * 3];
  108799. var otherP1 = indices[otherIndex * 3 + 1];
  108800. var otherP2 = indices[otherIndex * 3 + 2];
  108801. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  108802. var otherEdgeIndex = 0;
  108803. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  108804. continue;
  108805. }
  108806. switch (edgeIndex) {
  108807. case 0:
  108808. if (this._checkVerticesInsteadOfIndices) {
  108809. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  108810. }
  108811. else {
  108812. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  108813. }
  108814. break;
  108815. case 1:
  108816. if (this._checkVerticesInsteadOfIndices) {
  108817. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  108818. }
  108819. else {
  108820. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  108821. }
  108822. break;
  108823. case 2:
  108824. if (this._checkVerticesInsteadOfIndices) {
  108825. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  108826. }
  108827. else {
  108828. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  108829. }
  108830. break;
  108831. }
  108832. if (otherEdgeIndex === -1) {
  108833. continue;
  108834. }
  108835. faceAdjacencies.edges[edgeIndex] = otherIndex;
  108836. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  108837. faceAdjacencies.edgesConnectedCount++;
  108838. otherFaceAdjacencies.edgesConnectedCount++;
  108839. if (faceAdjacencies.edgesConnectedCount === 3) {
  108840. break;
  108841. }
  108842. }
  108843. }
  108844. }
  108845. // Create lines
  108846. for (index = 0; index < adjacencies.length; index++) {
  108847. // 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
  108848. var current = adjacencies[index];
  108849. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  108850. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  108851. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  108852. }
  108853. // Merge into a single mesh
  108854. var engine = this._source.getScene().getEngine();
  108855. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  108856. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  108857. this._ib = engine.createIndexBuffer(this._linesIndices);
  108858. this._indicesCount = this._linesIndices.length;
  108859. };
  108860. /**
  108861. * Checks wether or not the edges renderer is ready to render.
  108862. * @return true if ready, otherwise false.
  108863. */
  108864. EdgesRenderer.prototype.isReady = function () {
  108865. return this._lineShader.isReady();
  108866. };
  108867. /**
  108868. * Renders the edges of the attached mesh,
  108869. */
  108870. EdgesRenderer.prototype.render = function () {
  108871. var scene = this._source.getScene();
  108872. if (!this.isReady() || !scene.activeCamera) {
  108873. return;
  108874. }
  108875. var engine = scene.getEngine();
  108876. this._lineShader._preBind();
  108877. if (this._source.edgesColor.a !== 1) {
  108878. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  108879. }
  108880. else {
  108881. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  108882. }
  108883. // VBOs
  108884. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  108885. scene.resetCachedMaterial();
  108886. this._lineShader.setColor4("color", this._source.edgesColor);
  108887. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  108888. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  108889. }
  108890. else {
  108891. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  108892. }
  108893. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  108894. this._lineShader.bind(this._source.getWorldMatrix());
  108895. // Draw order
  108896. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  108897. this._lineShader.unbind();
  108898. };
  108899. return EdgesRenderer;
  108900. }());
  108901. BABYLON.EdgesRenderer = EdgesRenderer;
  108902. })(BABYLON || (BABYLON = {}));
  108903. //# sourceMappingURL=babylon.edgesRenderer.js.map
  108904. var BABYLON;
  108905. (function (BABYLON) {
  108906. /**
  108907. * FaceAdjacencies Helper class to generate edges
  108908. */
  108909. var FaceAdjacencies = /** @class */ (function () {
  108910. function FaceAdjacencies() {
  108911. this.edges = new Array();
  108912. this.edgesConnectedCount = 0;
  108913. }
  108914. return FaceAdjacencies;
  108915. }());
  108916. /**
  108917. * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation
  108918. */
  108919. var LineEdgesRenderer = /** @class */ (function (_super) {
  108920. __extends(LineEdgesRenderer, _super);
  108921. /**
  108922. * This constructor turns off auto generating edges line in Edges Renderer to make it here.
  108923. * @param source LineMesh used to generate edges
  108924. * @param epsilon not important (specified angle for edge detection)
  108925. * @param checkVerticesInsteadOfIndices not important for LineMesh
  108926. */
  108927. function LineEdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  108928. if (epsilon === void 0) { epsilon = 0.95; }
  108929. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  108930. var _this = _super.call(this, source, epsilon, checkVerticesInsteadOfIndices, false) || this;
  108931. _this._generateEdgesLines();
  108932. return _this;
  108933. }
  108934. /**
  108935. * Always create the edge since its a line so only important things are p0 and p1
  108936. * @param faceIndex not important for LineMesh
  108937. * @param edge not important for LineMesh
  108938. * @param faceNormals not important for LineMesh
  108939. * @param p0 beginnig of line
  108940. * @param p1 end of line
  108941. */
  108942. LineEdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  108943. var offset = this._linesPositions.length / 3;
  108944. var normal = p0.subtract(p1);
  108945. normal.normalize();
  108946. // Positions
  108947. this._linesPositions.push(p0.x);
  108948. this._linesPositions.push(p0.y);
  108949. this._linesPositions.push(p0.z);
  108950. this._linesPositions.push(p0.x);
  108951. this._linesPositions.push(p0.y);
  108952. this._linesPositions.push(p0.z);
  108953. this._linesPositions.push(p1.x);
  108954. this._linesPositions.push(p1.y);
  108955. this._linesPositions.push(p1.z);
  108956. this._linesPositions.push(p1.x);
  108957. this._linesPositions.push(p1.y);
  108958. this._linesPositions.push(p1.z);
  108959. // Normals
  108960. this._linesNormals.push(p1.x);
  108961. this._linesNormals.push(p1.y);
  108962. this._linesNormals.push(p1.z);
  108963. this._linesNormals.push(-1);
  108964. this._linesNormals.push(p1.x);
  108965. this._linesNormals.push(p1.y);
  108966. this._linesNormals.push(p1.z);
  108967. this._linesNormals.push(1);
  108968. this._linesNormals.push(p0.x);
  108969. this._linesNormals.push(p0.y);
  108970. this._linesNormals.push(p0.z);
  108971. this._linesNormals.push(-1);
  108972. this._linesNormals.push(p0.x);
  108973. this._linesNormals.push(p0.y);
  108974. this._linesNormals.push(p0.z);
  108975. this._linesNormals.push(1);
  108976. // Indices
  108977. this._linesIndices.push(offset);
  108978. this._linesIndices.push(offset + 1);
  108979. this._linesIndices.push(offset + 2);
  108980. this._linesIndices.push(offset);
  108981. this._linesIndices.push(offset + 2);
  108982. this._linesIndices.push(offset + 3);
  108983. };
  108984. /**
  108985. * Generate edges for each line in LinesMesh. Every Line should be rendered as edge.
  108986. */
  108987. LineEdgesRenderer.prototype._generateEdgesLines = function () {
  108988. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  108989. var indices = this._source.getIndices();
  108990. if (!indices || !positions) {
  108991. return;
  108992. }
  108993. // First let's find adjacencies
  108994. var adjacencies = new Array();
  108995. var faceNormals = new Array();
  108996. var index;
  108997. for (var i = 0; i < (positions.length / 3) - 1; i++) {
  108998. var currentAdjecancy = new FaceAdjacencies();
  108999. currentAdjecancy.p0 = new BABYLON.Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
  109000. currentAdjecancy.p1 = new BABYLON.Vector3(positions[(i + 1) * 3], positions[(i + 1) * 3 + 1], positions[(i + 1) * 3 + 2]);
  109001. adjacencies.push(currentAdjecancy);
  109002. }
  109003. // Create lines
  109004. for (index = 0; index < adjacencies.length; index++) {
  109005. // 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
  109006. var current = adjacencies[index];
  109007. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  109008. }
  109009. // Merge into a single mesh
  109010. var engine = this._source.getScene().getEngine();
  109011. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  109012. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  109013. this._ib = engine.createIndexBuffer(this._linesIndices);
  109014. this._indicesCount = this._linesIndices.length;
  109015. };
  109016. return LineEdgesRenderer;
  109017. }(BABYLON.EdgesRenderer));
  109018. BABYLON.LineEdgesRenderer = LineEdgesRenderer;
  109019. })(BABYLON || (BABYLON = {}));
  109020. //# sourceMappingURL=babylon.lineEdgesRenderer.js.map
  109021. var BABYLON;
  109022. (function (BABYLON) {
  109023. // Adds the parser to the scene parsers.
  109024. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  109025. if (parsedData.effectLayers) {
  109026. if (!container.effectLayers) {
  109027. container.effectLayers = new Array();
  109028. }
  109029. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  109030. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  109031. container.effectLayers.push(effectLayer);
  109032. }
  109033. }
  109034. });
  109035. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  109036. var index = this.effectLayers.indexOf(toRemove);
  109037. if (index !== -1) {
  109038. this.effectLayers.splice(index, 1);
  109039. }
  109040. return index;
  109041. };
  109042. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  109043. this.effectLayers.push(newEffectLayer);
  109044. };
  109045. /**
  109046. * Defines the layer scene component responsible to manage any effect layers
  109047. * in a given scene.
  109048. */
  109049. var EffectLayerSceneComponent = /** @class */ (function () {
  109050. /**
  109051. * Creates a new instance of the component for the given scene
  109052. * @param scene Defines the scene to register the component in
  109053. */
  109054. function EffectLayerSceneComponent(scene) {
  109055. /**
  109056. * The component name helpfull to identify the component in the list of scene components.
  109057. */
  109058. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  109059. this._renderEffects = false;
  109060. this._needStencil = false;
  109061. this._previousStencilState = false;
  109062. this.scene = scene;
  109063. this._engine = scene.getEngine();
  109064. scene.effectLayers = new Array();
  109065. }
  109066. /**
  109067. * Registers the component in a given scene
  109068. */
  109069. EffectLayerSceneComponent.prototype.register = function () {
  109070. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  109071. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  109072. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  109073. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  109074. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  109075. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  109076. };
  109077. /**
  109078. * Rebuilds the elements related to this component in case of
  109079. * context lost for instance.
  109080. */
  109081. EffectLayerSceneComponent.prototype.rebuild = function () {
  109082. var layers = this.scene.effectLayers;
  109083. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  109084. var effectLayer = layers_1[_i];
  109085. effectLayer._rebuild();
  109086. }
  109087. };
  109088. /**
  109089. * Serializes the component data to the specified json object
  109090. * @param serializationObject The object to serialize to
  109091. */
  109092. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  109093. // Effect layers
  109094. serializationObject.effectLayers = [];
  109095. var layers = this.scene.effectLayers;
  109096. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  109097. var effectLayer = layers_2[_i];
  109098. if (effectLayer.serialize) {
  109099. serializationObject.effectLayers.push(effectLayer.serialize());
  109100. }
  109101. }
  109102. };
  109103. /**
  109104. * Adds all the element from the container to the scene
  109105. * @param container the container holding the elements
  109106. */
  109107. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  109108. var _this = this;
  109109. if (!container.effectLayers) {
  109110. return;
  109111. }
  109112. container.effectLayers.forEach(function (o) {
  109113. _this.scene.addEffectLayer(o);
  109114. });
  109115. };
  109116. /**
  109117. * Removes all the elements in the container from the scene
  109118. * @param container contains the elements to remove
  109119. */
  109120. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  109121. var _this = this;
  109122. if (!container.effectLayers) {
  109123. return;
  109124. }
  109125. container.effectLayers.forEach(function (o) {
  109126. _this.scene.removeEffectLayer(o);
  109127. });
  109128. };
  109129. /**
  109130. * Disposes the component and the associated ressources.
  109131. */
  109132. EffectLayerSceneComponent.prototype.dispose = function () {
  109133. var layers = this.scene.effectLayers;
  109134. while (layers.length) {
  109135. layers[0].dispose();
  109136. }
  109137. };
  109138. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  109139. var layers = this.scene.effectLayers;
  109140. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  109141. var layer = layers_3[_i];
  109142. if (!layer.hasMesh(mesh)) {
  109143. continue;
  109144. }
  109145. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  109146. var subMesh = _b[_a];
  109147. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  109148. return false;
  109149. }
  109150. }
  109151. }
  109152. return true;
  109153. };
  109154. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  109155. this._renderEffects = false;
  109156. this._needStencil = false;
  109157. var layers = this.scene.effectLayers;
  109158. if (layers && layers.length > 0) {
  109159. this._previousStencilState = this._engine.getStencilBuffer();
  109160. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  109161. var effectLayer = layers_4[_i];
  109162. if (effectLayer.shouldRender() &&
  109163. (!effectLayer.camera ||
  109164. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  109165. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  109166. this._renderEffects = true;
  109167. this._needStencil = this._needStencil || effectLayer.needStencil();
  109168. var renderTarget = effectLayer._mainTexture;
  109169. if (renderTarget._shouldRender()) {
  109170. this.scene.incrementRenderId();
  109171. renderTarget.render(false, false);
  109172. }
  109173. }
  109174. }
  109175. this.scene.incrementRenderId();
  109176. }
  109177. };
  109178. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  109179. // Activate effect Layer stencil
  109180. if (this._needStencil) {
  109181. this._engine.setStencilBuffer(true);
  109182. }
  109183. };
  109184. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  109185. // Restore effect Layer stencil
  109186. if (this._needStencil) {
  109187. this._engine.setStencilBuffer(this._previousStencilState);
  109188. }
  109189. };
  109190. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  109191. if (this._renderEffects) {
  109192. this._engine.setDepthBuffer(false);
  109193. var layers = this.scene.effectLayers;
  109194. for (var i = 0; i < layers.length; i++) {
  109195. var effectLayer = layers[i];
  109196. if (effectLayer.renderingGroupId === renderingGroupId) {
  109197. if (effectLayer.shouldRender()) {
  109198. effectLayer.render();
  109199. }
  109200. }
  109201. }
  109202. this._engine.setDepthBuffer(true);
  109203. }
  109204. };
  109205. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  109206. if (this._renderEffects) {
  109207. this._draw(-1);
  109208. }
  109209. };
  109210. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  109211. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  109212. this._draw(index);
  109213. }
  109214. };
  109215. return EffectLayerSceneComponent;
  109216. }());
  109217. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  109218. })(BABYLON || (BABYLON = {}));
  109219. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  109220. var __assign = (this && this.__assign) || function () {
  109221. __assign = Object.assign || function(t) {
  109222. for (var s, i = 1, n = arguments.length; i < n; i++) {
  109223. s = arguments[i];
  109224. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  109225. t[p] = s[p];
  109226. }
  109227. return t;
  109228. };
  109229. return __assign.apply(this, arguments);
  109230. };
  109231. var BABYLON;
  109232. (function (BABYLON) {
  109233. /**
  109234. * The effect layer Helps adding post process effect blended with the main pass.
  109235. *
  109236. * This can be for instance use to generate glow or higlight effects on the scene.
  109237. *
  109238. * The effect layer class can not be used directly and is intented to inherited from to be
  109239. * customized per effects.
  109240. */
  109241. var EffectLayer = /** @class */ (function () {
  109242. /**
  109243. * Instantiates a new effect Layer and references it in the scene.
  109244. * @param name The name of the layer
  109245. * @param scene The scene to use the layer in
  109246. */
  109247. function EffectLayer(
  109248. /** The Friendly of the effect in the scene */
  109249. name, scene) {
  109250. this._vertexBuffers = {};
  109251. this._maxSize = 0;
  109252. this._mainTextureDesiredSize = { width: 0, height: 0 };
  109253. this._shouldRender = true;
  109254. this._postProcesses = [];
  109255. this._textures = [];
  109256. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  109257. /**
  109258. * The clear color of the texture used to generate the glow map.
  109259. */
  109260. this.neutralColor = new BABYLON.Color4();
  109261. /**
  109262. * Specifies wether the highlight layer is enabled or not.
  109263. */
  109264. this.isEnabled = true;
  109265. /**
  109266. * An event triggered when the effect layer has been disposed.
  109267. */
  109268. this.onDisposeObservable = new BABYLON.Observable();
  109269. /**
  109270. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  109271. */
  109272. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  109273. /**
  109274. * An event triggered when the generated texture is being merged in the scene.
  109275. */
  109276. this.onBeforeComposeObservable = new BABYLON.Observable();
  109277. /**
  109278. * An event triggered when the generated texture has been merged in the scene.
  109279. */
  109280. this.onAfterComposeObservable = new BABYLON.Observable();
  109281. /**
  109282. * An event triggered when the efffect layer changes its size.
  109283. */
  109284. this.onSizeChangedObservable = new BABYLON.Observable();
  109285. this.name = name;
  109286. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  109287. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  109288. if (!component) {
  109289. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  109290. this._scene._addComponent(component);
  109291. }
  109292. this._engine = this._scene.getEngine();
  109293. this._maxSize = this._engine.getCaps().maxTextureSize;
  109294. this._scene.effectLayers.push(this);
  109295. // Generate Buffers
  109296. this._generateIndexBuffer();
  109297. this._genrateVertexBuffer();
  109298. }
  109299. Object.defineProperty(EffectLayer.prototype, "camera", {
  109300. /**
  109301. * Gets the camera attached to the layer.
  109302. */
  109303. get: function () {
  109304. return this._effectLayerOptions.camera;
  109305. },
  109306. enumerable: true,
  109307. configurable: true
  109308. });
  109309. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  109310. /**
  109311. * Gets the rendering group id the layer should render in.
  109312. */
  109313. get: function () {
  109314. return this._effectLayerOptions.renderingGroupId;
  109315. },
  109316. enumerable: true,
  109317. configurable: true
  109318. });
  109319. /**
  109320. * Initializes the effect layer with the required options.
  109321. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  109322. */
  109323. EffectLayer.prototype._init = function (options) {
  109324. // Adapt options
  109325. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  109326. this._setMainTextureSize();
  109327. this._createMainTexture();
  109328. this._createTextureAndPostProcesses();
  109329. this._mergeEffect = this._createMergeEffect();
  109330. };
  109331. /**
  109332. * Generates the index buffer of the full screen quad blending to the main canvas.
  109333. */
  109334. EffectLayer.prototype._generateIndexBuffer = function () {
  109335. // Indices
  109336. var indices = [];
  109337. indices.push(0);
  109338. indices.push(1);
  109339. indices.push(2);
  109340. indices.push(0);
  109341. indices.push(2);
  109342. indices.push(3);
  109343. this._indexBuffer = this._engine.createIndexBuffer(indices);
  109344. };
  109345. /**
  109346. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  109347. */
  109348. EffectLayer.prototype._genrateVertexBuffer = function () {
  109349. // VBO
  109350. var vertices = [];
  109351. vertices.push(1, 1);
  109352. vertices.push(-1, 1);
  109353. vertices.push(-1, -1);
  109354. vertices.push(1, -1);
  109355. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  109356. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  109357. };
  109358. /**
  109359. * Sets the main texture desired size which is the closest power of two
  109360. * of the engine canvas size.
  109361. */
  109362. EffectLayer.prototype._setMainTextureSize = function () {
  109363. if (this._effectLayerOptions.mainTextureFixedSize) {
  109364. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  109365. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  109366. }
  109367. else {
  109368. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  109369. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  109370. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  109371. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  109372. }
  109373. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  109374. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  109375. };
  109376. /**
  109377. * Creates the main texture for the effect layer.
  109378. */
  109379. EffectLayer.prototype._createMainTexture = function () {
  109380. var _this = this;
  109381. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  109382. width: this._mainTextureDesiredSize.width,
  109383. height: this._mainTextureDesiredSize.height
  109384. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  109385. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  109386. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109387. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109388. this._mainTexture.anisotropicFilteringLevel = 1;
  109389. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  109390. this._mainTexture.renderParticles = false;
  109391. this._mainTexture.renderList = null;
  109392. this._mainTexture.ignoreCameraViewport = true;
  109393. // Custom render function
  109394. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  109395. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  109396. var index;
  109397. var engine = _this._scene.getEngine();
  109398. if (depthOnlySubMeshes.length) {
  109399. engine.setColorWrite(false);
  109400. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  109401. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  109402. }
  109403. engine.setColorWrite(true);
  109404. }
  109405. for (index = 0; index < opaqueSubMeshes.length; index++) {
  109406. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  109407. }
  109408. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  109409. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  109410. }
  109411. for (index = 0; index < transparentSubMeshes.length; index++) {
  109412. _this._renderSubMesh(transparentSubMeshes.data[index]);
  109413. }
  109414. };
  109415. this._mainTexture.onClearObservable.add(function (engine) {
  109416. engine.clear(_this.neutralColor, true, true, true);
  109417. });
  109418. };
  109419. /**
  109420. * Checks for the readiness of the element composing the layer.
  109421. * @param subMesh the mesh to check for
  109422. * @param useInstances specify wether or not to use instances to render the mesh
  109423. * @param emissiveTexture the associated emissive texture used to generate the glow
  109424. * @return true if ready otherwise, false
  109425. */
  109426. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  109427. var material = subMesh.getMaterial();
  109428. if (!material) {
  109429. return false;
  109430. }
  109431. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  109432. return false;
  109433. }
  109434. var defines = [];
  109435. var attribs = [BABYLON.VertexBuffer.PositionKind];
  109436. var mesh = subMesh.getMesh();
  109437. var uv1 = false;
  109438. var uv2 = false;
  109439. // Alpha test
  109440. if (material && material.needAlphaTesting()) {
  109441. var alphaTexture = material.getAlphaTestTexture();
  109442. if (alphaTexture) {
  109443. defines.push("#define ALPHATEST");
  109444. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  109445. alphaTexture.coordinatesIndex === 1) {
  109446. defines.push("#define DIFFUSEUV2");
  109447. uv2 = true;
  109448. }
  109449. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  109450. defines.push("#define DIFFUSEUV1");
  109451. uv1 = true;
  109452. }
  109453. }
  109454. }
  109455. // Emissive
  109456. if (emissiveTexture) {
  109457. defines.push("#define EMISSIVE");
  109458. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  109459. emissiveTexture.coordinatesIndex === 1) {
  109460. defines.push("#define EMISSIVEUV2");
  109461. uv2 = true;
  109462. }
  109463. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  109464. defines.push("#define EMISSIVEUV1");
  109465. uv1 = true;
  109466. }
  109467. }
  109468. if (uv1) {
  109469. attribs.push(BABYLON.VertexBuffer.UVKind);
  109470. defines.push("#define UV1");
  109471. }
  109472. if (uv2) {
  109473. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  109474. defines.push("#define UV2");
  109475. }
  109476. // Bones
  109477. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  109478. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  109479. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  109480. if (mesh.numBoneInfluencers > 4) {
  109481. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  109482. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  109483. }
  109484. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  109485. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  109486. }
  109487. else {
  109488. defines.push("#define NUM_BONE_INFLUENCERS 0");
  109489. }
  109490. // Morph targets
  109491. var manager = mesh.morphTargetManager;
  109492. var morphInfluencers = 0;
  109493. if (manager) {
  109494. if (manager.numInfluencers > 0) {
  109495. defines.push("#define MORPHTARGETS");
  109496. morphInfluencers = manager.numInfluencers;
  109497. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  109498. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  109499. }
  109500. }
  109501. // Instances
  109502. if (useInstances) {
  109503. defines.push("#define INSTANCES");
  109504. attribs.push("world0");
  109505. attribs.push("world1");
  109506. attribs.push("world2");
  109507. attribs.push("world3");
  109508. }
  109509. // Get correct effect
  109510. var join = defines.join("\n");
  109511. if (this._cachedDefines !== join) {
  109512. this._cachedDefines = join;
  109513. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  109514. }
  109515. return this._effectLayerMapGenerationEffect.isReady();
  109516. };
  109517. /**
  109518. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  109519. */
  109520. EffectLayer.prototype.render = function () {
  109521. var currentEffect = this._mergeEffect;
  109522. // Check
  109523. if (!currentEffect.isReady()) {
  109524. return;
  109525. }
  109526. for (var i = 0; i < this._postProcesses.length; i++) {
  109527. if (!this._postProcesses[i].isReady()) {
  109528. return;
  109529. }
  109530. }
  109531. var engine = this._scene.getEngine();
  109532. this.onBeforeComposeObservable.notifyObservers(this);
  109533. // Render
  109534. engine.enableEffect(currentEffect);
  109535. engine.setState(false);
  109536. // VBOs
  109537. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  109538. // Cache
  109539. var previousAlphaMode = engine.getAlphaMode();
  109540. // Go Blend.
  109541. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  109542. // Blends the map on the main canvas.
  109543. this._internalRender(currentEffect);
  109544. // Restore Alpha
  109545. engine.setAlphaMode(previousAlphaMode);
  109546. this.onAfterComposeObservable.notifyObservers(this);
  109547. // Handle size changes.
  109548. var size = this._mainTexture.getSize();
  109549. this._setMainTextureSize();
  109550. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  109551. // Recreate RTT and post processes on size change.
  109552. this.onSizeChangedObservable.notifyObservers(this);
  109553. this._disposeTextureAndPostProcesses();
  109554. this._createMainTexture();
  109555. this._createTextureAndPostProcesses();
  109556. }
  109557. };
  109558. /**
  109559. * Determine if a given mesh will be used in the current effect.
  109560. * @param mesh mesh to test
  109561. * @returns true if the mesh will be used
  109562. */
  109563. EffectLayer.prototype.hasMesh = function (mesh) {
  109564. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  109565. return true;
  109566. }
  109567. return false;
  109568. };
  109569. /**
  109570. * Returns true if the layer contains information to display, otherwise false.
  109571. * @returns true if the glow layer should be rendered
  109572. */
  109573. EffectLayer.prototype.shouldRender = function () {
  109574. return this.isEnabled && this._shouldRender;
  109575. };
  109576. /**
  109577. * Returns true if the mesh should render, otherwise false.
  109578. * @param mesh The mesh to render
  109579. * @returns true if it should render otherwise false
  109580. */
  109581. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  109582. return true;
  109583. };
  109584. /**
  109585. * Returns true if the mesh should render, otherwise false.
  109586. * @param mesh The mesh to render
  109587. * @returns true if it should render otherwise false
  109588. */
  109589. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  109590. return true;
  109591. };
  109592. /**
  109593. * Renders the submesh passed in parameter to the generation map.
  109594. */
  109595. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  109596. var _this = this;
  109597. if (!this.shouldRender()) {
  109598. return;
  109599. }
  109600. var material = subMesh.getMaterial();
  109601. var mesh = subMesh.getRenderingMesh();
  109602. var scene = this._scene;
  109603. var engine = scene.getEngine();
  109604. if (!material) {
  109605. return;
  109606. }
  109607. // Do not block in blend mode.
  109608. if (material.needAlphaBlendingForMesh(mesh)) {
  109609. return;
  109610. }
  109611. // Culling
  109612. engine.setState(material.backFaceCulling);
  109613. // Managing instances
  109614. var batch = mesh._getInstancesRenderList(subMesh._id);
  109615. if (batch.mustReturn) {
  109616. return;
  109617. }
  109618. // Early Exit per mesh
  109619. if (!this._shouldRenderMesh(mesh)) {
  109620. return;
  109621. }
  109622. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  109623. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  109624. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  109625. engine.enableEffect(this._effectLayerMapGenerationEffect);
  109626. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  109627. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  109628. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  109629. // Alpha test
  109630. if (material && material.needAlphaTesting()) {
  109631. var alphaTexture = material.getAlphaTestTexture();
  109632. if (alphaTexture) {
  109633. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  109634. var textureMatrix = alphaTexture.getTextureMatrix();
  109635. if (textureMatrix) {
  109636. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  109637. }
  109638. }
  109639. }
  109640. // Glow emissive only
  109641. if (this._emissiveTextureAndColor.texture) {
  109642. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  109643. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  109644. }
  109645. // Bones
  109646. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  109647. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  109648. }
  109649. // Morph targets
  109650. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  109651. // Draw
  109652. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  109653. }
  109654. else {
  109655. // Need to reset refresh rate of the main map
  109656. this._mainTexture.resetRefreshCounter();
  109657. }
  109658. };
  109659. /**
  109660. * Rebuild the required buffers.
  109661. * @hidden Internal use only.
  109662. */
  109663. EffectLayer.prototype._rebuild = function () {
  109664. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  109665. if (vb) {
  109666. vb._rebuild();
  109667. }
  109668. this._generateIndexBuffer();
  109669. };
  109670. /**
  109671. * Dispose only the render target textures and post process.
  109672. */
  109673. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  109674. this._mainTexture.dispose();
  109675. for (var i = 0; i < this._postProcesses.length; i++) {
  109676. if (this._postProcesses[i]) {
  109677. this._postProcesses[i].dispose();
  109678. }
  109679. }
  109680. this._postProcesses = [];
  109681. for (var i = 0; i < this._textures.length; i++) {
  109682. if (this._textures[i]) {
  109683. this._textures[i].dispose();
  109684. }
  109685. }
  109686. this._textures = [];
  109687. };
  109688. /**
  109689. * Dispose the highlight layer and free resources.
  109690. */
  109691. EffectLayer.prototype.dispose = function () {
  109692. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  109693. if (vertexBuffer) {
  109694. vertexBuffer.dispose();
  109695. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  109696. }
  109697. if (this._indexBuffer) {
  109698. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  109699. this._indexBuffer = null;
  109700. }
  109701. // Clean textures and post processes
  109702. this._disposeTextureAndPostProcesses();
  109703. // Remove from scene
  109704. var index = this._scene.effectLayers.indexOf(this, 0);
  109705. if (index > -1) {
  109706. this._scene.effectLayers.splice(index, 1);
  109707. }
  109708. // Callback
  109709. this.onDisposeObservable.notifyObservers(this);
  109710. this.onDisposeObservable.clear();
  109711. this.onBeforeRenderMainTextureObservable.clear();
  109712. this.onBeforeComposeObservable.clear();
  109713. this.onAfterComposeObservable.clear();
  109714. this.onSizeChangedObservable.clear();
  109715. };
  109716. /**
  109717. * Gets the class name of the effect layer
  109718. * @returns the string with the class name of the effect layer
  109719. */
  109720. EffectLayer.prototype.getClassName = function () {
  109721. return "EffectLayer";
  109722. };
  109723. /**
  109724. * Creates an effect layer from parsed effect layer data
  109725. * @param parsedEffectLayer defines effect layer data
  109726. * @param scene defines the current scene
  109727. * @param rootUrl defines the root URL containing the effect layer information
  109728. * @returns a parsed effect Layer
  109729. */
  109730. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  109731. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  109732. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  109733. };
  109734. __decorate([
  109735. BABYLON.serialize()
  109736. ], EffectLayer.prototype, "name", void 0);
  109737. __decorate([
  109738. BABYLON.serializeAsColor4()
  109739. ], EffectLayer.prototype, "neutralColor", void 0);
  109740. __decorate([
  109741. BABYLON.serialize()
  109742. ], EffectLayer.prototype, "isEnabled", void 0);
  109743. __decorate([
  109744. BABYLON.serializeAsCameraReference()
  109745. ], EffectLayer.prototype, "camera", null);
  109746. __decorate([
  109747. BABYLON.serialize()
  109748. ], EffectLayer.prototype, "renderingGroupId", null);
  109749. return EffectLayer;
  109750. }());
  109751. BABYLON.EffectLayer = EffectLayer;
  109752. })(BABYLON || (BABYLON = {}));
  109753. //# sourceMappingURL=babylon.effectLayer.js.map
  109754. var BABYLON;
  109755. (function (BABYLON) {
  109756. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  109757. for (var index = 0; index < this.effectLayers.length; index++) {
  109758. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  109759. return this.effectLayers[index];
  109760. }
  109761. }
  109762. return null;
  109763. };
  109764. /**
  109765. * Special Glow Blur post process only blurring the alpha channel
  109766. * It enforces keeping the most luminous color in the color channel.
  109767. */
  109768. var GlowBlurPostProcess = /** @class */ (function (_super) {
  109769. __extends(GlowBlurPostProcess, _super);
  109770. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  109771. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  109772. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  109773. _this.direction = direction;
  109774. _this.kernel = kernel;
  109775. _this.onApplyObservable.add(function (effect) {
  109776. effect.setFloat2("screenSize", _this.width, _this.height);
  109777. effect.setVector2("direction", _this.direction);
  109778. effect.setFloat("blurWidth", _this.kernel);
  109779. });
  109780. return _this;
  109781. }
  109782. return GlowBlurPostProcess;
  109783. }(BABYLON.PostProcess));
  109784. /**
  109785. * The highlight layer Helps adding a glow effect around a mesh.
  109786. *
  109787. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  109788. * glowy meshes to your scene.
  109789. *
  109790. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  109791. */
  109792. var HighlightLayer = /** @class */ (function (_super) {
  109793. __extends(HighlightLayer, _super);
  109794. /**
  109795. * Instantiates a new highlight Layer and references it to the scene..
  109796. * @param name The name of the layer
  109797. * @param scene The scene to use the layer in
  109798. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  109799. */
  109800. function HighlightLayer(name, scene, options) {
  109801. var _this = _super.call(this, name, scene) || this;
  109802. _this.name = name;
  109803. /**
  109804. * Specifies whether or not the inner glow is ACTIVE in the layer.
  109805. */
  109806. _this.innerGlow = true;
  109807. /**
  109808. * Specifies whether or not the outer glow is ACTIVE in the layer.
  109809. */
  109810. _this.outerGlow = true;
  109811. /**
  109812. * An event triggered when the highlight layer is being blurred.
  109813. */
  109814. _this.onBeforeBlurObservable = new BABYLON.Observable();
  109815. /**
  109816. * An event triggered when the highlight layer has been blurred.
  109817. */
  109818. _this.onAfterBlurObservable = new BABYLON.Observable();
  109819. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  109820. _this._meshes = {};
  109821. _this._excludedMeshes = {};
  109822. _this.neutralColor = HighlightLayer.NeutralColor;
  109823. // Warn on stencil
  109824. if (!_this._engine.isStencilEnable) {
  109825. 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 }");
  109826. }
  109827. // Adapt options
  109828. _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);
  109829. // Initialize the layer
  109830. _this._init({
  109831. alphaBlendingMode: _this._options.alphaBlendingMode,
  109832. camera: _this._options.camera,
  109833. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  109834. mainTextureRatio: _this._options.mainTextureRatio,
  109835. renderingGroupId: _this._options.renderingGroupId
  109836. });
  109837. // Do not render as long as no meshes have been added
  109838. _this._shouldRender = false;
  109839. return _this;
  109840. }
  109841. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  109842. /**
  109843. * Gets the horizontal size of the blur.
  109844. */
  109845. get: function () {
  109846. return this._horizontalBlurPostprocess.kernel;
  109847. },
  109848. /**
  109849. * Specifies the horizontal size of the blur.
  109850. */
  109851. set: function (value) {
  109852. this._horizontalBlurPostprocess.kernel = value;
  109853. },
  109854. enumerable: true,
  109855. configurable: true
  109856. });
  109857. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  109858. /**
  109859. * Gets the vertical size of the blur.
  109860. */
  109861. get: function () {
  109862. return this._verticalBlurPostprocess.kernel;
  109863. },
  109864. /**
  109865. * Specifies the vertical size of the blur.
  109866. */
  109867. set: function (value) {
  109868. this._verticalBlurPostprocess.kernel = value;
  109869. },
  109870. enumerable: true,
  109871. configurable: true
  109872. });
  109873. /**
  109874. * Get the effect name of the layer.
  109875. * @return The effect name
  109876. */
  109877. HighlightLayer.prototype.getEffectName = function () {
  109878. return HighlightLayer.EffectName;
  109879. };
  109880. /**
  109881. * Create the merge effect. This is the shader use to blit the information back
  109882. * to the main canvas at the end of the scene rendering.
  109883. */
  109884. HighlightLayer.prototype._createMergeEffect = function () {
  109885. // Effect
  109886. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  109887. };
  109888. /**
  109889. * Creates the render target textures and post processes used in the highlight layer.
  109890. */
  109891. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  109892. var _this = this;
  109893. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  109894. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  109895. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  109896. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  109897. var textureType = 0;
  109898. if (this._engine.getCaps().textureHalfFloatRender) {
  109899. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  109900. }
  109901. else {
  109902. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  109903. }
  109904. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  109905. width: blurTextureWidth,
  109906. height: blurTextureHeight
  109907. }, this._scene, false, true, textureType);
  109908. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109909. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109910. this._blurTexture.anisotropicFilteringLevel = 16;
  109911. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  109912. this._blurTexture.renderParticles = false;
  109913. this._blurTexture.ignoreCameraViewport = true;
  109914. this._textures = [this._blurTexture];
  109915. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  109916. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  109917. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  109918. effect.setTexture("textureSampler", _this._mainTexture);
  109919. });
  109920. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  109921. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  109922. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  109923. });
  109924. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  109925. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  109926. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  109927. });
  109928. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  109929. }
  109930. else {
  109931. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  109932. width: blurTextureWidth,
  109933. height: blurTextureHeight
  109934. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  109935. this._horizontalBlurPostprocess.width = blurTextureWidth;
  109936. this._horizontalBlurPostprocess.height = blurTextureHeight;
  109937. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  109938. effect.setTexture("textureSampler", _this._mainTexture);
  109939. });
  109940. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  109941. width: blurTextureWidth,
  109942. height: blurTextureHeight
  109943. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  109944. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  109945. }
  109946. this._mainTexture.onAfterUnbindObservable.add(function () {
  109947. _this.onBeforeBlurObservable.notifyObservers(_this);
  109948. var internalTexture = _this._blurTexture.getInternalTexture();
  109949. if (internalTexture) {
  109950. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  109951. }
  109952. _this.onAfterBlurObservable.notifyObservers(_this);
  109953. });
  109954. // Prevent autoClear.
  109955. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  109956. };
  109957. /**
  109958. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  109959. */
  109960. HighlightLayer.prototype.needStencil = function () {
  109961. return true;
  109962. };
  109963. /**
  109964. * Checks for the readiness of the element composing the layer.
  109965. * @param subMesh the mesh to check for
  109966. * @param useInstances specify wether or not to use instances to render the mesh
  109967. * @param emissiveTexture the associated emissive texture used to generate the glow
  109968. * @return true if ready otherwise, false
  109969. */
  109970. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  109971. var material = subMesh.getMaterial();
  109972. var mesh = subMesh.getRenderingMesh();
  109973. if (!material || !mesh || !this._meshes) {
  109974. return false;
  109975. }
  109976. var emissiveTexture = null;
  109977. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  109978. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  109979. emissiveTexture = material.emissiveTexture;
  109980. }
  109981. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  109982. };
  109983. /**
  109984. * Implementation specific of rendering the generating effect on the main canvas.
  109985. * @param effect The effect used to render through
  109986. */
  109987. HighlightLayer.prototype._internalRender = function (effect) {
  109988. // Texture
  109989. effect.setTexture("textureSampler", this._blurTexture);
  109990. // Cache
  109991. var engine = this._engine;
  109992. var previousStencilBuffer = engine.getStencilBuffer();
  109993. var previousStencilFunction = engine.getStencilFunction();
  109994. var previousStencilMask = engine.getStencilMask();
  109995. var previousStencilOperationPass = engine.getStencilOperationPass();
  109996. var previousStencilOperationFail = engine.getStencilOperationFail();
  109997. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  109998. var previousStencilReference = engine.getStencilFunctionReference();
  109999. // Stencil operations
  110000. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  110001. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  110002. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  110003. // Draw order
  110004. engine.setStencilMask(0x00);
  110005. engine.setStencilBuffer(true);
  110006. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  110007. // 2 passes inner outer
  110008. if (this.outerGlow) {
  110009. effect.setFloat("offset", 0);
  110010. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  110011. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  110012. }
  110013. if (this.innerGlow) {
  110014. effect.setFloat("offset", 1);
  110015. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  110016. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  110017. }
  110018. // Restore Cache
  110019. engine.setStencilFunction(previousStencilFunction);
  110020. engine.setStencilMask(previousStencilMask);
  110021. engine.setStencilBuffer(previousStencilBuffer);
  110022. engine.setStencilOperationPass(previousStencilOperationPass);
  110023. engine.setStencilOperationFail(previousStencilOperationFail);
  110024. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  110025. engine.setStencilFunctionReference(previousStencilReference);
  110026. };
  110027. /**
  110028. * Returns true if the layer contains information to display, otherwise false.
  110029. */
  110030. HighlightLayer.prototype.shouldRender = function () {
  110031. if (_super.prototype.shouldRender.call(this)) {
  110032. return this._meshes ? true : false;
  110033. }
  110034. return false;
  110035. };
  110036. /**
  110037. * Returns true if the mesh should render, otherwise false.
  110038. * @param mesh The mesh to render
  110039. * @returns true if it should render otherwise false
  110040. */
  110041. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  110042. // Excluded Mesh
  110043. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  110044. return false;
  110045. }
  110046. if (!_super.prototype.hasMesh.call(this, mesh)) {
  110047. return false;
  110048. }
  110049. return true;
  110050. };
  110051. /**
  110052. * Sets the required values for both the emissive texture and and the main color.
  110053. */
  110054. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  110055. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  110056. if (highlightLayerMesh) {
  110057. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  110058. }
  110059. else {
  110060. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  110061. }
  110062. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  110063. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  110064. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  110065. }
  110066. else {
  110067. this._emissiveTextureAndColor.texture = null;
  110068. }
  110069. };
  110070. /**
  110071. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  110072. * @param mesh The mesh to exclude from the highlight layer
  110073. */
  110074. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  110075. if (!this._excludedMeshes) {
  110076. return;
  110077. }
  110078. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  110079. if (!meshExcluded) {
  110080. this._excludedMeshes[mesh.uniqueId] = {
  110081. mesh: mesh,
  110082. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  110083. mesh.getEngine().setStencilBuffer(false);
  110084. }),
  110085. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  110086. mesh.getEngine().setStencilBuffer(true);
  110087. }),
  110088. };
  110089. }
  110090. };
  110091. /**
  110092. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  110093. * @param mesh The mesh to highlight
  110094. */
  110095. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  110096. if (!this._excludedMeshes) {
  110097. return;
  110098. }
  110099. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  110100. if (meshExcluded) {
  110101. if (meshExcluded.beforeRender) {
  110102. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  110103. }
  110104. if (meshExcluded.afterRender) {
  110105. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  110106. }
  110107. }
  110108. this._excludedMeshes[mesh.uniqueId] = null;
  110109. };
  110110. /**
  110111. * Determine if a given mesh will be highlighted by the current HighlightLayer
  110112. * @param mesh mesh to test
  110113. * @returns true if the mesh will be highlighted by the current HighlightLayer
  110114. */
  110115. HighlightLayer.prototype.hasMesh = function (mesh) {
  110116. if (!this._meshes) {
  110117. return false;
  110118. }
  110119. if (!_super.prototype.hasMesh.call(this, mesh)) {
  110120. return false;
  110121. }
  110122. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  110123. };
  110124. /**
  110125. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  110126. * @param mesh The mesh to highlight
  110127. * @param color The color of the highlight
  110128. * @param glowEmissiveOnly Extract the glow from the emissive texture
  110129. */
  110130. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  110131. var _this = this;
  110132. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  110133. if (!this._meshes) {
  110134. return;
  110135. }
  110136. var meshHighlight = this._meshes[mesh.uniqueId];
  110137. if (meshHighlight) {
  110138. meshHighlight.color = color;
  110139. }
  110140. else {
  110141. this._meshes[mesh.uniqueId] = {
  110142. mesh: mesh,
  110143. color: color,
  110144. // Lambda required for capture due to Observable this context
  110145. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  110146. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  110147. _this._defaultStencilReference(mesh);
  110148. }
  110149. else {
  110150. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  110151. }
  110152. }),
  110153. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  110154. glowEmissiveOnly: glowEmissiveOnly
  110155. };
  110156. mesh.onDisposeObservable.add(function () {
  110157. _this._disposeMesh(mesh);
  110158. });
  110159. }
  110160. this._shouldRender = true;
  110161. };
  110162. /**
  110163. * Remove a mesh from the highlight layer in order to make it stop glowing.
  110164. * @param mesh The mesh to highlight
  110165. */
  110166. HighlightLayer.prototype.removeMesh = function (mesh) {
  110167. if (!this._meshes) {
  110168. return;
  110169. }
  110170. var meshHighlight = this._meshes[mesh.uniqueId];
  110171. if (meshHighlight) {
  110172. if (meshHighlight.observerHighlight) {
  110173. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  110174. }
  110175. if (meshHighlight.observerDefault) {
  110176. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  110177. }
  110178. delete this._meshes[mesh.uniqueId];
  110179. }
  110180. this._shouldRender = false;
  110181. for (var meshHighlightToCheck in this._meshes) {
  110182. if (this._meshes[meshHighlightToCheck]) {
  110183. this._shouldRender = true;
  110184. break;
  110185. }
  110186. }
  110187. };
  110188. /**
  110189. * Force the stencil to the normal expected value for none glowing parts
  110190. */
  110191. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  110192. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  110193. };
  110194. /**
  110195. * Free any resources and references associated to a mesh.
  110196. * Internal use
  110197. * @param mesh The mesh to free.
  110198. * @hidden
  110199. */
  110200. HighlightLayer.prototype._disposeMesh = function (mesh) {
  110201. this.removeMesh(mesh);
  110202. this.removeExcludedMesh(mesh);
  110203. };
  110204. /**
  110205. * Dispose the highlight layer and free resources.
  110206. */
  110207. HighlightLayer.prototype.dispose = function () {
  110208. if (this._meshes) {
  110209. // Clean mesh references
  110210. for (var id in this._meshes) {
  110211. var meshHighlight = this._meshes[id];
  110212. if (meshHighlight && meshHighlight.mesh) {
  110213. if (meshHighlight.observerHighlight) {
  110214. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  110215. }
  110216. if (meshHighlight.observerDefault) {
  110217. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  110218. }
  110219. }
  110220. }
  110221. this._meshes = null;
  110222. }
  110223. if (this._excludedMeshes) {
  110224. for (var id in this._excludedMeshes) {
  110225. var meshHighlight = this._excludedMeshes[id];
  110226. if (meshHighlight) {
  110227. if (meshHighlight.beforeRender) {
  110228. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  110229. }
  110230. if (meshHighlight.afterRender) {
  110231. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  110232. }
  110233. }
  110234. }
  110235. this._excludedMeshes = null;
  110236. }
  110237. _super.prototype.dispose.call(this);
  110238. };
  110239. /**
  110240. * Gets the class name of the effect layer
  110241. * @returns the string with the class name of the effect layer
  110242. */
  110243. HighlightLayer.prototype.getClassName = function () {
  110244. return "HighlightLayer";
  110245. };
  110246. /**
  110247. * Serializes this Highlight layer
  110248. * @returns a serialized Highlight layer object
  110249. */
  110250. HighlightLayer.prototype.serialize = function () {
  110251. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  110252. serializationObject.customType = "BABYLON.HighlightLayer";
  110253. // Highlighted meshes
  110254. serializationObject.meshes = [];
  110255. if (this._meshes) {
  110256. for (var m in this._meshes) {
  110257. var mesh = this._meshes[m];
  110258. if (mesh) {
  110259. serializationObject.meshes.push({
  110260. glowEmissiveOnly: mesh.glowEmissiveOnly,
  110261. color: mesh.color.asArray(),
  110262. meshId: mesh.mesh.id
  110263. });
  110264. }
  110265. }
  110266. }
  110267. // Excluded meshes
  110268. serializationObject.excludedMeshes = [];
  110269. if (this._excludedMeshes) {
  110270. for (var e in this._excludedMeshes) {
  110271. var excludedMesh = this._excludedMeshes[e];
  110272. if (excludedMesh) {
  110273. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  110274. }
  110275. }
  110276. }
  110277. return serializationObject;
  110278. };
  110279. /**
  110280. * Creates a Highlight layer from parsed Highlight layer data
  110281. * @param parsedHightlightLayer defines the Highlight layer data
  110282. * @param scene defines the current scene
  110283. * @param rootUrl defines the root URL containing the Highlight layer information
  110284. * @returns a parsed Highlight layer
  110285. */
  110286. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  110287. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  110288. var index;
  110289. // Excluded meshes
  110290. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  110291. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  110292. if (mesh) {
  110293. hl.addExcludedMesh(mesh);
  110294. }
  110295. }
  110296. // Included meshes
  110297. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  110298. var highlightedMesh = parsedHightlightLayer.meshes[index];
  110299. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  110300. if (mesh) {
  110301. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  110302. }
  110303. }
  110304. return hl;
  110305. };
  110306. /**
  110307. * Effect Name of the highlight layer.
  110308. */
  110309. HighlightLayer.EffectName = "HighlightLayer";
  110310. /**
  110311. * The neutral color used during the preparation of the glow effect.
  110312. * This is black by default as the blend operation is a blend operation.
  110313. */
  110314. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  110315. /**
  110316. * Stencil value used for glowing meshes.
  110317. */
  110318. HighlightLayer.GlowingMeshStencilReference = 0x02;
  110319. /**
  110320. * Stencil value used for the other meshes in the scene.
  110321. */
  110322. HighlightLayer.NormalMeshStencilReference = 0x01;
  110323. __decorate([
  110324. BABYLON.serialize()
  110325. ], HighlightLayer.prototype, "innerGlow", void 0);
  110326. __decorate([
  110327. BABYLON.serialize()
  110328. ], HighlightLayer.prototype, "outerGlow", void 0);
  110329. __decorate([
  110330. BABYLON.serialize()
  110331. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  110332. __decorate([
  110333. BABYLON.serialize()
  110334. ], HighlightLayer.prototype, "blurVerticalSize", null);
  110335. __decorate([
  110336. BABYLON.serialize("options")
  110337. ], HighlightLayer.prototype, "_options", void 0);
  110338. return HighlightLayer;
  110339. }(BABYLON.EffectLayer));
  110340. BABYLON.HighlightLayer = HighlightLayer;
  110341. })(BABYLON || (BABYLON = {}));
  110342. //# sourceMappingURL=babylon.highlightLayer.js.map
  110343. var BABYLON;
  110344. (function (BABYLON) {
  110345. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  110346. for (var index = 0; index < this.effectLayers.length; index++) {
  110347. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  110348. return this.effectLayers[index];
  110349. }
  110350. }
  110351. return null;
  110352. };
  110353. /**
  110354. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  110355. *
  110356. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  110357. * glowy meshes to your scene.
  110358. *
  110359. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  110360. */
  110361. var GlowLayer = /** @class */ (function (_super) {
  110362. __extends(GlowLayer, _super);
  110363. /**
  110364. * Instantiates a new glow Layer and references it to the scene.
  110365. * @param name The name of the layer
  110366. * @param scene The scene to use the layer in
  110367. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  110368. */
  110369. function GlowLayer(name, scene, options) {
  110370. var _this = _super.call(this, name, scene) || this;
  110371. _this._intensity = 1.0;
  110372. _this._includedOnlyMeshes = [];
  110373. _this._excludedMeshes = [];
  110374. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  110375. // Adapt options
  110376. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  110377. // Initialize the layer
  110378. _this._init({
  110379. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  110380. camera: _this._options.camera,
  110381. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  110382. mainTextureRatio: _this._options.mainTextureRatio,
  110383. renderingGroupId: _this._options.renderingGroupId
  110384. });
  110385. return _this;
  110386. }
  110387. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  110388. /**
  110389. * Gets the kernel size of the blur.
  110390. */
  110391. get: function () {
  110392. return this._horizontalBlurPostprocess1.kernel;
  110393. },
  110394. /**
  110395. * Sets the kernel size of the blur.
  110396. */
  110397. set: function (value) {
  110398. this._horizontalBlurPostprocess1.kernel = value;
  110399. this._verticalBlurPostprocess1.kernel = value;
  110400. this._horizontalBlurPostprocess2.kernel = value;
  110401. this._verticalBlurPostprocess2.kernel = value;
  110402. },
  110403. enumerable: true,
  110404. configurable: true
  110405. });
  110406. Object.defineProperty(GlowLayer.prototype, "intensity", {
  110407. /**
  110408. * Gets the glow intensity.
  110409. */
  110410. get: function () {
  110411. return this._intensity;
  110412. },
  110413. /**
  110414. * Sets the glow intensity.
  110415. */
  110416. set: function (value) {
  110417. this._intensity = value;
  110418. },
  110419. enumerable: true,
  110420. configurable: true
  110421. });
  110422. /**
  110423. * Get the effect name of the layer.
  110424. * @return The effect name
  110425. */
  110426. GlowLayer.prototype.getEffectName = function () {
  110427. return GlowLayer.EffectName;
  110428. };
  110429. /**
  110430. * Create the merge effect. This is the shader use to blit the information back
  110431. * to the main canvas at the end of the scene rendering.
  110432. */
  110433. GlowLayer.prototype._createMergeEffect = function () {
  110434. // Effect
  110435. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  110436. };
  110437. /**
  110438. * Creates the render target textures and post processes used in the glow layer.
  110439. */
  110440. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  110441. var _this = this;
  110442. var blurTextureWidth = this._mainTextureDesiredSize.width;
  110443. var blurTextureHeight = this._mainTextureDesiredSize.height;
  110444. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  110445. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  110446. var textureType = 0;
  110447. if (this._engine.getCaps().textureHalfFloatRender) {
  110448. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  110449. }
  110450. else {
  110451. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  110452. }
  110453. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  110454. width: blurTextureWidth,
  110455. height: blurTextureHeight
  110456. }, this._scene, false, true, textureType);
  110457. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110458. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110459. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  110460. this._blurTexture1.renderParticles = false;
  110461. this._blurTexture1.ignoreCameraViewport = true;
  110462. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  110463. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  110464. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  110465. width: blurTextureWidth2,
  110466. height: blurTextureHeight2
  110467. }, this._scene, false, true, textureType);
  110468. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110469. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110470. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  110471. this._blurTexture2.renderParticles = false;
  110472. this._blurTexture2.ignoreCameraViewport = true;
  110473. this._textures = [this._blurTexture1, this._blurTexture2];
  110474. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  110475. width: blurTextureWidth,
  110476. height: blurTextureHeight
  110477. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  110478. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  110479. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  110480. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  110481. effect.setTexture("textureSampler", _this._mainTexture);
  110482. });
  110483. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  110484. width: blurTextureWidth,
  110485. height: blurTextureHeight
  110486. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  110487. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  110488. width: blurTextureWidth2,
  110489. height: blurTextureHeight2
  110490. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  110491. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  110492. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  110493. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  110494. effect.setTexture("textureSampler", _this._blurTexture1);
  110495. });
  110496. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  110497. width: blurTextureWidth2,
  110498. height: blurTextureHeight2
  110499. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  110500. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  110501. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  110502. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  110503. this._mainTexture.samples = this._options.mainTextureSamples;
  110504. this._mainTexture.onAfterUnbindObservable.add(function () {
  110505. var internalTexture = _this._blurTexture1.getInternalTexture();
  110506. if (internalTexture) {
  110507. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  110508. internalTexture = _this._blurTexture2.getInternalTexture();
  110509. if (internalTexture) {
  110510. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  110511. }
  110512. }
  110513. });
  110514. // Prevent autoClear.
  110515. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  110516. };
  110517. /**
  110518. * Checks for the readiness of the element composing the layer.
  110519. * @param subMesh the mesh to check for
  110520. * @param useInstances specify wether or not to use instances to render the mesh
  110521. * @param emissiveTexture the associated emissive texture used to generate the glow
  110522. * @return true if ready otherwise, false
  110523. */
  110524. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  110525. var material = subMesh.getMaterial();
  110526. var mesh = subMesh.getRenderingMesh();
  110527. if (!material || !mesh) {
  110528. return false;
  110529. }
  110530. var emissiveTexture = material.emissiveTexture;
  110531. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  110532. };
  110533. /**
  110534. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  110535. */
  110536. GlowLayer.prototype.needStencil = function () {
  110537. return false;
  110538. };
  110539. /**
  110540. * Implementation specific of rendering the generating effect on the main canvas.
  110541. * @param effect The effect used to render through
  110542. */
  110543. GlowLayer.prototype._internalRender = function (effect) {
  110544. // Texture
  110545. effect.setTexture("textureSampler", this._blurTexture1);
  110546. effect.setTexture("textureSampler2", this._blurTexture2);
  110547. effect.setFloat("offset", this._intensity);
  110548. // Cache
  110549. var engine = this._engine;
  110550. var previousStencilBuffer = engine.getStencilBuffer();
  110551. // Draw order
  110552. engine.setStencilBuffer(false);
  110553. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  110554. // Draw order
  110555. engine.setStencilBuffer(previousStencilBuffer);
  110556. };
  110557. /**
  110558. * Sets the required values for both the emissive texture and and the main color.
  110559. */
  110560. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  110561. var textureLevel = 1.0;
  110562. if (this.customEmissiveTextureSelector) {
  110563. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  110564. }
  110565. else {
  110566. if (material) {
  110567. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  110568. if (this._emissiveTextureAndColor.texture) {
  110569. textureLevel = this._emissiveTextureAndColor.texture.level;
  110570. }
  110571. }
  110572. else {
  110573. this._emissiveTextureAndColor.texture = null;
  110574. }
  110575. }
  110576. if (this.customEmissiveColorSelector) {
  110577. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  110578. }
  110579. else {
  110580. if (material.emissiveColor) {
  110581. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  110582. }
  110583. else {
  110584. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  110585. }
  110586. }
  110587. };
  110588. /**
  110589. * Returns true if the mesh should render, otherwise false.
  110590. * @param mesh The mesh to render
  110591. * @returns true if it should render otherwise false
  110592. */
  110593. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  110594. return this.hasMesh(mesh);
  110595. };
  110596. /**
  110597. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  110598. * @param mesh The mesh to exclude from the glow layer
  110599. */
  110600. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  110601. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  110602. this._excludedMeshes.push(mesh.uniqueId);
  110603. }
  110604. };
  110605. /**
  110606. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  110607. * @param mesh The mesh to remove
  110608. */
  110609. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  110610. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  110611. if (index !== -1) {
  110612. this._excludedMeshes.splice(index, 1);
  110613. }
  110614. };
  110615. /**
  110616. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  110617. * @param mesh The mesh to include in the glow layer
  110618. */
  110619. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  110620. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  110621. this._includedOnlyMeshes.push(mesh.uniqueId);
  110622. }
  110623. };
  110624. /**
  110625. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  110626. * @param mesh The mesh to remove
  110627. */
  110628. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  110629. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  110630. if (index !== -1) {
  110631. this._includedOnlyMeshes.splice(index, 1);
  110632. }
  110633. };
  110634. /**
  110635. * Determine if a given mesh will be used in the glow layer
  110636. * @param mesh The mesh to test
  110637. * @returns true if the mesh will be highlighted by the current glow layer
  110638. */
  110639. GlowLayer.prototype.hasMesh = function (mesh) {
  110640. if (!_super.prototype.hasMesh.call(this, mesh)) {
  110641. return false;
  110642. }
  110643. // Included Mesh
  110644. if (this._includedOnlyMeshes.length) {
  110645. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  110646. }
  110647. // Excluded Mesh
  110648. if (this._excludedMeshes.length) {
  110649. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  110650. }
  110651. return true;
  110652. };
  110653. /**
  110654. * Free any resources and references associated to a mesh.
  110655. * Internal use
  110656. * @param mesh The mesh to free.
  110657. * @hidden
  110658. */
  110659. GlowLayer.prototype._disposeMesh = function (mesh) {
  110660. this.removeIncludedOnlyMesh(mesh);
  110661. this.removeExcludedMesh(mesh);
  110662. };
  110663. /**
  110664. * Gets the class name of the effect layer
  110665. * @returns the string with the class name of the effect layer
  110666. */
  110667. GlowLayer.prototype.getClassName = function () {
  110668. return "GlowLayer";
  110669. };
  110670. /**
  110671. * Serializes this glow layer
  110672. * @returns a serialized glow layer object
  110673. */
  110674. GlowLayer.prototype.serialize = function () {
  110675. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  110676. serializationObject.customType = "BABYLON.GlowLayer";
  110677. var index;
  110678. // Included meshes
  110679. serializationObject.includedMeshes = [];
  110680. if (this._includedOnlyMeshes.length) {
  110681. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  110682. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  110683. if (mesh) {
  110684. serializationObject.includedMeshes.push(mesh.id);
  110685. }
  110686. }
  110687. }
  110688. // Excluded meshes
  110689. serializationObject.excludedMeshes = [];
  110690. if (this._excludedMeshes.length) {
  110691. for (index = 0; index < this._excludedMeshes.length; index++) {
  110692. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  110693. if (mesh) {
  110694. serializationObject.excludedMeshes.push(mesh.id);
  110695. }
  110696. }
  110697. }
  110698. return serializationObject;
  110699. };
  110700. /**
  110701. * Creates a Glow Layer from parsed glow layer data
  110702. * @param parsedGlowLayer defines glow layer data
  110703. * @param scene defines the current scene
  110704. * @param rootUrl defines the root URL containing the glow layer information
  110705. * @returns a parsed Glow Layer
  110706. */
  110707. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  110708. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  110709. var index;
  110710. // Excluded meshes
  110711. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  110712. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  110713. if (mesh) {
  110714. gl.addExcludedMesh(mesh);
  110715. }
  110716. }
  110717. // Included meshes
  110718. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  110719. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  110720. if (mesh) {
  110721. gl.addIncludedOnlyMesh(mesh);
  110722. }
  110723. }
  110724. return gl;
  110725. };
  110726. /**
  110727. * Effect Name of the layer.
  110728. */
  110729. GlowLayer.EffectName = "GlowLayer";
  110730. /**
  110731. * The default blur kernel size used for the glow.
  110732. */
  110733. GlowLayer.DefaultBlurKernelSize = 32;
  110734. /**
  110735. * The default texture size ratio used for the glow.
  110736. */
  110737. GlowLayer.DefaultTextureRatio = 0.5;
  110738. __decorate([
  110739. BABYLON.serialize()
  110740. ], GlowLayer.prototype, "blurKernelSize", null);
  110741. __decorate([
  110742. BABYLON.serialize()
  110743. ], GlowLayer.prototype, "intensity", null);
  110744. __decorate([
  110745. BABYLON.serialize("options")
  110746. ], GlowLayer.prototype, "_options", void 0);
  110747. return GlowLayer;
  110748. }(BABYLON.EffectLayer));
  110749. BABYLON.GlowLayer = GlowLayer;
  110750. })(BABYLON || (BABYLON = {}));
  110751. //# sourceMappingURL=babylon.glowLayer.js.map
  110752. var BABYLON;
  110753. (function (BABYLON) {
  110754. /**
  110755. * Defines the list of states available for a task inside a AssetsManager
  110756. */
  110757. var AssetTaskState;
  110758. (function (AssetTaskState) {
  110759. /**
  110760. * Initialization
  110761. */
  110762. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  110763. /**
  110764. * Running
  110765. */
  110766. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  110767. /**
  110768. * Done
  110769. */
  110770. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  110771. /**
  110772. * Error
  110773. */
  110774. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  110775. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  110776. /**
  110777. * Define an abstract asset task used with a AssetsManager class to load assets into a scene
  110778. */
  110779. var AbstractAssetTask = /** @class */ (function () {
  110780. /**
  110781. * Creates a new AssetsManager
  110782. * @param name defines the name of the task
  110783. */
  110784. function AbstractAssetTask(
  110785. /**
  110786. * Task name
  110787. */ name) {
  110788. this.name = name;
  110789. this._isCompleted = false;
  110790. this._taskState = AssetTaskState.INIT;
  110791. }
  110792. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  110793. /**
  110794. * Get if the task is completed
  110795. */
  110796. get: function () {
  110797. return this._isCompleted;
  110798. },
  110799. enumerable: true,
  110800. configurable: true
  110801. });
  110802. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  110803. /**
  110804. * Gets the current state of the task
  110805. */
  110806. get: function () {
  110807. return this._taskState;
  110808. },
  110809. enumerable: true,
  110810. configurable: true
  110811. });
  110812. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  110813. /**
  110814. * Gets the current error object (if task is in error)
  110815. */
  110816. get: function () {
  110817. return this._errorObject;
  110818. },
  110819. enumerable: true,
  110820. configurable: true
  110821. });
  110822. /**
  110823. * Internal only
  110824. * @hidden
  110825. */
  110826. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  110827. if (this._errorObject) {
  110828. return;
  110829. }
  110830. this._errorObject = {
  110831. message: message,
  110832. exception: exception
  110833. };
  110834. };
  110835. /**
  110836. * Execute the current task
  110837. * @param scene defines the scene where you want your assets to be loaded
  110838. * @param onSuccess is a callback called when the task is successfully executed
  110839. * @param onError is a callback called if an error occurs
  110840. */
  110841. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  110842. var _this = this;
  110843. this._taskState = AssetTaskState.RUNNING;
  110844. this.runTask(scene, function () {
  110845. _this.onDoneCallback(onSuccess, onError);
  110846. }, function (msg, exception) {
  110847. _this.onErrorCallback(onError, msg, exception);
  110848. });
  110849. };
  110850. /**
  110851. * Execute the current task
  110852. * @param scene defines the scene where you want your assets to be loaded
  110853. * @param onSuccess is a callback called when the task is successfully executed
  110854. * @param onError is a callback called if an error occurs
  110855. */
  110856. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  110857. throw new Error("runTask is not implemented");
  110858. };
  110859. /**
  110860. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  110861. * This can be used with failed tasks that have the reason for failure fixed.
  110862. */
  110863. AbstractAssetTask.prototype.reset = function () {
  110864. this._taskState = AssetTaskState.INIT;
  110865. };
  110866. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  110867. this._taskState = AssetTaskState.ERROR;
  110868. this._errorObject = {
  110869. message: message,
  110870. exception: exception
  110871. };
  110872. if (this.onError) {
  110873. this.onError(this, message, exception);
  110874. }
  110875. onError();
  110876. };
  110877. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  110878. try {
  110879. this._taskState = AssetTaskState.DONE;
  110880. this._isCompleted = true;
  110881. if (this.onSuccess) {
  110882. this.onSuccess(this);
  110883. }
  110884. onSuccess();
  110885. }
  110886. catch (e) {
  110887. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  110888. }
  110889. };
  110890. return AbstractAssetTask;
  110891. }());
  110892. BABYLON.AbstractAssetTask = AbstractAssetTask;
  110893. /**
  110894. * Class used to share progress information about assets loading
  110895. */
  110896. var AssetsProgressEvent = /** @class */ (function () {
  110897. /**
  110898. * Creates a AssetsProgressEvent
  110899. * @param remainingCount defines the number of remaining tasks to process
  110900. * @param totalCount defines the total number of tasks
  110901. * @param task defines the task that was just processed
  110902. */
  110903. function AssetsProgressEvent(remainingCount, totalCount, task) {
  110904. this.remainingCount = remainingCount;
  110905. this.totalCount = totalCount;
  110906. this.task = task;
  110907. }
  110908. return AssetsProgressEvent;
  110909. }());
  110910. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  110911. /**
  110912. * Define a task used by AssetsManager to load meshes
  110913. */
  110914. var MeshAssetTask = /** @class */ (function (_super) {
  110915. __extends(MeshAssetTask, _super);
  110916. /**
  110917. * Creates a new MeshAssetTask
  110918. * @param name defines the name of the task
  110919. * @param meshesNames defines the list of mesh's names you want to load
  110920. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  110921. * @param sceneFilename defines the filename of the scene to load from
  110922. */
  110923. function MeshAssetTask(
  110924. /**
  110925. * Defines the name of the task
  110926. */
  110927. name,
  110928. /**
  110929. * Defines the list of mesh's names you want to load
  110930. */
  110931. meshesNames,
  110932. /**
  110933. * Defines the root url to use as a base to load your meshes and associated resources
  110934. */
  110935. rootUrl,
  110936. /**
  110937. * Defines the filename of the scene to load from
  110938. */
  110939. sceneFilename) {
  110940. var _this = _super.call(this, name) || this;
  110941. _this.name = name;
  110942. _this.meshesNames = meshesNames;
  110943. _this.rootUrl = rootUrl;
  110944. _this.sceneFilename = sceneFilename;
  110945. return _this;
  110946. }
  110947. /**
  110948. * Execute the current task
  110949. * @param scene defines the scene where you want your assets to be loaded
  110950. * @param onSuccess is a callback called when the task is successfully executed
  110951. * @param onError is a callback called if an error occurs
  110952. */
  110953. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  110954. var _this = this;
  110955. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  110956. _this.loadedMeshes = meshes;
  110957. _this.loadedParticleSystems = particleSystems;
  110958. _this.loadedSkeletons = skeletons;
  110959. onSuccess();
  110960. }, null, function (scene, message, exception) {
  110961. onError(message, exception);
  110962. });
  110963. };
  110964. return MeshAssetTask;
  110965. }(AbstractAssetTask));
  110966. BABYLON.MeshAssetTask = MeshAssetTask;
  110967. /**
  110968. * Define a task used by AssetsManager to load text content
  110969. */
  110970. var TextFileAssetTask = /** @class */ (function (_super) {
  110971. __extends(TextFileAssetTask, _super);
  110972. /**
  110973. * Creates a new TextFileAssetTask object
  110974. * @param name defines the name of the task
  110975. * @param url defines the location of the file to load
  110976. */
  110977. function TextFileAssetTask(
  110978. /**
  110979. * Defines the name of the task
  110980. */
  110981. name,
  110982. /**
  110983. * Defines the location of the file to load
  110984. */
  110985. url) {
  110986. var _this = _super.call(this, name) || this;
  110987. _this.name = name;
  110988. _this.url = url;
  110989. return _this;
  110990. }
  110991. /**
  110992. * Execute the current task
  110993. * @param scene defines the scene where you want your assets to be loaded
  110994. * @param onSuccess is a callback called when the task is successfully executed
  110995. * @param onError is a callback called if an error occurs
  110996. */
  110997. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  110998. var _this = this;
  110999. scene._loadFile(this.url, function (data) {
  111000. _this.text = data;
  111001. onSuccess();
  111002. }, undefined, false, false, function (request, exception) {
  111003. if (request) {
  111004. onError(request.status + " " + request.statusText, exception);
  111005. }
  111006. });
  111007. };
  111008. return TextFileAssetTask;
  111009. }(AbstractAssetTask));
  111010. BABYLON.TextFileAssetTask = TextFileAssetTask;
  111011. /**
  111012. * Define a task used by AssetsManager to load binary data
  111013. */
  111014. var BinaryFileAssetTask = /** @class */ (function (_super) {
  111015. __extends(BinaryFileAssetTask, _super);
  111016. /**
  111017. * Creates a new BinaryFileAssetTask object
  111018. * @param name defines the name of the new task
  111019. * @param url defines the location of the file to load
  111020. */
  111021. function BinaryFileAssetTask(
  111022. /**
  111023. * Defines the name of the task
  111024. */
  111025. name,
  111026. /**
  111027. * Defines the location of the file to load
  111028. */
  111029. url) {
  111030. var _this = _super.call(this, name) || this;
  111031. _this.name = name;
  111032. _this.url = url;
  111033. return _this;
  111034. }
  111035. /**
  111036. * Execute the current task
  111037. * @param scene defines the scene where you want your assets to be loaded
  111038. * @param onSuccess is a callback called when the task is successfully executed
  111039. * @param onError is a callback called if an error occurs
  111040. */
  111041. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  111042. var _this = this;
  111043. scene._loadFile(this.url, function (data) {
  111044. _this.data = data;
  111045. onSuccess();
  111046. }, undefined, true, true, function (request, exception) {
  111047. if (request) {
  111048. onError(request.status + " " + request.statusText, exception);
  111049. }
  111050. });
  111051. };
  111052. return BinaryFileAssetTask;
  111053. }(AbstractAssetTask));
  111054. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  111055. /**
  111056. * Define a task used by AssetsManager to load images
  111057. */
  111058. var ImageAssetTask = /** @class */ (function (_super) {
  111059. __extends(ImageAssetTask, _super);
  111060. /**
  111061. * Creates a new ImageAssetTask
  111062. * @param name defines the name of the task
  111063. * @param url defines the location of the image to load
  111064. */
  111065. function ImageAssetTask(
  111066. /**
  111067. * Defines the name of the task
  111068. */
  111069. name,
  111070. /**
  111071. * Defines the location of the image to load
  111072. */
  111073. url) {
  111074. var _this = _super.call(this, name) || this;
  111075. _this.name = name;
  111076. _this.url = url;
  111077. return _this;
  111078. }
  111079. /**
  111080. * Execute the current task
  111081. * @param scene defines the scene where you want your assets to be loaded
  111082. * @param onSuccess is a callback called when the task is successfully executed
  111083. * @param onError is a callback called if an error occurs
  111084. */
  111085. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  111086. var _this = this;
  111087. var img = new Image();
  111088. BABYLON.Tools.SetCorsBehavior(this.url, img);
  111089. img.onload = function () {
  111090. _this.image = img;
  111091. onSuccess();
  111092. };
  111093. img.onerror = function (err) {
  111094. onError("Error loading image", err);
  111095. };
  111096. img.src = this.url;
  111097. };
  111098. return ImageAssetTask;
  111099. }(AbstractAssetTask));
  111100. BABYLON.ImageAssetTask = ImageAssetTask;
  111101. /**
  111102. * Define a task used by AssetsManager to load 2D textures
  111103. */
  111104. var TextureAssetTask = /** @class */ (function (_super) {
  111105. __extends(TextureAssetTask, _super);
  111106. /**
  111107. * Creates a new TextureAssetTask object
  111108. * @param name defines the name of the task
  111109. * @param url defines the location of the file to load
  111110. * @param noMipmap defines if mipmap should not be generated (default is false)
  111111. * @param invertY defines if texture must be inverted on Y axis (default is false)
  111112. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  111113. */
  111114. function TextureAssetTask(
  111115. /**
  111116. * Defines the name of the task
  111117. */
  111118. name,
  111119. /**
  111120. * Defines the location of the file to load
  111121. */
  111122. url,
  111123. /**
  111124. * Defines if mipmap should not be generated (default is false)
  111125. */
  111126. noMipmap,
  111127. /**
  111128. * Defines if texture must be inverted on Y axis (default is false)
  111129. */
  111130. invertY,
  111131. /**
  111132. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  111133. */
  111134. samplingMode) {
  111135. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  111136. var _this = _super.call(this, name) || this;
  111137. _this.name = name;
  111138. _this.url = url;
  111139. _this.noMipmap = noMipmap;
  111140. _this.invertY = invertY;
  111141. _this.samplingMode = samplingMode;
  111142. return _this;
  111143. }
  111144. /**
  111145. * Execute the current task
  111146. * @param scene defines the scene where you want your assets to be loaded
  111147. * @param onSuccess is a callback called when the task is successfully executed
  111148. * @param onError is a callback called if an error occurs
  111149. */
  111150. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  111151. var onload = function () {
  111152. onSuccess();
  111153. };
  111154. var onerror = function (message, exception) {
  111155. onError(message, exception);
  111156. };
  111157. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  111158. };
  111159. return TextureAssetTask;
  111160. }(AbstractAssetTask));
  111161. BABYLON.TextureAssetTask = TextureAssetTask;
  111162. /**
  111163. * Define a task used by AssetsManager to load cube textures
  111164. */
  111165. var CubeTextureAssetTask = /** @class */ (function (_super) {
  111166. __extends(CubeTextureAssetTask, _super);
  111167. /**
  111168. * Creates a new CubeTextureAssetTask
  111169. * @param name defines the name of the task
  111170. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  111171. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  111172. * @param noMipmap defines if mipmaps should not be generated (default is false)
  111173. * @param files defines the explicit list of files (undefined by default)
  111174. */
  111175. function CubeTextureAssetTask(
  111176. /**
  111177. * Defines the name of the task
  111178. */
  111179. name,
  111180. /**
  111181. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  111182. */
  111183. url,
  111184. /**
  111185. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  111186. */
  111187. extensions,
  111188. /**
  111189. * Defines if mipmaps should not be generated (default is false)
  111190. */
  111191. noMipmap,
  111192. /**
  111193. * Defines the explicit list of files (undefined by default)
  111194. */
  111195. files) {
  111196. var _this = _super.call(this, name) || this;
  111197. _this.name = name;
  111198. _this.url = url;
  111199. _this.extensions = extensions;
  111200. _this.noMipmap = noMipmap;
  111201. _this.files = files;
  111202. return _this;
  111203. }
  111204. /**
  111205. * Execute the current task
  111206. * @param scene defines the scene where you want your assets to be loaded
  111207. * @param onSuccess is a callback called when the task is successfully executed
  111208. * @param onError is a callback called if an error occurs
  111209. */
  111210. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  111211. var onload = function () {
  111212. onSuccess();
  111213. };
  111214. var onerror = function (message, exception) {
  111215. onError(message, exception);
  111216. };
  111217. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  111218. };
  111219. return CubeTextureAssetTask;
  111220. }(AbstractAssetTask));
  111221. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  111222. /**
  111223. * Define a task used by AssetsManager to load HDR cube textures
  111224. */
  111225. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  111226. __extends(HDRCubeTextureAssetTask, _super);
  111227. /**
  111228. * Creates a new HDRCubeTextureAssetTask object
  111229. * @param name defines the name of the task
  111230. * @param url defines the location of the file to load
  111231. * @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.
  111232. * @param noMipmap defines if mipmaps should not be generated (default is false)
  111233. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  111234. * @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)
  111235. * @param reserved Internal use only
  111236. */
  111237. function HDRCubeTextureAssetTask(
  111238. /**
  111239. * Defines the name of the task
  111240. */
  111241. name,
  111242. /**
  111243. * Defines the location of the file to load
  111244. */
  111245. url,
  111246. /**
  111247. * Defines the desired size (the more it increases the longer the generation will be)
  111248. */
  111249. size,
  111250. /**
  111251. * Defines if mipmaps should not be generated (default is false)
  111252. */
  111253. noMipmap,
  111254. /**
  111255. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  111256. */
  111257. generateHarmonics,
  111258. /**
  111259. * 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)
  111260. */
  111261. gammaSpace,
  111262. /**
  111263. * Internal Use Only
  111264. */
  111265. reserved) {
  111266. if (noMipmap === void 0) { noMipmap = false; }
  111267. if (generateHarmonics === void 0) { generateHarmonics = true; }
  111268. if (gammaSpace === void 0) { gammaSpace = false; }
  111269. if (reserved === void 0) { reserved = false; }
  111270. var _this = _super.call(this, name) || this;
  111271. _this.name = name;
  111272. _this.url = url;
  111273. _this.size = size;
  111274. _this.noMipmap = noMipmap;
  111275. _this.generateHarmonics = generateHarmonics;
  111276. _this.gammaSpace = gammaSpace;
  111277. _this.reserved = reserved;
  111278. return _this;
  111279. }
  111280. /**
  111281. * Execute the current task
  111282. * @param scene defines the scene where you want your assets to be loaded
  111283. * @param onSuccess is a callback called when the task is successfully executed
  111284. * @param onError is a callback called if an error occurs
  111285. */
  111286. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  111287. var onload = function () {
  111288. onSuccess();
  111289. };
  111290. var onerror = function (message, exception) {
  111291. onError(message, exception);
  111292. };
  111293. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  111294. };
  111295. return HDRCubeTextureAssetTask;
  111296. }(AbstractAssetTask));
  111297. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  111298. /**
  111299. * This class can be used to easily import assets into a scene
  111300. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  111301. */
  111302. var AssetsManager = /** @class */ (function () {
  111303. /**
  111304. * Creates a new AssetsManager
  111305. * @param scene defines the scene to work on
  111306. */
  111307. function AssetsManager(scene) {
  111308. this._isLoading = false;
  111309. this._tasks = new Array();
  111310. this._waitingTasksCount = 0;
  111311. this._totalTasksCount = 0;
  111312. /**
  111313. * Observable called when all tasks are processed
  111314. */
  111315. this.onTaskSuccessObservable = new BABYLON.Observable();
  111316. /**
  111317. * Observable called when a task had an error
  111318. */
  111319. this.onTaskErrorObservable = new BABYLON.Observable();
  111320. /**
  111321. * Observable called when a task is successful
  111322. */
  111323. this.onTasksDoneObservable = new BABYLON.Observable();
  111324. /**
  111325. * Observable called when a task is done (whatever the result is)
  111326. */
  111327. this.onProgressObservable = new BABYLON.Observable();
  111328. /**
  111329. * Gets or sets a boolean defining if the AssetsManager should use the default loading screen
  111330. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  111331. */
  111332. this.useDefaultLoadingScreen = true;
  111333. this._scene = scene;
  111334. }
  111335. /**
  111336. * Add a MeshAssetTask to the list of active tasks
  111337. * @param taskName defines the name of the new task
  111338. * @param meshesNames defines the name of meshes to load
  111339. * @param rootUrl defines the root url to use to locate files
  111340. * @param sceneFilename defines the filename of the scene file
  111341. * @returns a new MeshAssetTask object
  111342. */
  111343. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  111344. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  111345. this._tasks.push(task);
  111346. return task;
  111347. };
  111348. /**
  111349. * Add a TextFileAssetTask to the list of active tasks
  111350. * @param taskName defines the name of the new task
  111351. * @param url defines the url of the file to load
  111352. * @returns a new TextFileAssetTask object
  111353. */
  111354. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  111355. var task = new TextFileAssetTask(taskName, url);
  111356. this._tasks.push(task);
  111357. return task;
  111358. };
  111359. /**
  111360. * Add a BinaryFileAssetTask to the list of active tasks
  111361. * @param taskName defines the name of the new task
  111362. * @param url defines the url of the file to load
  111363. * @returns a new BinaryFileAssetTask object
  111364. */
  111365. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  111366. var task = new BinaryFileAssetTask(taskName, url);
  111367. this._tasks.push(task);
  111368. return task;
  111369. };
  111370. /**
  111371. * Add a ImageAssetTask to the list of active tasks
  111372. * @param taskName defines the name of the new task
  111373. * @param url defines the url of the file to load
  111374. * @returns a new ImageAssetTask object
  111375. */
  111376. AssetsManager.prototype.addImageTask = function (taskName, url) {
  111377. var task = new ImageAssetTask(taskName, url);
  111378. this._tasks.push(task);
  111379. return task;
  111380. };
  111381. /**
  111382. * Add a TextureAssetTask to the list of active tasks
  111383. * @param taskName defines the name of the new task
  111384. * @param url defines the url of the file to load
  111385. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  111386. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  111387. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  111388. * @returns a new TextureAssetTask object
  111389. */
  111390. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  111391. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  111392. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  111393. this._tasks.push(task);
  111394. return task;
  111395. };
  111396. /**
  111397. * Add a CubeTextureAssetTask to the list of active tasks
  111398. * @param taskName defines the name of the new task
  111399. * @param url defines the url of the file to load
  111400. * @param extensions defines the extension to use to load the cube map (can be null)
  111401. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  111402. * @param files defines the list of files to load (can be null)
  111403. * @returns a new CubeTextureAssetTask object
  111404. */
  111405. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  111406. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  111407. this._tasks.push(task);
  111408. return task;
  111409. };
  111410. /**
  111411. *
  111412. * Add a HDRCubeTextureAssetTask to the list of active tasks
  111413. * @param taskName defines the name of the new task
  111414. * @param url defines the url of the file to load
  111415. * @param size defines the size you want for the cubemap (can be null)
  111416. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  111417. * @param generateHarmonics defines if you want to automatically generate (true by default)
  111418. * @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)
  111419. * @param reserved Internal use only
  111420. * @returns a new HDRCubeTextureAssetTask object
  111421. */
  111422. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  111423. if (noMipmap === void 0) { noMipmap = false; }
  111424. if (generateHarmonics === void 0) { generateHarmonics = true; }
  111425. if (gammaSpace === void 0) { gammaSpace = false; }
  111426. if (reserved === void 0) { reserved = false; }
  111427. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  111428. this._tasks.push(task);
  111429. return task;
  111430. };
  111431. /**
  111432. * Remove a task from the assets manager.
  111433. * @param task the task to remove
  111434. */
  111435. AssetsManager.prototype.removeTask = function (task) {
  111436. var index = this._tasks.indexOf(task);
  111437. if (index > -1) {
  111438. this._tasks.splice(index, 1);
  111439. }
  111440. };
  111441. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  111442. this._waitingTasksCount--;
  111443. try {
  111444. if (this.onProgress) {
  111445. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  111446. }
  111447. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  111448. }
  111449. catch (e) {
  111450. BABYLON.Tools.Error("Error running progress callbacks.");
  111451. console.log(e);
  111452. }
  111453. if (this._waitingTasksCount === 0) {
  111454. try {
  111455. if (this.onFinish) {
  111456. this.onFinish(this._tasks);
  111457. }
  111458. // Let's remove successfull tasks
  111459. var currentTasks = this._tasks.slice();
  111460. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  111461. var task = currentTasks_1[_i];
  111462. if (task.taskState === AssetTaskState.DONE) {
  111463. var index = this._tasks.indexOf(task);
  111464. if (index > -1) {
  111465. this._tasks.splice(index, 1);
  111466. }
  111467. }
  111468. }
  111469. this.onTasksDoneObservable.notifyObservers(this._tasks);
  111470. }
  111471. catch (e) {
  111472. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  111473. console.log(e);
  111474. }
  111475. this._isLoading = false;
  111476. this._scene.getEngine().hideLoadingUI();
  111477. }
  111478. };
  111479. AssetsManager.prototype._runTask = function (task) {
  111480. var _this = this;
  111481. var done = function () {
  111482. try {
  111483. if (_this.onTaskSuccess) {
  111484. _this.onTaskSuccess(task);
  111485. }
  111486. _this.onTaskSuccessObservable.notifyObservers(task);
  111487. _this._decreaseWaitingTasksCount(task);
  111488. }
  111489. catch (e) {
  111490. error("Error executing task success callbacks", e);
  111491. }
  111492. };
  111493. var error = function (message, exception) {
  111494. task._setErrorObject(message, exception);
  111495. if (_this.onTaskError) {
  111496. _this.onTaskError(task);
  111497. }
  111498. _this.onTaskErrorObservable.notifyObservers(task);
  111499. _this._decreaseWaitingTasksCount(task);
  111500. };
  111501. task.run(this._scene, done, error);
  111502. };
  111503. /**
  111504. * Reset the AssetsManager and remove all tasks
  111505. * @return the current instance of the AssetsManager
  111506. */
  111507. AssetsManager.prototype.reset = function () {
  111508. this._isLoading = false;
  111509. this._tasks = new Array();
  111510. return this;
  111511. };
  111512. /**
  111513. * Start the loading process
  111514. * @return the current instance of the AssetsManager
  111515. */
  111516. AssetsManager.prototype.load = function () {
  111517. if (this._isLoading) {
  111518. return this;
  111519. }
  111520. this._isLoading = true;
  111521. this._waitingTasksCount = this._tasks.length;
  111522. this._totalTasksCount = this._tasks.length;
  111523. if (this._waitingTasksCount === 0) {
  111524. this._isLoading = false;
  111525. if (this.onFinish) {
  111526. this.onFinish(this._tasks);
  111527. }
  111528. this.onTasksDoneObservable.notifyObservers(this._tasks);
  111529. return this;
  111530. }
  111531. if (this.useDefaultLoadingScreen) {
  111532. this._scene.getEngine().displayLoadingUI();
  111533. }
  111534. for (var index = 0; index < this._tasks.length; index++) {
  111535. var task = this._tasks[index];
  111536. if (task.taskState === AssetTaskState.INIT) {
  111537. this._runTask(task);
  111538. }
  111539. }
  111540. return this;
  111541. };
  111542. return AssetsManager;
  111543. }());
  111544. BABYLON.AssetsManager = AssetsManager;
  111545. })(BABYLON || (BABYLON = {}));
  111546. //# sourceMappingURL=babylon.assetsManager.js.map
  111547. var BABYLON;
  111548. (function (BABYLON) {
  111549. var serializedGeometries = [];
  111550. var serializeGeometry = function (geometry, serializationGeometries) {
  111551. if (serializedGeometries[geometry.id]) {
  111552. return;
  111553. }
  111554. if (geometry.doNotSerialize) {
  111555. return;
  111556. }
  111557. if (geometry instanceof BABYLON.BoxGeometry) {
  111558. serializationGeometries.boxes.push(geometry.serialize());
  111559. }
  111560. else if (geometry instanceof BABYLON.SphereGeometry) {
  111561. serializationGeometries.spheres.push(geometry.serialize());
  111562. }
  111563. else if (geometry instanceof BABYLON.CylinderGeometry) {
  111564. serializationGeometries.cylinders.push(geometry.serialize());
  111565. }
  111566. else if (geometry instanceof BABYLON.TorusGeometry) {
  111567. serializationGeometries.toruses.push(geometry.serialize());
  111568. }
  111569. else if (geometry instanceof BABYLON.GroundGeometry) {
  111570. serializationGeometries.grounds.push(geometry.serialize());
  111571. }
  111572. else if (geometry instanceof BABYLON.Plane) {
  111573. serializationGeometries.planes.push(geometry.serialize());
  111574. }
  111575. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  111576. serializationGeometries.torusKnots.push(geometry.serialize());
  111577. }
  111578. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  111579. throw new Error("Unknown primitive type");
  111580. }
  111581. else {
  111582. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  111583. }
  111584. serializedGeometries[geometry.id] = true;
  111585. };
  111586. var serializeMesh = function (mesh, serializationScene) {
  111587. var serializationObject = {};
  111588. // Geometry
  111589. var geometry = mesh._geometry;
  111590. if (geometry) {
  111591. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  111592. // 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
  111593. serializeGeometry(geometry, serializationScene.geometries);
  111594. }
  111595. }
  111596. // Custom
  111597. if (mesh.serialize) {
  111598. mesh.serialize(serializationObject);
  111599. }
  111600. return serializationObject;
  111601. };
  111602. var finalizeSingleMesh = function (mesh, serializationObject) {
  111603. //only works if the mesh is already loaded
  111604. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  111605. //serialize material
  111606. if (mesh.material) {
  111607. if (mesh.material instanceof BABYLON.MultiMaterial) {
  111608. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  111609. serializationObject.materials = serializationObject.materials || [];
  111610. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  111611. serializationObject.multiMaterials.push(mesh.material.serialize());
  111612. var _loop_1 = function (submaterial) {
  111613. if (submaterial) {
  111614. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  111615. serializationObject.materials.push(submaterial.serialize());
  111616. }
  111617. }
  111618. };
  111619. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  111620. var submaterial = _a[_i];
  111621. _loop_1(submaterial);
  111622. }
  111623. }
  111624. }
  111625. else {
  111626. serializationObject.materials = serializationObject.materials || [];
  111627. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  111628. serializationObject.materials.push(mesh.material.serialize());
  111629. }
  111630. }
  111631. }
  111632. //serialize geometry
  111633. var geometry = mesh._geometry;
  111634. if (geometry) {
  111635. if (!serializationObject.geometries) {
  111636. serializationObject.geometries = {};
  111637. serializationObject.geometries.boxes = [];
  111638. serializationObject.geometries.spheres = [];
  111639. serializationObject.geometries.cylinders = [];
  111640. serializationObject.geometries.toruses = [];
  111641. serializationObject.geometries.grounds = [];
  111642. serializationObject.geometries.planes = [];
  111643. serializationObject.geometries.torusKnots = [];
  111644. serializationObject.geometries.vertexData = [];
  111645. }
  111646. serializeGeometry(geometry, serializationObject.geometries);
  111647. }
  111648. // Skeletons
  111649. if (mesh.skeleton) {
  111650. serializationObject.skeletons = serializationObject.skeletons || [];
  111651. serializationObject.skeletons.push(mesh.skeleton.serialize());
  111652. }
  111653. //serialize the actual mesh
  111654. serializationObject.meshes = serializationObject.meshes || [];
  111655. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  111656. }
  111657. };
  111658. /**
  111659. * Class used to serialize a scene into a string
  111660. */
  111661. var SceneSerializer = /** @class */ (function () {
  111662. function SceneSerializer() {
  111663. }
  111664. /**
  111665. * Clear cache used by a previous serialization
  111666. */
  111667. SceneSerializer.ClearCache = function () {
  111668. serializedGeometries = [];
  111669. };
  111670. /**
  111671. * Serialize a scene into a JSON compatible object
  111672. * @param scene defines the scene to serialize
  111673. * @returns a JSON compatible object
  111674. */
  111675. SceneSerializer.Serialize = function (scene) {
  111676. var serializationObject = {};
  111677. SceneSerializer.ClearCache();
  111678. // Scene
  111679. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  111680. serializationObject.autoClear = scene.autoClear;
  111681. serializationObject.clearColor = scene.clearColor.asArray();
  111682. serializationObject.ambientColor = scene.ambientColor.asArray();
  111683. serializationObject.gravity = scene.gravity.asArray();
  111684. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  111685. serializationObject.workerCollisions = scene.workerCollisions;
  111686. // Fog
  111687. if (scene.fogMode && scene.fogMode !== 0) {
  111688. serializationObject.fogMode = scene.fogMode;
  111689. serializationObject.fogColor = scene.fogColor.asArray();
  111690. serializationObject.fogStart = scene.fogStart;
  111691. serializationObject.fogEnd = scene.fogEnd;
  111692. serializationObject.fogDensity = scene.fogDensity;
  111693. }
  111694. //Physics
  111695. if (scene.isPhysicsEnabled()) {
  111696. var physicEngine = scene.getPhysicsEngine();
  111697. if (physicEngine) {
  111698. serializationObject.physicsEnabled = true;
  111699. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  111700. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  111701. }
  111702. }
  111703. // Metadata
  111704. if (scene.metadata) {
  111705. serializationObject.metadata = scene.metadata;
  111706. }
  111707. // Morph targets
  111708. serializationObject.morphTargetManagers = [];
  111709. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  111710. var abstractMesh = _a[_i];
  111711. var manager = abstractMesh.morphTargetManager;
  111712. if (manager) {
  111713. serializationObject.morphTargetManagers.push(manager.serialize());
  111714. }
  111715. }
  111716. // Lights
  111717. serializationObject.lights = [];
  111718. var index;
  111719. var light;
  111720. for (index = 0; index < scene.lights.length; index++) {
  111721. light = scene.lights[index];
  111722. if (!light.doNotSerialize) {
  111723. serializationObject.lights.push(light.serialize());
  111724. }
  111725. }
  111726. // Cameras
  111727. serializationObject.cameras = [];
  111728. for (index = 0; index < scene.cameras.length; index++) {
  111729. var camera = scene.cameras[index];
  111730. if (!camera.doNotSerialize) {
  111731. serializationObject.cameras.push(camera.serialize());
  111732. }
  111733. }
  111734. if (scene.activeCamera) {
  111735. serializationObject.activeCameraID = scene.activeCamera.id;
  111736. }
  111737. // Animations
  111738. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  111739. // Materials
  111740. serializationObject.materials = [];
  111741. serializationObject.multiMaterials = [];
  111742. var material;
  111743. for (index = 0; index < scene.materials.length; index++) {
  111744. material = scene.materials[index];
  111745. if (!material.doNotSerialize) {
  111746. serializationObject.materials.push(material.serialize());
  111747. }
  111748. }
  111749. // MultiMaterials
  111750. serializationObject.multiMaterials = [];
  111751. for (index = 0; index < scene.multiMaterials.length; index++) {
  111752. var multiMaterial = scene.multiMaterials[index];
  111753. serializationObject.multiMaterials.push(multiMaterial.serialize());
  111754. }
  111755. // Environment texture
  111756. if (scene.environmentTexture) {
  111757. serializationObject.environmentTexture = scene.environmentTexture.name;
  111758. }
  111759. // Skeletons
  111760. serializationObject.skeletons = [];
  111761. for (index = 0; index < scene.skeletons.length; index++) {
  111762. var skeleton = scene.skeletons[index];
  111763. if (!skeleton.doNotSerialize) {
  111764. serializationObject.skeletons.push(skeleton.serialize());
  111765. }
  111766. }
  111767. // Transform nodes
  111768. serializationObject.transformNodes = [];
  111769. for (index = 0; index < scene.transformNodes.length; index++) {
  111770. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  111771. }
  111772. // Geometries
  111773. serializationObject.geometries = {};
  111774. serializationObject.geometries.boxes = [];
  111775. serializationObject.geometries.spheres = [];
  111776. serializationObject.geometries.cylinders = [];
  111777. serializationObject.geometries.toruses = [];
  111778. serializationObject.geometries.grounds = [];
  111779. serializationObject.geometries.planes = [];
  111780. serializationObject.geometries.torusKnots = [];
  111781. serializationObject.geometries.vertexData = [];
  111782. serializedGeometries = [];
  111783. var geometries = scene.getGeometries();
  111784. for (index = 0; index < geometries.length; index++) {
  111785. var geometry = geometries[index];
  111786. if (geometry.isReady()) {
  111787. serializeGeometry(geometry, serializationObject.geometries);
  111788. }
  111789. }
  111790. // Meshes
  111791. serializationObject.meshes = [];
  111792. for (index = 0; index < scene.meshes.length; index++) {
  111793. var abstractMesh = scene.meshes[index];
  111794. if (abstractMesh instanceof BABYLON.Mesh) {
  111795. var mesh = abstractMesh;
  111796. if (!mesh.doNotSerialize) {
  111797. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  111798. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  111799. }
  111800. }
  111801. }
  111802. }
  111803. // Particles Systems
  111804. serializationObject.particleSystems = [];
  111805. for (index = 0; index < scene.particleSystems.length; index++) {
  111806. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  111807. }
  111808. // Action Manager
  111809. if (scene.actionManager) {
  111810. serializationObject.actions = scene.actionManager.serialize("scene");
  111811. }
  111812. // Components
  111813. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  111814. var component = _c[_b];
  111815. component.serialize(serializationObject);
  111816. }
  111817. return serializationObject;
  111818. };
  111819. /**
  111820. * Serialize a mesh into a JSON compatible object
  111821. * @param toSerialize defines the mesh to serialize
  111822. * @param withParents defines if parents must be serialized as well
  111823. * @param withChildren defines if children must be serialized as well
  111824. * @returns a JSON compatible object
  111825. */
  111826. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  111827. if (withParents === void 0) { withParents = false; }
  111828. if (withChildren === void 0) { withChildren = false; }
  111829. var serializationObject = {};
  111830. SceneSerializer.ClearCache();
  111831. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  111832. if (withParents || withChildren) {
  111833. //deliberate for loop! not for each, appended should be processed as well.
  111834. for (var i = 0; i < toSerialize.length; ++i) {
  111835. if (withChildren) {
  111836. toSerialize[i].getDescendants().forEach(function (node) {
  111837. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  111838. toSerialize.push(node);
  111839. }
  111840. });
  111841. }
  111842. //make sure the array doesn't contain the object already
  111843. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  111844. toSerialize.push(toSerialize[i].parent);
  111845. }
  111846. }
  111847. }
  111848. toSerialize.forEach(function (mesh) {
  111849. finalizeSingleMesh(mesh, serializationObject);
  111850. });
  111851. return serializationObject;
  111852. };
  111853. return SceneSerializer;
  111854. }());
  111855. BABYLON.SceneSerializer = SceneSerializer;
  111856. })(BABYLON || (BABYLON = {}));
  111857. //# sourceMappingURL=babylon.sceneSerializer.js.map
  111858. var BABYLON;
  111859. (function (BABYLON) {
  111860. /**
  111861. * Class used to generate realtime reflection / refraction cube textures
  111862. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  111863. */
  111864. var ReflectionProbe = /** @class */ (function () {
  111865. /**
  111866. * Creates a new reflection probe
  111867. * @param name defines the name of the probe
  111868. * @param size defines the texture resolution (for each face)
  111869. * @param scene defines the hosting scene
  111870. * @param generateMipMaps defines if mip maps should be generated automatically (true by default)
  111871. * @param useFloat defines if HDR data (flaot data) should be used to store colors (false by default)
  111872. */
  111873. function ReflectionProbe(
  111874. /** defines the name of the probe */
  111875. name, size, scene, generateMipMaps, useFloat) {
  111876. if (generateMipMaps === void 0) { generateMipMaps = true; }
  111877. if (useFloat === void 0) { useFloat = false; }
  111878. var _this = this;
  111879. this.name = name;
  111880. this._viewMatrix = BABYLON.Matrix.Identity();
  111881. this._target = BABYLON.Vector3.Zero();
  111882. this._add = BABYLON.Vector3.Zero();
  111883. this._invertYAxis = false;
  111884. /** Gets or sets probe position (center of the cube map) */
  111885. this.position = BABYLON.Vector3.Zero();
  111886. this._scene = scene;
  111887. // Create the scene field if not exist.
  111888. if (!this._scene.reflectionProbes) {
  111889. this._scene.reflectionProbes = new Array();
  111890. }
  111891. this._scene.reflectionProbes.push(this);
  111892. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  111893. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  111894. switch (faceIndex) {
  111895. case 0:
  111896. _this._add.copyFromFloats(1, 0, 0);
  111897. break;
  111898. case 1:
  111899. _this._add.copyFromFloats(-1, 0, 0);
  111900. break;
  111901. case 2:
  111902. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  111903. break;
  111904. case 3:
  111905. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  111906. break;
  111907. case 4:
  111908. _this._add.copyFromFloats(0, 0, 1);
  111909. break;
  111910. case 5:
  111911. _this._add.copyFromFloats(0, 0, -1);
  111912. break;
  111913. }
  111914. if (_this._attachedMesh) {
  111915. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  111916. }
  111917. _this.position.addToRef(_this._add, _this._target);
  111918. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  111919. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  111920. scene._forcedViewPosition = _this.position;
  111921. });
  111922. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  111923. scene._forcedViewPosition = null;
  111924. scene.updateTransformMatrix(true);
  111925. });
  111926. if (scene.activeCamera) {
  111927. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  111928. }
  111929. }
  111930. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  111931. /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
  111932. get: function () {
  111933. return this._renderTargetTexture.samples;
  111934. },
  111935. set: function (value) {
  111936. this._renderTargetTexture.samples = value;
  111937. },
  111938. enumerable: true,
  111939. configurable: true
  111940. });
  111941. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  111942. /** Gets or sets the refresh rate to use (on every frame by default) */
  111943. get: function () {
  111944. return this._renderTargetTexture.refreshRate;
  111945. },
  111946. set: function (value) {
  111947. this._renderTargetTexture.refreshRate = value;
  111948. },
  111949. enumerable: true,
  111950. configurable: true
  111951. });
  111952. /**
  111953. * Gets the hosting scene
  111954. * @returns a Scene
  111955. */
  111956. ReflectionProbe.prototype.getScene = function () {
  111957. return this._scene;
  111958. };
  111959. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  111960. /** Gets the internal CubeTexture used to render to */
  111961. get: function () {
  111962. return this._renderTargetTexture;
  111963. },
  111964. enumerable: true,
  111965. configurable: true
  111966. });
  111967. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  111968. /** Gets the list of meshes to render */
  111969. get: function () {
  111970. return this._renderTargetTexture.renderList;
  111971. },
  111972. enumerable: true,
  111973. configurable: true
  111974. });
  111975. /**
  111976. * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)
  111977. * @param mesh defines the mesh to attach to
  111978. */
  111979. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  111980. this._attachedMesh = mesh;
  111981. };
  111982. /**
  111983. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups
  111984. * @param renderingGroupId The rendering group id corresponding to its index
  111985. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  111986. */
  111987. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  111988. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  111989. };
  111990. /**
  111991. * Clean all associated resources
  111992. */
  111993. ReflectionProbe.prototype.dispose = function () {
  111994. var index = this._scene.reflectionProbes.indexOf(this);
  111995. if (index !== -1) {
  111996. // Remove from the scene if found
  111997. this._scene.reflectionProbes.splice(index, 1);
  111998. }
  111999. if (this._renderTargetTexture) {
  112000. this._renderTargetTexture.dispose();
  112001. this._renderTargetTexture = null;
  112002. }
  112003. };
  112004. return ReflectionProbe;
  112005. }());
  112006. BABYLON.ReflectionProbe = ReflectionProbe;
  112007. })(BABYLON || (BABYLON = {}));
  112008. //# sourceMappingURL=babylon.reflectionProbe.js.map
  112009. var BABYLON;
  112010. (function (BABYLON) {
  112011. /**
  112012. * Defines the layer scene component responsible to manage any layers
  112013. * in a given scene.
  112014. */
  112015. var LayerSceneComponent = /** @class */ (function () {
  112016. /**
  112017. * Creates a new instance of the component for the given scene
  112018. * @param scene Defines the scene to register the component in
  112019. */
  112020. function LayerSceneComponent(scene) {
  112021. /**
  112022. * The component name helpfull to identify the component in the list of scene components.
  112023. */
  112024. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  112025. this.scene = scene;
  112026. this._engine = scene.getEngine();
  112027. scene.layers = new Array();
  112028. }
  112029. /**
  112030. * Registers the component in a given scene
  112031. */
  112032. LayerSceneComponent.prototype.register = function () {
  112033. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  112034. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  112035. };
  112036. /**
  112037. * Rebuilds the elements related to this component in case of
  112038. * context lost for instance.
  112039. */
  112040. LayerSceneComponent.prototype.rebuild = function () {
  112041. var layers = this.scene.layers;
  112042. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  112043. var layer = layers_1[_i];
  112044. layer._rebuild();
  112045. }
  112046. };
  112047. /**
  112048. * Disposes the component and the associated ressources.
  112049. */
  112050. LayerSceneComponent.prototype.dispose = function () {
  112051. var layers = this.scene.layers;
  112052. while (layers.length) {
  112053. layers[0].dispose();
  112054. }
  112055. };
  112056. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  112057. var layers = this.scene.layers;
  112058. if (layers.length) {
  112059. this._engine.setDepthBuffer(false);
  112060. var cameraLayerMask = camera.layerMask;
  112061. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  112062. var layer = layers_2[_i];
  112063. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  112064. layer.render();
  112065. }
  112066. }
  112067. this._engine.setDepthBuffer(true);
  112068. }
  112069. };
  112070. LayerSceneComponent.prototype._drawBackground = function (camera) {
  112071. this._draw(camera, true);
  112072. };
  112073. LayerSceneComponent.prototype._drawForeground = function (camera) {
  112074. this._draw(camera, false);
  112075. };
  112076. return LayerSceneComponent;
  112077. }());
  112078. BABYLON.LayerSceneComponent = LayerSceneComponent;
  112079. })(BABYLON || (BABYLON = {}));
  112080. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  112081. var BABYLON;
  112082. (function (BABYLON) {
  112083. /**
  112084. * This represents a full screen 2d layer.
  112085. * This can be usefull to display a picture in the background of your scene for instance.
  112086. * @see https://www.babylonjs-playground.com/#08A2BS#1
  112087. */
  112088. var Layer = /** @class */ (function () {
  112089. /**
  112090. * Instantiates a new layer.
  112091. * This represents a full screen 2d layer.
  112092. * This can be usefull to display a picture in the background of your scene for instance.
  112093. * @see https://www.babylonjs-playground.com/#08A2BS#1
  112094. * @param name Define the name of the layer in the scene
  112095. * @param imgUrl Define the url of the texture to display in the layer
  112096. * @param scene Define the scene the layer belongs to
  112097. * @param isBackground Defines whether the layer is displayed in front or behind the scene
  112098. * @param color Defines a color for the layer
  112099. */
  112100. function Layer(
  112101. /**
  112102. * Define the name of the layer.
  112103. */
  112104. name, imgUrl, scene, isBackground, color) {
  112105. this.name = name;
  112106. /**
  112107. * Define the scale of the layer in order to zoom in out of the texture.
  112108. */
  112109. this.scale = new BABYLON.Vector2(1, 1);
  112110. /**
  112111. * Define an offset for the layer in order to shift the texture.
  112112. */
  112113. this.offset = new BABYLON.Vector2(0, 0);
  112114. /**
  112115. * Define the alpha blending mode used in the layer in case the texture or color has an alpha.
  112116. */
  112117. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  112118. /**
  112119. * Define a mask to restrict the layer to only some of the scene cameras.
  112120. */
  112121. this.layerMask = 0x0FFFFFFF;
  112122. this._vertexBuffers = {};
  112123. /**
  112124. * An event triggered when the layer is disposed.
  112125. */
  112126. this.onDisposeObservable = new BABYLON.Observable();
  112127. /**
  112128. * An event triggered before rendering the scene
  112129. */
  112130. this.onBeforeRenderObservable = new BABYLON.Observable();
  112131. /**
  112132. * An event triggered after rendering the scene
  112133. */
  112134. this.onAfterRenderObservable = new BABYLON.Observable();
  112135. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  112136. this.isBackground = isBackground === undefined ? true : isBackground;
  112137. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  112138. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  112139. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  112140. if (!layerComponent) {
  112141. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  112142. this._scene._addComponent(layerComponent);
  112143. }
  112144. this._scene.layers.push(this);
  112145. var engine = this._scene.getEngine();
  112146. // VBO
  112147. var vertices = [];
  112148. vertices.push(1, 1);
  112149. vertices.push(-1, 1);
  112150. vertices.push(-1, -1);
  112151. vertices.push(1, -1);
  112152. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  112153. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  112154. this._createIndexBuffer();
  112155. // Effects
  112156. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  112157. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  112158. }
  112159. Object.defineProperty(Layer.prototype, "onDispose", {
  112160. /**
  112161. * Back compatibility with callback before the onDisposeObservable existed.
  112162. * The set callback will be triggered when the layer has been disposed.
  112163. */
  112164. set: function (callback) {
  112165. if (this._onDisposeObserver) {
  112166. this.onDisposeObservable.remove(this._onDisposeObserver);
  112167. }
  112168. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  112169. },
  112170. enumerable: true,
  112171. configurable: true
  112172. });
  112173. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  112174. /**
  112175. * Back compatibility with callback before the onBeforeRenderObservable existed.
  112176. * The set callback will be triggered just before rendering the layer.
  112177. */
  112178. set: function (callback) {
  112179. if (this._onBeforeRenderObserver) {
  112180. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  112181. }
  112182. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  112183. },
  112184. enumerable: true,
  112185. configurable: true
  112186. });
  112187. Object.defineProperty(Layer.prototype, "onAfterRender", {
  112188. /**
  112189. * Back compatibility with callback before the onAfterRenderObservable existed.
  112190. * The set callback will be triggered just after rendering the layer.
  112191. */
  112192. set: function (callback) {
  112193. if (this._onAfterRenderObserver) {
  112194. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  112195. }
  112196. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  112197. },
  112198. enumerable: true,
  112199. configurable: true
  112200. });
  112201. Layer.prototype._createIndexBuffer = function () {
  112202. var engine = this._scene.getEngine();
  112203. // Indices
  112204. var indices = [];
  112205. indices.push(0);
  112206. indices.push(1);
  112207. indices.push(2);
  112208. indices.push(0);
  112209. indices.push(2);
  112210. indices.push(3);
  112211. this._indexBuffer = engine.createIndexBuffer(indices);
  112212. };
  112213. /** @hidden */
  112214. Layer.prototype._rebuild = function () {
  112215. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  112216. if (vb) {
  112217. vb._rebuild();
  112218. }
  112219. this._createIndexBuffer();
  112220. };
  112221. /**
  112222. * Renders the layer in the scene.
  112223. */
  112224. Layer.prototype.render = function () {
  112225. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  112226. // Check
  112227. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady()) {
  112228. return;
  112229. }
  112230. var engine = this._scene.getEngine();
  112231. this.onBeforeRenderObservable.notifyObservers(this);
  112232. // Render
  112233. engine.enableEffect(currentEffect);
  112234. engine.setState(false);
  112235. // Texture
  112236. currentEffect.setTexture("textureSampler", this.texture);
  112237. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  112238. // Color
  112239. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  112240. // Scale / offset
  112241. currentEffect.setVector2("offset", this.offset);
  112242. currentEffect.setVector2("scale", this.scale);
  112243. // VBOs
  112244. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  112245. // Draw order
  112246. if (!this.alphaTest) {
  112247. engine.setAlphaMode(this.alphaBlendingMode);
  112248. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  112249. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  112250. }
  112251. else {
  112252. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  112253. }
  112254. this.onAfterRenderObservable.notifyObservers(this);
  112255. };
  112256. /**
  112257. * Disposes and releases the associated ressources.
  112258. */
  112259. Layer.prototype.dispose = function () {
  112260. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  112261. if (vertexBuffer) {
  112262. vertexBuffer.dispose();
  112263. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  112264. }
  112265. if (this._indexBuffer) {
  112266. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  112267. this._indexBuffer = null;
  112268. }
  112269. if (this.texture) {
  112270. this.texture.dispose();
  112271. this.texture = null;
  112272. }
  112273. // Remove from scene
  112274. var index = this._scene.layers.indexOf(this);
  112275. this._scene.layers.splice(index, 1);
  112276. // Callback
  112277. this.onDisposeObservable.notifyObservers(this);
  112278. this.onDisposeObservable.clear();
  112279. this.onAfterRenderObservable.clear();
  112280. this.onBeforeRenderObservable.clear();
  112281. };
  112282. return Layer;
  112283. }());
  112284. BABYLON.Layer = Layer;
  112285. })(BABYLON || (BABYLON = {}));
  112286. //# sourceMappingURL=babylon.layer.js.map
  112287. var BABYLON;
  112288. (function (BABYLON) {
  112289. /**
  112290. * Class used to host texture specific utilities
  112291. */
  112292. var TextureTools = /** @class */ (function () {
  112293. function TextureTools() {
  112294. }
  112295. /**
  112296. * Uses the GPU to create a copy texture rescaled at a given size
  112297. * @param texture Texture to copy from
  112298. * @param width defines the desired width
  112299. * @param height defines the desired height
  112300. * @param useBilinearMode defines if bilinear mode has to be used
  112301. * @return the generated texture
  112302. */
  112303. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  112304. if (useBilinearMode === void 0) { useBilinearMode = true; }
  112305. var scene = texture.getScene();
  112306. var engine = scene.getEngine();
  112307. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  112308. rtt.wrapU = texture.wrapU;
  112309. rtt.wrapV = texture.wrapV;
  112310. rtt.uOffset = texture.uOffset;
  112311. rtt.vOffset = texture.vOffset;
  112312. rtt.uScale = texture.uScale;
  112313. rtt.vScale = texture.vScale;
  112314. rtt.uAng = texture.uAng;
  112315. rtt.vAng = texture.vAng;
  112316. rtt.wAng = texture.wAng;
  112317. rtt.coordinatesIndex = texture.coordinatesIndex;
  112318. rtt.level = texture.level;
  112319. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  112320. rtt._texture.isReady = false;
  112321. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112322. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112323. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  112324. passPostProcess.getEffect().executeWhenCompiled(function () {
  112325. passPostProcess.onApply = function (effect) {
  112326. effect.setTexture("textureSampler", texture);
  112327. };
  112328. var internalTexture = rtt.getInternalTexture();
  112329. if (internalTexture) {
  112330. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  112331. engine.unBindFramebuffer(internalTexture);
  112332. rtt.disposeFramebufferObjects();
  112333. passPostProcess.dispose();
  112334. internalTexture.isReady = true;
  112335. }
  112336. });
  112337. return rtt;
  112338. };
  112339. /**
  112340. * Gets an environment BRDF texture for a given scene
  112341. * @param scene defines the hosting scene
  112342. * @returns the environment BRDF texture
  112343. */
  112344. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  112345. if (!scene._environmentBRDFTexture) {
  112346. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  112347. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112348. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112349. scene._environmentBRDFTexture = texture;
  112350. }
  112351. return scene._environmentBRDFTexture;
  112352. };
  112353. 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=";
  112354. return TextureTools;
  112355. }());
  112356. BABYLON.TextureTools = TextureTools;
  112357. })(BABYLON || (BABYLON = {}));
  112358. //# sourceMappingURL=babylon.textureTools.js.map
  112359. var BABYLON;
  112360. (function (BABYLON) {
  112361. /**
  112362. * 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.
  112363. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  112364. */
  112365. var FramingBehavior = /** @class */ (function () {
  112366. function FramingBehavior() {
  112367. this._mode = FramingBehavior.FitFrustumSidesMode;
  112368. this._radiusScale = 1.0;
  112369. this._positionScale = 0.5;
  112370. this._defaultElevation = 0.3;
  112371. this._elevationReturnTime = 1500;
  112372. this._elevationReturnWaitTime = 1000;
  112373. this._zoomStopsAnimation = false;
  112374. this._framingTime = 1500;
  112375. /**
  112376. * Define if the behavior should automatically change the configured
  112377. * camera limits and sensibilities.
  112378. */
  112379. this.autoCorrectCameraLimitsAndSensibility = true;
  112380. this._isPointerDown = false;
  112381. this._lastInteractionTime = -Infinity;
  112382. // Framing control
  112383. this._animatables = new Array();
  112384. this._betaIsAnimating = false;
  112385. }
  112386. Object.defineProperty(FramingBehavior.prototype, "name", {
  112387. /**
  112388. * Gets the name of the behavior.
  112389. */
  112390. get: function () {
  112391. return "Framing";
  112392. },
  112393. enumerable: true,
  112394. configurable: true
  112395. });
  112396. Object.defineProperty(FramingBehavior.prototype, "mode", {
  112397. /**
  112398. * Gets current mode used by the behavior.
  112399. */
  112400. get: function () {
  112401. return this._mode;
  112402. },
  112403. /**
  112404. * Sets the current mode used by the behavior
  112405. */
  112406. set: function (mode) {
  112407. this._mode = mode;
  112408. },
  112409. enumerable: true,
  112410. configurable: true
  112411. });
  112412. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  112413. /**
  112414. * Gets the scale applied to the radius
  112415. */
  112416. get: function () {
  112417. return this._radiusScale;
  112418. },
  112419. /**
  112420. * Sets the scale applied to the radius (1 by default)
  112421. */
  112422. set: function (radius) {
  112423. this._radiusScale = radius;
  112424. },
  112425. enumerable: true,
  112426. configurable: true
  112427. });
  112428. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  112429. /**
  112430. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  112431. */
  112432. get: function () {
  112433. return this._positionScale;
  112434. },
  112435. /**
  112436. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  112437. */
  112438. set: function (scale) {
  112439. this._positionScale = scale;
  112440. },
  112441. enumerable: true,
  112442. configurable: true
  112443. });
  112444. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  112445. /**
  112446. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  112447. * behaviour is triggered, in radians.
  112448. */
  112449. get: function () {
  112450. return this._defaultElevation;
  112451. },
  112452. /**
  112453. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  112454. * behaviour is triggered, in radians.
  112455. */
  112456. set: function (elevation) {
  112457. this._defaultElevation = elevation;
  112458. },
  112459. enumerable: true,
  112460. configurable: true
  112461. });
  112462. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  112463. /**
  112464. * Gets the time (in milliseconds) taken to return to the default beta position.
  112465. * Negative value indicates camera should not return to default.
  112466. */
  112467. get: function () {
  112468. return this._elevationReturnTime;
  112469. },
  112470. /**
  112471. * Sets the time (in milliseconds) taken to return to the default beta position.
  112472. * Negative value indicates camera should not return to default.
  112473. */
  112474. set: function (speed) {
  112475. this._elevationReturnTime = speed;
  112476. },
  112477. enumerable: true,
  112478. configurable: true
  112479. });
  112480. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  112481. /**
  112482. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  112483. */
  112484. get: function () {
  112485. return this._elevationReturnWaitTime;
  112486. },
  112487. /**
  112488. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  112489. */
  112490. set: function (time) {
  112491. this._elevationReturnWaitTime = time;
  112492. },
  112493. enumerable: true,
  112494. configurable: true
  112495. });
  112496. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  112497. /**
  112498. * Gets the flag that indicates if user zooming should stop animation.
  112499. */
  112500. get: function () {
  112501. return this._zoomStopsAnimation;
  112502. },
  112503. /**
  112504. * Sets the flag that indicates if user zooming should stop animation.
  112505. */
  112506. set: function (flag) {
  112507. this._zoomStopsAnimation = flag;
  112508. },
  112509. enumerable: true,
  112510. configurable: true
  112511. });
  112512. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  112513. /**
  112514. * Gets the transition time when framing the mesh, in milliseconds
  112515. */
  112516. get: function () {
  112517. return this._framingTime;
  112518. },
  112519. /**
  112520. * Sets the transition time when framing the mesh, in milliseconds
  112521. */
  112522. set: function (time) {
  112523. this._framingTime = time;
  112524. },
  112525. enumerable: true,
  112526. configurable: true
  112527. });
  112528. /**
  112529. * Initializes the behavior.
  112530. */
  112531. FramingBehavior.prototype.init = function () {
  112532. // Do notihng
  112533. };
  112534. /**
  112535. * Attaches the behavior to its arc rotate camera.
  112536. * @param camera Defines the camera to attach the behavior to
  112537. */
  112538. FramingBehavior.prototype.attach = function (camera) {
  112539. var _this = this;
  112540. this._attachedCamera = camera;
  112541. var scene = this._attachedCamera.getScene();
  112542. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  112543. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  112544. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  112545. _this._isPointerDown = true;
  112546. return;
  112547. }
  112548. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  112549. _this._isPointerDown = false;
  112550. }
  112551. });
  112552. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  112553. if (mesh) {
  112554. _this.zoomOnMesh(mesh);
  112555. }
  112556. });
  112557. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  112558. // Stop the animation if there is user interaction and the animation should stop for this interaction
  112559. _this._applyUserInteraction();
  112560. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  112561. // back to the default position after a given timeout
  112562. _this._maintainCameraAboveGround();
  112563. });
  112564. };
  112565. /**
  112566. * Detaches the behavior from its current arc rotate camera.
  112567. */
  112568. FramingBehavior.prototype.detach = function () {
  112569. if (!this._attachedCamera) {
  112570. return;
  112571. }
  112572. var scene = this._attachedCamera.getScene();
  112573. if (this._onPrePointerObservableObserver) {
  112574. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  112575. }
  112576. if (this._onAfterCheckInputsObserver) {
  112577. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  112578. }
  112579. if (this._onMeshTargetChangedObserver) {
  112580. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  112581. }
  112582. this._attachedCamera = null;
  112583. };
  112584. /**
  112585. * Targets the given mesh and updates zoom level accordingly.
  112586. * @param mesh The mesh to target.
  112587. * @param radius Optional. If a cached radius position already exists, overrides default.
  112588. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  112589. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  112590. * @param onAnimationEnd Callback triggered at the end of the framing animation
  112591. */
  112592. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  112593. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  112594. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  112595. mesh.computeWorldMatrix(true);
  112596. var boundingBox = mesh.getBoundingInfo().boundingBox;
  112597. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  112598. };
  112599. /**
  112600. * Targets the given mesh with its children and updates zoom level accordingly.
  112601. * @param mesh The mesh to target.
  112602. * @param radius Optional. If a cached radius position already exists, overrides default.
  112603. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  112604. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  112605. * @param onAnimationEnd Callback triggered at the end of the framing animation
  112606. */
  112607. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  112608. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  112609. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  112610. mesh.computeWorldMatrix(true);
  112611. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  112612. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  112613. };
  112614. /**
  112615. * Targets the given meshes with their children and updates zoom level accordingly.
  112616. * @param meshes The mesh to target.
  112617. * @param radius Optional. If a cached radius position already exists, overrides default.
  112618. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  112619. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  112620. * @param onAnimationEnd Callback triggered at the end of the framing animation
  112621. */
  112622. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  112623. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  112624. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  112625. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  112626. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  112627. for (var i = 0; i < meshes.length; i++) {
  112628. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  112629. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  112630. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  112631. }
  112632. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  112633. };
  112634. /**
  112635. * Targets the bounding box info defined by its extends and updates zoom level accordingly.
  112636. * @param minimumWorld Determines the smaller position of the bounding box extend
  112637. * @param maximumWorld Determines the bigger position of the bounding box extend
  112638. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  112639. * @param onAnimationEnd Callback triggered at the end of the framing animation
  112640. */
  112641. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  112642. var _this = this;
  112643. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  112644. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  112645. var zoomTarget;
  112646. if (!this._attachedCamera) {
  112647. return;
  112648. }
  112649. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  112650. var bottom = minimumWorld.y;
  112651. var top = maximumWorld.y;
  112652. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  112653. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  112654. if (focusOnOriginXZ) {
  112655. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  112656. }
  112657. else {
  112658. var centerWorld = minimumWorld.add(radiusWorld);
  112659. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  112660. }
  112661. if (!this._vectorTransition) {
  112662. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  112663. }
  112664. this._betaIsAnimating = true;
  112665. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  112666. if (animatable) {
  112667. this._animatables.push(animatable);
  112668. }
  112669. // sets the radius and lower radius bounds
  112670. // Small delta ensures camera is not always at lower zoom limit.
  112671. var radius = 0;
  112672. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  112673. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  112674. if (this.autoCorrectCameraLimitsAndSensibility) {
  112675. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  112676. }
  112677. radius = position;
  112678. }
  112679. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  112680. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  112681. if (this.autoCorrectCameraLimitsAndSensibility && this._attachedCamera.lowerRadiusLimit === null) {
  112682. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  112683. }
  112684. }
  112685. // Set sensibilities
  112686. if (this.autoCorrectCameraLimitsAndSensibility) {
  112687. var extend = maximumWorld.subtract(minimumWorld).length();
  112688. this._attachedCamera.panningSensibility = 5000 / extend;
  112689. this._attachedCamera.wheelPrecision = 100 / radius;
  112690. }
  112691. // transition to new radius
  112692. if (!this._radiusTransition) {
  112693. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  112694. }
  112695. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  112696. _this.stopAllAnimations();
  112697. if (onAnimationEnd) {
  112698. onAnimationEnd();
  112699. }
  112700. if (_this._attachedCamera && _this._attachedCamera.useInputToRestoreState) {
  112701. _this._attachedCamera.storeState();
  112702. }
  112703. });
  112704. if (animatable) {
  112705. this._animatables.push(animatable);
  112706. }
  112707. };
  112708. /**
  112709. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  112710. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  112711. * frustum width.
  112712. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  112713. * to fully enclose the mesh in the viewing frustum.
  112714. */
  112715. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  112716. var size = maximumWorld.subtract(minimumWorld);
  112717. var boxVectorGlobalDiagonal = size.length();
  112718. var frustumSlope = this._getFrustumSlope();
  112719. // Formula for setting distance
  112720. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  112721. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  112722. // Horizon distance
  112723. var radius = radiusWithoutFraming * this._radiusScale;
  112724. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  112725. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  112726. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  112727. var camera = this._attachedCamera;
  112728. if (!camera) {
  112729. return 0;
  112730. }
  112731. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  112732. // Don't exceed the requested limit
  112733. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  112734. }
  112735. // Don't exceed the upper radius limit
  112736. if (camera.upperRadiusLimit) {
  112737. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  112738. }
  112739. return distance;
  112740. };
  112741. /**
  112742. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  112743. * is automatically returned to its default position (expected to be above ground plane).
  112744. */
  112745. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  112746. var _this = this;
  112747. if (this._elevationReturnTime < 0) {
  112748. return;
  112749. }
  112750. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  112751. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  112752. var limitBeta = Math.PI * 0.5;
  112753. // Bring the camera back up if below the ground plane
  112754. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  112755. this._betaIsAnimating = true;
  112756. //Transition to new position
  112757. this.stopAllAnimations();
  112758. if (!this._betaTransition) {
  112759. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  112760. }
  112761. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  112762. _this._clearAnimationLocks();
  112763. _this.stopAllAnimations();
  112764. });
  112765. if (animatabe) {
  112766. this._animatables.push(animatabe);
  112767. }
  112768. }
  112769. };
  112770. /**
  112771. * Returns the frustum slope based on the canvas ratio and camera FOV
  112772. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  112773. */
  112774. FramingBehavior.prototype._getFrustumSlope = function () {
  112775. // Calculate the viewport ratio
  112776. // Aspect Ratio is Height/Width.
  112777. var camera = this._attachedCamera;
  112778. if (!camera) {
  112779. return BABYLON.Vector2.Zero();
  112780. }
  112781. var engine = camera.getScene().getEngine();
  112782. var aspectRatio = engine.getAspectRatio(camera);
  112783. // Camera FOV is the vertical field of view (top-bottom) in radians.
  112784. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  112785. var frustumSlopeY = Math.tan(camera.fov / 2);
  112786. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  112787. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  112788. // along the forward vector.
  112789. var frustumSlopeX = frustumSlopeY * aspectRatio;
  112790. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  112791. };
  112792. /**
  112793. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  112794. */
  112795. FramingBehavior.prototype._clearAnimationLocks = function () {
  112796. this._betaIsAnimating = false;
  112797. };
  112798. /**
  112799. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  112800. */
  112801. FramingBehavior.prototype._applyUserInteraction = function () {
  112802. if (this.isUserIsMoving) {
  112803. this._lastInteractionTime = BABYLON.Tools.Now;
  112804. this.stopAllAnimations();
  112805. this._clearAnimationLocks();
  112806. }
  112807. };
  112808. /**
  112809. * Stops and removes all animations that have been applied to the camera
  112810. */
  112811. FramingBehavior.prototype.stopAllAnimations = function () {
  112812. if (this._attachedCamera) {
  112813. this._attachedCamera.animations = [];
  112814. }
  112815. while (this._animatables.length) {
  112816. if (this._animatables[0]) {
  112817. this._animatables[0].onAnimationEnd = null;
  112818. this._animatables[0].stop();
  112819. }
  112820. this._animatables.shift();
  112821. }
  112822. };
  112823. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  112824. /**
  112825. * Gets a value indicating if the user is moving the camera
  112826. */
  112827. get: function () {
  112828. if (!this._attachedCamera) {
  112829. return false;
  112830. }
  112831. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  112832. this._attachedCamera.inertialBetaOffset !== 0 ||
  112833. this._attachedCamera.inertialRadiusOffset !== 0 ||
  112834. this._attachedCamera.inertialPanningX !== 0 ||
  112835. this._attachedCamera.inertialPanningY !== 0 ||
  112836. this._isPointerDown;
  112837. },
  112838. enumerable: true,
  112839. configurable: true
  112840. });
  112841. /**
  112842. * The easing function used by animations
  112843. */
  112844. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  112845. /**
  112846. * The easing mode used by animations
  112847. */
  112848. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  112849. // Statics
  112850. /**
  112851. * The camera can move all the way towards the mesh.
  112852. */
  112853. FramingBehavior.IgnoreBoundsSizeMode = 0;
  112854. /**
  112855. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  112856. */
  112857. FramingBehavior.FitFrustumSidesMode = 1;
  112858. return FramingBehavior;
  112859. }());
  112860. BABYLON.FramingBehavior = FramingBehavior;
  112861. })(BABYLON || (BABYLON = {}));
  112862. //# sourceMappingURL=babylon.framingBehavior.js.map
  112863. var BABYLON;
  112864. (function (BABYLON) {
  112865. /**
  112866. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  112867. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  112868. */
  112869. var BouncingBehavior = /** @class */ (function () {
  112870. function BouncingBehavior() {
  112871. /**
  112872. * The duration of the animation, in milliseconds
  112873. */
  112874. this.transitionDuration = 450;
  112875. /**
  112876. * Length of the distance animated by the transition when lower radius is reached
  112877. */
  112878. this.lowerRadiusTransitionRange = 2;
  112879. /**
  112880. * Length of the distance animated by the transition when upper radius is reached
  112881. */
  112882. this.upperRadiusTransitionRange = -2;
  112883. this._autoTransitionRange = false;
  112884. // Animations
  112885. this._radiusIsAnimating = false;
  112886. this._radiusBounceTransition = null;
  112887. this._animatables = new Array();
  112888. }
  112889. Object.defineProperty(BouncingBehavior.prototype, "name", {
  112890. /**
  112891. * Gets the name of the behavior.
  112892. */
  112893. get: function () {
  112894. return "Bouncing";
  112895. },
  112896. enumerable: true,
  112897. configurable: true
  112898. });
  112899. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  112900. /**
  112901. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  112902. */
  112903. get: function () {
  112904. return this._autoTransitionRange;
  112905. },
  112906. /**
  112907. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  112908. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  112909. */
  112910. set: function (value) {
  112911. var _this = this;
  112912. if (this._autoTransitionRange === value) {
  112913. return;
  112914. }
  112915. this._autoTransitionRange = value;
  112916. var camera = this._attachedCamera;
  112917. if (!camera) {
  112918. return;
  112919. }
  112920. if (value) {
  112921. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  112922. if (!mesh) {
  112923. return;
  112924. }
  112925. mesh.computeWorldMatrix(true);
  112926. var diagonal = mesh.getBoundingInfo().diagonalLength;
  112927. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  112928. _this.upperRadiusTransitionRange = diagonal * 0.05;
  112929. });
  112930. }
  112931. else if (this._onMeshTargetChangedObserver) {
  112932. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  112933. }
  112934. },
  112935. enumerable: true,
  112936. configurable: true
  112937. });
  112938. /**
  112939. * Initializes the behavior.
  112940. */
  112941. BouncingBehavior.prototype.init = function () {
  112942. // Do notihng
  112943. };
  112944. /**
  112945. * Attaches the behavior to its arc rotate camera.
  112946. * @param camera Defines the camera to attach the behavior to
  112947. */
  112948. BouncingBehavior.prototype.attach = function (camera) {
  112949. var _this = this;
  112950. this._attachedCamera = camera;
  112951. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  112952. if (!_this._attachedCamera) {
  112953. return;
  112954. }
  112955. // Add the bounce animation to the lower radius limit
  112956. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  112957. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  112958. }
  112959. // Add the bounce animation to the upper radius limit
  112960. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  112961. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  112962. }
  112963. });
  112964. };
  112965. /**
  112966. * Detaches the behavior from its current arc rotate camera.
  112967. */
  112968. BouncingBehavior.prototype.detach = function () {
  112969. if (!this._attachedCamera) {
  112970. return;
  112971. }
  112972. if (this._onAfterCheckInputsObserver) {
  112973. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  112974. }
  112975. if (this._onMeshTargetChangedObserver) {
  112976. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  112977. }
  112978. this._attachedCamera = null;
  112979. };
  112980. /**
  112981. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  112982. * @param radiusLimit The limit to check against.
  112983. * @return Bool to indicate if at limit.
  112984. */
  112985. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  112986. if (!this._attachedCamera) {
  112987. return false;
  112988. }
  112989. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  112990. return true;
  112991. }
  112992. return false;
  112993. };
  112994. /**
  112995. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  112996. * @param radiusDelta The delta by which to animate to. Can be negative.
  112997. */
  112998. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  112999. var _this = this;
  113000. if (!this._attachedCamera) {
  113001. return;
  113002. }
  113003. if (!this._radiusBounceTransition) {
  113004. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  113005. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  113006. }
  113007. // Prevent zoom until bounce has completed
  113008. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  113009. this._attachedCamera.wheelPrecision = Infinity;
  113010. this._attachedCamera.inertialRadiusOffset = 0;
  113011. // Animate to the radius limit
  113012. this.stopAllAnimations();
  113013. this._radiusIsAnimating = true;
  113014. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  113015. if (animatable) {
  113016. this._animatables.push(animatable);
  113017. }
  113018. };
  113019. /**
  113020. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  113021. */
  113022. BouncingBehavior.prototype._clearAnimationLocks = function () {
  113023. this._radiusIsAnimating = false;
  113024. if (this._attachedCamera) {
  113025. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  113026. }
  113027. };
  113028. /**
  113029. * Stops and removes all animations that have been applied to the camera
  113030. */
  113031. BouncingBehavior.prototype.stopAllAnimations = function () {
  113032. if (this._attachedCamera) {
  113033. this._attachedCamera.animations = [];
  113034. }
  113035. while (this._animatables.length) {
  113036. this._animatables[0].onAnimationEnd = null;
  113037. this._animatables[0].stop();
  113038. this._animatables.shift();
  113039. }
  113040. };
  113041. /**
  113042. * The easing function used by animations
  113043. */
  113044. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  113045. /**
  113046. * The easing mode used by animations
  113047. */
  113048. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  113049. return BouncingBehavior;
  113050. }());
  113051. BABYLON.BouncingBehavior = BouncingBehavior;
  113052. })(BABYLON || (BABYLON = {}));
  113053. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  113054. var BABYLON;
  113055. (function (BABYLON) {
  113056. /**
  113057. * The autoRotation behavior (BABYLON.AutoRotationBehavior) is designed to create a smooth rotation of an ArcRotateCamera when there is no user interaction.
  113058. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  113059. */
  113060. var AutoRotationBehavior = /** @class */ (function () {
  113061. function AutoRotationBehavior() {
  113062. this._zoomStopsAnimation = false;
  113063. this._idleRotationSpeed = 0.05;
  113064. this._idleRotationWaitTime = 2000;
  113065. this._idleRotationSpinupTime = 2000;
  113066. this._isPointerDown = false;
  113067. this._lastFrameTime = null;
  113068. this._lastInteractionTime = -Infinity;
  113069. this._cameraRotationSpeed = 0;
  113070. this._lastFrameRadius = 0;
  113071. }
  113072. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  113073. /**
  113074. * Gets the name of the behavior.
  113075. */
  113076. get: function () {
  113077. return "AutoRotation";
  113078. },
  113079. enumerable: true,
  113080. configurable: true
  113081. });
  113082. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  113083. /**
  113084. * Gets the flag that indicates if user zooming should stop animation.
  113085. */
  113086. get: function () {
  113087. return this._zoomStopsAnimation;
  113088. },
  113089. /**
  113090. * Sets the flag that indicates if user zooming should stop animation.
  113091. */
  113092. set: function (flag) {
  113093. this._zoomStopsAnimation = flag;
  113094. },
  113095. enumerable: true,
  113096. configurable: true
  113097. });
  113098. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  113099. /**
  113100. * Gets the default speed at which the camera rotates around the model.
  113101. */
  113102. get: function () {
  113103. return this._idleRotationSpeed;
  113104. },
  113105. /**
  113106. * Sets the default speed at which the camera rotates around the model.
  113107. */
  113108. set: function (speed) {
  113109. this._idleRotationSpeed = speed;
  113110. },
  113111. enumerable: true,
  113112. configurable: true
  113113. });
  113114. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  113115. /**
  113116. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  113117. */
  113118. get: function () {
  113119. return this._idleRotationWaitTime;
  113120. },
  113121. /**
  113122. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  113123. */
  113124. set: function (time) {
  113125. this._idleRotationWaitTime = time;
  113126. },
  113127. enumerable: true,
  113128. configurable: true
  113129. });
  113130. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  113131. /**
  113132. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  113133. */
  113134. get: function () {
  113135. return this._idleRotationSpinupTime;
  113136. },
  113137. /**
  113138. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  113139. */
  113140. set: function (time) {
  113141. this._idleRotationSpinupTime = time;
  113142. },
  113143. enumerable: true,
  113144. configurable: true
  113145. });
  113146. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  113147. /**
  113148. * Gets a value indicating if the camera is currently rotating because of this behavior
  113149. */
  113150. get: function () {
  113151. return Math.abs(this._cameraRotationSpeed) > 0;
  113152. },
  113153. enumerable: true,
  113154. configurable: true
  113155. });
  113156. /**
  113157. * Initializes the behavior.
  113158. */
  113159. AutoRotationBehavior.prototype.init = function () {
  113160. // Do notihng
  113161. };
  113162. /**
  113163. * Attaches the behavior to its arc rotate camera.
  113164. * @param camera Defines the camera to attach the behavior to
  113165. */
  113166. AutoRotationBehavior.prototype.attach = function (camera) {
  113167. var _this = this;
  113168. this._attachedCamera = camera;
  113169. var scene = this._attachedCamera.getScene();
  113170. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  113171. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  113172. _this._isPointerDown = true;
  113173. return;
  113174. }
  113175. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  113176. _this._isPointerDown = false;
  113177. }
  113178. });
  113179. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  113180. var now = BABYLON.Tools.Now;
  113181. var dt = 0;
  113182. if (_this._lastFrameTime != null) {
  113183. dt = now - _this._lastFrameTime;
  113184. }
  113185. _this._lastFrameTime = now;
  113186. // Stop the animation if there is user interaction and the animation should stop for this interaction
  113187. _this._applyUserInteraction();
  113188. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  113189. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  113190. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  113191. // Step camera rotation by rotation speed
  113192. if (_this._attachedCamera) {
  113193. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  113194. }
  113195. });
  113196. };
  113197. /**
  113198. * Detaches the behavior from its current arc rotate camera.
  113199. */
  113200. AutoRotationBehavior.prototype.detach = function () {
  113201. if (!this._attachedCamera) {
  113202. return;
  113203. }
  113204. var scene = this._attachedCamera.getScene();
  113205. if (this._onPrePointerObservableObserver) {
  113206. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  113207. }
  113208. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  113209. this._attachedCamera = null;
  113210. };
  113211. /**
  113212. * Returns true if user is scrolling.
  113213. * @return true if user is scrolling.
  113214. */
  113215. AutoRotationBehavior.prototype._userIsZooming = function () {
  113216. if (!this._attachedCamera) {
  113217. return false;
  113218. }
  113219. return this._attachedCamera.inertialRadiusOffset !== 0;
  113220. };
  113221. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  113222. if (!this._attachedCamera) {
  113223. return false;
  113224. }
  113225. var zoomHasHitLimit = false;
  113226. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  113227. zoomHasHitLimit = true;
  113228. }
  113229. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  113230. this._lastFrameRadius = this._attachedCamera.radius;
  113231. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  113232. };
  113233. /**
  113234. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  113235. */
  113236. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  113237. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  113238. this._lastInteractionTime = BABYLON.Tools.Now;
  113239. }
  113240. };
  113241. // Tools
  113242. AutoRotationBehavior.prototype._userIsMoving = function () {
  113243. if (!this._attachedCamera) {
  113244. return false;
  113245. }
  113246. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  113247. this._attachedCamera.inertialBetaOffset !== 0 ||
  113248. this._attachedCamera.inertialRadiusOffset !== 0 ||
  113249. this._attachedCamera.inertialPanningX !== 0 ||
  113250. this._attachedCamera.inertialPanningY !== 0 ||
  113251. this._isPointerDown;
  113252. };
  113253. return AutoRotationBehavior;
  113254. }());
  113255. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  113256. })(BABYLON || (BABYLON = {}));
  113257. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  113258. var BABYLON;
  113259. (function (BABYLON) {
  113260. /**
  113261. * Options to create the null engine
  113262. */
  113263. var NullEngineOptions = /** @class */ (function () {
  113264. function NullEngineOptions() {
  113265. /**
  113266. * Render width (Default: 512)
  113267. */
  113268. this.renderWidth = 512;
  113269. /**
  113270. * Render height (Default: 256)
  113271. */
  113272. this.renderHeight = 256;
  113273. /**
  113274. * Texture size (Default: 512)
  113275. */
  113276. this.textureSize = 512;
  113277. /**
  113278. * If delta time between frames should be constant
  113279. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  113280. */
  113281. this.deterministicLockstep = false;
  113282. /**
  113283. * Maximum about of steps between frames (Default: 4)
  113284. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  113285. */
  113286. this.lockstepMaxSteps = 4;
  113287. }
  113288. return NullEngineOptions;
  113289. }());
  113290. BABYLON.NullEngineOptions = NullEngineOptions;
  113291. /**
  113292. * The null engine class provides support for headless version of babylon.js.
  113293. * This can be used in server side scenario or for testing purposes
  113294. */
  113295. var NullEngine = /** @class */ (function (_super) {
  113296. __extends(NullEngine, _super);
  113297. function NullEngine(options) {
  113298. if (options === void 0) { options = new NullEngineOptions(); }
  113299. var _this = _super.call(this, null) || this;
  113300. if (options.deterministicLockstep === undefined) {
  113301. options.deterministicLockstep = false;
  113302. }
  113303. if (options.lockstepMaxSteps === undefined) {
  113304. options.lockstepMaxSteps = 4;
  113305. }
  113306. _this._options = options;
  113307. // Init caps
  113308. // We consider we are on a webgl1 capable device
  113309. _this._caps = new BABYLON.EngineCapabilities();
  113310. _this._caps.maxTexturesImageUnits = 16;
  113311. _this._caps.maxVertexTextureImageUnits = 16;
  113312. _this._caps.maxTextureSize = 512;
  113313. _this._caps.maxCubemapTextureSize = 512;
  113314. _this._caps.maxRenderTextureSize = 512;
  113315. _this._caps.maxVertexAttribs = 16;
  113316. _this._caps.maxVaryingVectors = 16;
  113317. _this._caps.maxFragmentUniformVectors = 16;
  113318. _this._caps.maxVertexUniformVectors = 16;
  113319. // Extensions
  113320. _this._caps.standardDerivatives = false;
  113321. _this._caps.astc = null;
  113322. _this._caps.s3tc = null;
  113323. _this._caps.pvrtc = null;
  113324. _this._caps.etc1 = null;
  113325. _this._caps.etc2 = null;
  113326. _this._caps.textureAnisotropicFilterExtension = null;
  113327. _this._caps.maxAnisotropy = 0;
  113328. _this._caps.uintIndices = false;
  113329. _this._caps.fragmentDepthSupported = false;
  113330. _this._caps.highPrecisionShaderSupported = true;
  113331. _this._caps.colorBufferFloat = false;
  113332. _this._caps.textureFloat = false;
  113333. _this._caps.textureFloatLinearFiltering = false;
  113334. _this._caps.textureFloatRender = false;
  113335. _this._caps.textureHalfFloat = false;
  113336. _this._caps.textureHalfFloatLinearFiltering = false;
  113337. _this._caps.textureHalfFloatRender = false;
  113338. _this._caps.textureLOD = false;
  113339. _this._caps.drawBuffersExtension = false;
  113340. _this._caps.depthTextureExtension = false;
  113341. _this._caps.vertexArrayObject = false;
  113342. _this._caps.instancedArrays = false;
  113343. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  113344. // Wrappers
  113345. if (typeof URL === "undefined") {
  113346. URL = {
  113347. createObjectURL: function () { },
  113348. revokeObjectURL: function () { }
  113349. };
  113350. }
  113351. if (typeof Blob === "undefined") {
  113352. Blob = function () { };
  113353. }
  113354. return _this;
  113355. }
  113356. /**
  113357. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  113358. */
  113359. NullEngine.prototype.isDeterministicLockStep = function () {
  113360. return this._options.deterministicLockstep;
  113361. };
  113362. /** @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep */
  113363. NullEngine.prototype.getLockstepMaxSteps = function () {
  113364. return this._options.lockstepMaxSteps;
  113365. };
  113366. /**
  113367. * Sets hardware scaling, used to save performance if needed
  113368. * @see https://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  113369. */
  113370. NullEngine.prototype.getHardwareScalingLevel = function () {
  113371. return 1.0;
  113372. };
  113373. NullEngine.prototype.createVertexBuffer = function (vertices) {
  113374. return {
  113375. capacity: 0,
  113376. references: 1,
  113377. is32Bits: false
  113378. };
  113379. };
  113380. NullEngine.prototype.createIndexBuffer = function (indices) {
  113381. return {
  113382. capacity: 0,
  113383. references: 1,
  113384. is32Bits: false
  113385. };
  113386. };
  113387. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  113388. if (stencil === void 0) { stencil = false; }
  113389. };
  113390. NullEngine.prototype.getRenderWidth = function (useScreen) {
  113391. if (useScreen === void 0) { useScreen = false; }
  113392. if (!useScreen && this._currentRenderTarget) {
  113393. return this._currentRenderTarget.width;
  113394. }
  113395. return this._options.renderWidth;
  113396. };
  113397. NullEngine.prototype.getRenderHeight = function (useScreen) {
  113398. if (useScreen === void 0) { useScreen = false; }
  113399. if (!useScreen && this._currentRenderTarget) {
  113400. return this._currentRenderTarget.height;
  113401. }
  113402. return this._options.renderHeight;
  113403. };
  113404. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  113405. this._cachedViewport = viewport;
  113406. };
  113407. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  113408. return {
  113409. transformFeedback: null,
  113410. __SPECTOR_rebuildProgram: null
  113411. };
  113412. };
  113413. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  113414. return [];
  113415. };
  113416. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  113417. return [];
  113418. };
  113419. NullEngine.prototype.bindSamplers = function (effect) {
  113420. this._currentEffect = null;
  113421. };
  113422. NullEngine.prototype.enableEffect = function (effect) {
  113423. this._currentEffect = effect;
  113424. if (effect.onBind) {
  113425. effect.onBind(effect);
  113426. }
  113427. if (effect._onBindObservable) {
  113428. effect._onBindObservable.notifyObservers(effect);
  113429. }
  113430. };
  113431. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  113432. if (zOffset === void 0) { zOffset = 0; }
  113433. if (reverseSide === void 0) { reverseSide = false; }
  113434. };
  113435. NullEngine.prototype.setIntArray = function (uniform, array) {
  113436. };
  113437. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  113438. };
  113439. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  113440. };
  113441. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  113442. };
  113443. NullEngine.prototype.setFloatArray = function (uniform, array) {
  113444. };
  113445. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  113446. };
  113447. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  113448. };
  113449. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  113450. };
  113451. NullEngine.prototype.setArray = function (uniform, array) {
  113452. };
  113453. NullEngine.prototype.setArray2 = function (uniform, array) {
  113454. };
  113455. NullEngine.prototype.setArray3 = function (uniform, array) {
  113456. };
  113457. NullEngine.prototype.setArray4 = function (uniform, array) {
  113458. };
  113459. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  113460. };
  113461. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  113462. };
  113463. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  113464. };
  113465. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  113466. };
  113467. NullEngine.prototype.setFloat = function (uniform, value) {
  113468. };
  113469. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  113470. };
  113471. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  113472. };
  113473. NullEngine.prototype.setBool = function (uniform, bool) {
  113474. };
  113475. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  113476. };
  113477. NullEngine.prototype.setColor3 = function (uniform, color3) {
  113478. };
  113479. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  113480. };
  113481. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  113482. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  113483. if (this._alphaMode === mode) {
  113484. return;
  113485. }
  113486. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  113487. if (!noDepthWriteChange) {
  113488. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  113489. }
  113490. this._alphaMode = mode;
  113491. };
  113492. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  113493. };
  113494. NullEngine.prototype.wipeCaches = function (bruteForce) {
  113495. if (this.preventCacheWipeBetweenFrames) {
  113496. return;
  113497. }
  113498. this.resetTextureCache();
  113499. this._currentEffect = null;
  113500. if (bruteForce) {
  113501. this._currentProgram = null;
  113502. this._stencilState.reset();
  113503. this._depthCullingState.reset();
  113504. this._alphaState.reset();
  113505. }
  113506. this._cachedVertexBuffers = null;
  113507. this._cachedIndexBuffer = null;
  113508. this._cachedEffectForVertexBuffers = null;
  113509. };
  113510. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  113511. };
  113512. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  113513. };
  113514. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  113515. };
  113516. /** @hidden */
  113517. NullEngine.prototype._createTexture = function () {
  113518. return {};
  113519. };
  113520. /** @hidden */
  113521. NullEngine.prototype._releaseTexture = function (texture) {
  113522. };
  113523. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  113524. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  113525. if (onLoad === void 0) { onLoad = null; }
  113526. if (onError === void 0) { onError = null; }
  113527. if (buffer === void 0) { buffer = null; }
  113528. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  113529. var url = String(urlArg);
  113530. texture.url = url;
  113531. texture.generateMipMaps = !noMipmap;
  113532. texture.samplingMode = samplingMode;
  113533. texture.invertY = invertY;
  113534. texture.baseWidth = this._options.textureSize;
  113535. texture.baseHeight = this._options.textureSize;
  113536. texture.width = this._options.textureSize;
  113537. texture.height = this._options.textureSize;
  113538. if (format) {
  113539. texture.format = format;
  113540. }
  113541. texture.isReady = true;
  113542. if (onLoad) {
  113543. onLoad();
  113544. }
  113545. this._internalTexturesCache.push(texture);
  113546. return texture;
  113547. };
  113548. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  113549. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  113550. if (options !== undefined && typeof options === "object") {
  113551. fullOptions.generateMipMaps = options.generateMipMaps;
  113552. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  113553. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  113554. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  113555. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  113556. }
  113557. else {
  113558. fullOptions.generateMipMaps = options;
  113559. fullOptions.generateDepthBuffer = true;
  113560. fullOptions.generateStencilBuffer = false;
  113561. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  113562. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  113563. }
  113564. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  113565. var width = size.width || size;
  113566. var height = size.height || size;
  113567. texture._depthStencilBuffer = {};
  113568. texture._framebuffer = {};
  113569. texture.baseWidth = width;
  113570. texture.baseHeight = height;
  113571. texture.width = width;
  113572. texture.height = height;
  113573. texture.isReady = true;
  113574. texture.samples = 1;
  113575. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  113576. texture.samplingMode = fullOptions.samplingMode;
  113577. texture.type = fullOptions.type;
  113578. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  113579. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  113580. this._internalTexturesCache.push(texture);
  113581. return texture;
  113582. };
  113583. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  113584. texture.samplingMode = samplingMode;
  113585. };
  113586. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  113587. if (this._currentRenderTarget) {
  113588. this.unBindFramebuffer(this._currentRenderTarget);
  113589. }
  113590. this._currentRenderTarget = texture;
  113591. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  113592. if (this._cachedViewport && !forceFullscreenViewport) {
  113593. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  113594. }
  113595. };
  113596. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  113597. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  113598. this._currentRenderTarget = null;
  113599. if (onBeforeUnbind) {
  113600. if (texture._MSAAFramebuffer) {
  113601. this._currentFramebuffer = texture._framebuffer;
  113602. }
  113603. onBeforeUnbind();
  113604. }
  113605. this._currentFramebuffer = null;
  113606. };
  113607. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  113608. var vbo = {
  113609. capacity: 1,
  113610. references: 1,
  113611. is32Bits: false
  113612. };
  113613. return vbo;
  113614. };
  113615. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  113616. if (premulAlpha === void 0) { premulAlpha = false; }
  113617. };
  113618. /**
  113619. * @hidden
  113620. * Get the current error code of the webGL context
  113621. * @returns the error code
  113622. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  113623. */
  113624. NullEngine.prototype.getError = function () {
  113625. return 0;
  113626. };
  113627. /** @hidden */
  113628. NullEngine.prototype._getUnpackAlignement = function () {
  113629. return 1;
  113630. };
  113631. /** @hidden */
  113632. NullEngine.prototype._unpackFlipY = function (value) {
  113633. };
  113634. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  113635. if (offset === void 0) { offset = 0; }
  113636. };
  113637. /**
  113638. * Updates a dynamic vertex buffer.
  113639. * @param vertexBuffer the vertex buffer to update
  113640. * @param data the data used to update the vertex buffer
  113641. * @param byteOffset the byte offset of the data (optional)
  113642. * @param byteLength the byte length of the data (optional)
  113643. */
  113644. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  113645. };
  113646. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  113647. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  113648. this._boundTexturesCache[this._activeChannel] = texture;
  113649. return true;
  113650. }
  113651. return false;
  113652. };
  113653. /** @hidden */
  113654. NullEngine.prototype._bindTexture = function (channel, texture) {
  113655. if (channel < 0) {
  113656. return;
  113657. }
  113658. this._bindTextureDirectly(0, texture);
  113659. };
  113660. /** @hidden */
  113661. NullEngine.prototype._releaseBuffer = function (buffer) {
  113662. buffer.references--;
  113663. if (buffer.references === 0) {
  113664. return true;
  113665. }
  113666. return false;
  113667. };
  113668. NullEngine.prototype.releaseEffects = function () {
  113669. };
  113670. NullEngine.prototype.displayLoadingUI = function () {
  113671. };
  113672. NullEngine.prototype.hideLoadingUI = function () {
  113673. };
  113674. /** @hidden */
  113675. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  113676. if (faceIndex === void 0) { faceIndex = 0; }
  113677. if (lod === void 0) { lod = 0; }
  113678. };
  113679. /** @hidden */
  113680. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  113681. if (faceIndex === void 0) { faceIndex = 0; }
  113682. if (lod === void 0) { lod = 0; }
  113683. };
  113684. /** @hidden */
  113685. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  113686. if (faceIndex === void 0) { faceIndex = 0; }
  113687. if (lod === void 0) { lod = 0; }
  113688. };
  113689. /** @hidden */
  113690. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  113691. if (faceIndex === void 0) { faceIndex = 0; }
  113692. if (lod === void 0) { lod = 0; }
  113693. };
  113694. return NullEngine;
  113695. }(BABYLON.Engine));
  113696. BABYLON.NullEngine = NullEngine;
  113697. })(BABYLON || (BABYLON = {}));
  113698. //# sourceMappingURL=babylon.nullEngine.js.map
  113699. var BABYLON;
  113700. (function (BABYLON) {
  113701. /**
  113702. * This class can be used to get instrumentation data from a Babylon engine
  113703. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  113704. */
  113705. var EngineInstrumentation = /** @class */ (function () {
  113706. /**
  113707. * Instantiates a new engine instrumentation.
  113708. * This class can be used to get instrumentation data from a Babylon engine
  113709. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  113710. * @param engine Defines the engine to instrument
  113711. */
  113712. function EngineInstrumentation(
  113713. /**
  113714. * Define the instrumented engine.
  113715. */
  113716. engine) {
  113717. this.engine = engine;
  113718. this._captureGPUFrameTime = false;
  113719. this._gpuFrameTime = new BABYLON.PerfCounter();
  113720. this._captureShaderCompilationTime = false;
  113721. this._shaderCompilationTime = new BABYLON.PerfCounter();
  113722. // Observers
  113723. this._onBeginFrameObserver = null;
  113724. this._onEndFrameObserver = null;
  113725. this._onBeforeShaderCompilationObserver = null;
  113726. this._onAfterShaderCompilationObserver = null;
  113727. }
  113728. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  113729. // Properties
  113730. /**
  113731. * Gets the perf counter used for GPU frame time
  113732. */
  113733. get: function () {
  113734. return this._gpuFrameTime;
  113735. },
  113736. enumerable: true,
  113737. configurable: true
  113738. });
  113739. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  113740. /**
  113741. * Gets the GPU frame time capture status
  113742. */
  113743. get: function () {
  113744. return this._captureGPUFrameTime;
  113745. },
  113746. /**
  113747. * Enable or disable the GPU frame time capture
  113748. */
  113749. set: function (value) {
  113750. var _this = this;
  113751. if (value === this._captureGPUFrameTime) {
  113752. return;
  113753. }
  113754. this._captureGPUFrameTime = value;
  113755. if (value) {
  113756. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  113757. if (!_this._gpuFrameTimeToken) {
  113758. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  113759. }
  113760. });
  113761. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  113762. if (!_this._gpuFrameTimeToken) {
  113763. return;
  113764. }
  113765. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  113766. if (time > -1) {
  113767. _this._gpuFrameTimeToken = null;
  113768. _this._gpuFrameTime.fetchNewFrame();
  113769. _this._gpuFrameTime.addCount(time, true);
  113770. }
  113771. });
  113772. }
  113773. else {
  113774. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  113775. this._onBeginFrameObserver = null;
  113776. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  113777. this._onEndFrameObserver = null;
  113778. }
  113779. },
  113780. enumerable: true,
  113781. configurable: true
  113782. });
  113783. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  113784. /**
  113785. * Gets the perf counter used for shader compilation time
  113786. */
  113787. get: function () {
  113788. return this._shaderCompilationTime;
  113789. },
  113790. enumerable: true,
  113791. configurable: true
  113792. });
  113793. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  113794. /**
  113795. * Gets the shader compilation time capture status
  113796. */
  113797. get: function () {
  113798. return this._captureShaderCompilationTime;
  113799. },
  113800. /**
  113801. * Enable or disable the shader compilation time capture
  113802. */
  113803. set: function (value) {
  113804. var _this = this;
  113805. if (value === this._captureShaderCompilationTime) {
  113806. return;
  113807. }
  113808. this._captureShaderCompilationTime = value;
  113809. if (value) {
  113810. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  113811. _this._shaderCompilationTime.fetchNewFrame();
  113812. _this._shaderCompilationTime.beginMonitoring();
  113813. });
  113814. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  113815. _this._shaderCompilationTime.endMonitoring();
  113816. });
  113817. }
  113818. else {
  113819. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  113820. this._onBeforeShaderCompilationObserver = null;
  113821. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  113822. this._onAfterShaderCompilationObserver = null;
  113823. }
  113824. },
  113825. enumerable: true,
  113826. configurable: true
  113827. });
  113828. /**
  113829. * Dispose and release associated resources.
  113830. */
  113831. EngineInstrumentation.prototype.dispose = function () {
  113832. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  113833. this._onBeginFrameObserver = null;
  113834. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  113835. this._onEndFrameObserver = null;
  113836. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  113837. this._onBeforeShaderCompilationObserver = null;
  113838. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  113839. this._onAfterShaderCompilationObserver = null;
  113840. this.engine = null;
  113841. };
  113842. return EngineInstrumentation;
  113843. }());
  113844. BABYLON.EngineInstrumentation = EngineInstrumentation;
  113845. })(BABYLON || (BABYLON = {}));
  113846. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  113847. var BABYLON;
  113848. (function (BABYLON) {
  113849. /**
  113850. * This class can be used to get instrumentation data from a Babylon engine
  113851. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  113852. */
  113853. var SceneInstrumentation = /** @class */ (function () {
  113854. /**
  113855. * Instantiates a new scene instrumentation.
  113856. * This class can be used to get instrumentation data from a Babylon engine
  113857. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  113858. * @param scene Defines the scene to instrument
  113859. */
  113860. function SceneInstrumentation(
  113861. /**
  113862. * Defines the scene to instrument
  113863. */
  113864. scene) {
  113865. var _this = this;
  113866. this.scene = scene;
  113867. this._captureActiveMeshesEvaluationTime = false;
  113868. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  113869. this._captureRenderTargetsRenderTime = false;
  113870. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  113871. this._captureFrameTime = false;
  113872. this._frameTime = new BABYLON.PerfCounter();
  113873. this._captureRenderTime = false;
  113874. this._renderTime = new BABYLON.PerfCounter();
  113875. this._captureInterFrameTime = false;
  113876. this._interFrameTime = new BABYLON.PerfCounter();
  113877. this._captureParticlesRenderTime = false;
  113878. this._particlesRenderTime = new BABYLON.PerfCounter();
  113879. this._captureSpritesRenderTime = false;
  113880. this._spritesRenderTime = new BABYLON.PerfCounter();
  113881. this._capturePhysicsTime = false;
  113882. this._physicsTime = new BABYLON.PerfCounter();
  113883. this._captureAnimationsTime = false;
  113884. this._animationsTime = new BABYLON.PerfCounter();
  113885. this._captureCameraRenderTime = false;
  113886. this._cameraRenderTime = new BABYLON.PerfCounter();
  113887. // Observers
  113888. this._onBeforeActiveMeshesEvaluationObserver = null;
  113889. this._onAfterActiveMeshesEvaluationObserver = null;
  113890. this._onBeforeRenderTargetsRenderObserver = null;
  113891. this._onAfterRenderTargetsRenderObserver = null;
  113892. this._onAfterRenderObserver = null;
  113893. this._onBeforeDrawPhaseObserver = null;
  113894. this._onAfterDrawPhaseObserver = null;
  113895. this._onBeforeAnimationsObserver = null;
  113896. this._onBeforeParticlesRenderingObserver = null;
  113897. this._onAfterParticlesRenderingObserver = null;
  113898. this._onBeforeSpritesRenderingObserver = null;
  113899. this._onAfterSpritesRenderingObserver = null;
  113900. this._onBeforePhysicsObserver = null;
  113901. this._onAfterPhysicsObserver = null;
  113902. this._onAfterAnimationsObserver = null;
  113903. this._onBeforeCameraRenderObserver = null;
  113904. this._onAfterCameraRenderObserver = null;
  113905. // Before render
  113906. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  113907. if (_this._captureActiveMeshesEvaluationTime) {
  113908. _this._activeMeshesEvaluationTime.fetchNewFrame();
  113909. }
  113910. if (_this._captureRenderTargetsRenderTime) {
  113911. _this._renderTargetsRenderTime.fetchNewFrame();
  113912. }
  113913. if (_this._captureFrameTime) {
  113914. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  113915. _this._frameTime.beginMonitoring();
  113916. }
  113917. if (_this._captureInterFrameTime) {
  113918. _this._interFrameTime.endMonitoring();
  113919. }
  113920. if (_this._captureParticlesRenderTime) {
  113921. _this._particlesRenderTime.fetchNewFrame();
  113922. }
  113923. if (_this._captureSpritesRenderTime) {
  113924. _this._spritesRenderTime.fetchNewFrame();
  113925. }
  113926. if (_this._captureAnimationsTime) {
  113927. _this._animationsTime.beginMonitoring();
  113928. }
  113929. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  113930. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  113931. });
  113932. // After render
  113933. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  113934. if (_this._captureFrameTime) {
  113935. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  113936. _this._frameTime.endMonitoring();
  113937. }
  113938. if (_this._captureRenderTime) {
  113939. _this._renderTime.endMonitoring(false);
  113940. }
  113941. if (_this._captureInterFrameTime) {
  113942. _this._interFrameTime.beginMonitoring();
  113943. }
  113944. });
  113945. }
  113946. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  113947. // Properties
  113948. /**
  113949. * Gets the perf counter used for active meshes evaluation time
  113950. */
  113951. get: function () {
  113952. return this._activeMeshesEvaluationTime;
  113953. },
  113954. enumerable: true,
  113955. configurable: true
  113956. });
  113957. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  113958. /**
  113959. * Gets the active meshes evaluation time capture status
  113960. */
  113961. get: function () {
  113962. return this._captureActiveMeshesEvaluationTime;
  113963. },
  113964. /**
  113965. * Enable or disable the active meshes evaluation time capture
  113966. */
  113967. set: function (value) {
  113968. var _this = this;
  113969. if (value === this._captureActiveMeshesEvaluationTime) {
  113970. return;
  113971. }
  113972. this._captureActiveMeshesEvaluationTime = value;
  113973. if (value) {
  113974. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  113975. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  113976. _this._activeMeshesEvaluationTime.beginMonitoring();
  113977. });
  113978. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  113979. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  113980. _this._activeMeshesEvaluationTime.endMonitoring();
  113981. });
  113982. }
  113983. else {
  113984. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  113985. this._onBeforeActiveMeshesEvaluationObserver = null;
  113986. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  113987. this._onAfterActiveMeshesEvaluationObserver = null;
  113988. }
  113989. },
  113990. enumerable: true,
  113991. configurable: true
  113992. });
  113993. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  113994. /**
  113995. * Gets the perf counter used for render targets render time
  113996. */
  113997. get: function () {
  113998. return this._renderTargetsRenderTime;
  113999. },
  114000. enumerable: true,
  114001. configurable: true
  114002. });
  114003. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  114004. /**
  114005. * Gets the render targets render time capture status
  114006. */
  114007. get: function () {
  114008. return this._captureRenderTargetsRenderTime;
  114009. },
  114010. /**
  114011. * Enable or disable the render targets render time capture
  114012. */
  114013. set: function (value) {
  114014. var _this = this;
  114015. if (value === this._captureRenderTargetsRenderTime) {
  114016. return;
  114017. }
  114018. this._captureRenderTargetsRenderTime = value;
  114019. if (value) {
  114020. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  114021. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  114022. _this._renderTargetsRenderTime.beginMonitoring();
  114023. });
  114024. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  114025. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  114026. _this._renderTargetsRenderTime.endMonitoring(false);
  114027. });
  114028. }
  114029. else {
  114030. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  114031. this._onBeforeRenderTargetsRenderObserver = null;
  114032. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  114033. this._onAfterRenderTargetsRenderObserver = null;
  114034. }
  114035. },
  114036. enumerable: true,
  114037. configurable: true
  114038. });
  114039. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  114040. /**
  114041. * Gets the perf counter used for particles render time
  114042. */
  114043. get: function () {
  114044. return this._particlesRenderTime;
  114045. },
  114046. enumerable: true,
  114047. configurable: true
  114048. });
  114049. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  114050. /**
  114051. * Gets the particles render time capture status
  114052. */
  114053. get: function () {
  114054. return this._captureParticlesRenderTime;
  114055. },
  114056. /**
  114057. * Enable or disable the particles render time capture
  114058. */
  114059. set: function (value) {
  114060. var _this = this;
  114061. if (value === this._captureParticlesRenderTime) {
  114062. return;
  114063. }
  114064. this._captureParticlesRenderTime = value;
  114065. if (value) {
  114066. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  114067. BABYLON.Tools.StartPerformanceCounter("Particles");
  114068. _this._particlesRenderTime.beginMonitoring();
  114069. });
  114070. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  114071. BABYLON.Tools.EndPerformanceCounter("Particles");
  114072. _this._particlesRenderTime.endMonitoring(false);
  114073. });
  114074. }
  114075. else {
  114076. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  114077. this._onBeforeParticlesRenderingObserver = null;
  114078. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  114079. this._onAfterParticlesRenderingObserver = null;
  114080. }
  114081. },
  114082. enumerable: true,
  114083. configurable: true
  114084. });
  114085. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  114086. /**
  114087. * Gets the perf counter used for sprites render time
  114088. */
  114089. get: function () {
  114090. return this._spritesRenderTime;
  114091. },
  114092. enumerable: true,
  114093. configurable: true
  114094. });
  114095. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  114096. /**
  114097. * Gets the sprites render time capture status
  114098. */
  114099. get: function () {
  114100. return this._captureSpritesRenderTime;
  114101. },
  114102. /**
  114103. * Enable or disable the sprites render time capture
  114104. */
  114105. set: function (value) {
  114106. var _this = this;
  114107. if (value === this._captureSpritesRenderTime) {
  114108. return;
  114109. }
  114110. this._captureSpritesRenderTime = value;
  114111. if (!this.scene.spriteManagers) {
  114112. return;
  114113. }
  114114. if (value) {
  114115. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  114116. BABYLON.Tools.StartPerformanceCounter("Sprites");
  114117. _this._spritesRenderTime.beginMonitoring();
  114118. });
  114119. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  114120. BABYLON.Tools.EndPerformanceCounter("Sprites");
  114121. _this._spritesRenderTime.endMonitoring(false);
  114122. });
  114123. }
  114124. else {
  114125. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  114126. this._onBeforeSpritesRenderingObserver = null;
  114127. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  114128. this._onAfterSpritesRenderingObserver = null;
  114129. }
  114130. },
  114131. enumerable: true,
  114132. configurable: true
  114133. });
  114134. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  114135. /**
  114136. * Gets the perf counter used for physics time
  114137. */
  114138. get: function () {
  114139. return this._physicsTime;
  114140. },
  114141. enumerable: true,
  114142. configurable: true
  114143. });
  114144. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  114145. /**
  114146. * Gets the physics time capture status
  114147. */
  114148. get: function () {
  114149. return this._capturePhysicsTime;
  114150. },
  114151. /**
  114152. * Enable or disable the physics time capture
  114153. */
  114154. set: function (value) {
  114155. var _this = this;
  114156. if (value === this._capturePhysicsTime) {
  114157. return;
  114158. }
  114159. if (!this.scene.onBeforePhysicsObservable) {
  114160. return;
  114161. }
  114162. this._capturePhysicsTime = value;
  114163. if (value) {
  114164. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  114165. BABYLON.Tools.StartPerformanceCounter("Physics");
  114166. _this._physicsTime.beginMonitoring();
  114167. });
  114168. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  114169. BABYLON.Tools.EndPerformanceCounter("Physics");
  114170. _this._physicsTime.endMonitoring();
  114171. });
  114172. }
  114173. else {
  114174. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  114175. this._onBeforePhysicsObserver = null;
  114176. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  114177. this._onAfterPhysicsObserver = null;
  114178. }
  114179. },
  114180. enumerable: true,
  114181. configurable: true
  114182. });
  114183. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  114184. /**
  114185. * Gets the perf counter used for animations time
  114186. */
  114187. get: function () {
  114188. return this._animationsTime;
  114189. },
  114190. enumerable: true,
  114191. configurable: true
  114192. });
  114193. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  114194. /**
  114195. * Gets the animations time capture status
  114196. */
  114197. get: function () {
  114198. return this._captureAnimationsTime;
  114199. },
  114200. /**
  114201. * Enable or disable the animations time capture
  114202. */
  114203. set: function (value) {
  114204. var _this = this;
  114205. if (value === this._captureAnimationsTime) {
  114206. return;
  114207. }
  114208. this._captureAnimationsTime = value;
  114209. if (value) {
  114210. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  114211. _this._animationsTime.endMonitoring();
  114212. });
  114213. }
  114214. else {
  114215. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  114216. this._onAfterAnimationsObserver = null;
  114217. }
  114218. },
  114219. enumerable: true,
  114220. configurable: true
  114221. });
  114222. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  114223. /**
  114224. * Gets the perf counter used for frame time capture
  114225. */
  114226. get: function () {
  114227. return this._frameTime;
  114228. },
  114229. enumerable: true,
  114230. configurable: true
  114231. });
  114232. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  114233. /**
  114234. * Gets the frame time capture status
  114235. */
  114236. get: function () {
  114237. return this._captureFrameTime;
  114238. },
  114239. /**
  114240. * Enable or disable the frame time capture
  114241. */
  114242. set: function (value) {
  114243. this._captureFrameTime = value;
  114244. },
  114245. enumerable: true,
  114246. configurable: true
  114247. });
  114248. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  114249. /**
  114250. * Gets the perf counter used for inter-frames time capture
  114251. */
  114252. get: function () {
  114253. return this._interFrameTime;
  114254. },
  114255. enumerable: true,
  114256. configurable: true
  114257. });
  114258. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  114259. /**
  114260. * Gets the inter-frames time capture status
  114261. */
  114262. get: function () {
  114263. return this._captureInterFrameTime;
  114264. },
  114265. /**
  114266. * Enable or disable the inter-frames time capture
  114267. */
  114268. set: function (value) {
  114269. this._captureInterFrameTime = value;
  114270. },
  114271. enumerable: true,
  114272. configurable: true
  114273. });
  114274. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  114275. /**
  114276. * Gets the perf counter used for render time capture
  114277. */
  114278. get: function () {
  114279. return this._renderTime;
  114280. },
  114281. enumerable: true,
  114282. configurable: true
  114283. });
  114284. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  114285. /**
  114286. * Gets the render time capture status
  114287. */
  114288. get: function () {
  114289. return this._captureRenderTime;
  114290. },
  114291. /**
  114292. * Enable or disable the render time capture
  114293. */
  114294. set: function (value) {
  114295. var _this = this;
  114296. if (value === this._captureRenderTime) {
  114297. return;
  114298. }
  114299. this._captureRenderTime = value;
  114300. if (value) {
  114301. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  114302. _this._renderTime.beginMonitoring();
  114303. BABYLON.Tools.StartPerformanceCounter("Main render");
  114304. });
  114305. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  114306. _this._renderTime.endMonitoring(false);
  114307. BABYLON.Tools.EndPerformanceCounter("Main render");
  114308. });
  114309. }
  114310. else {
  114311. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  114312. this._onBeforeDrawPhaseObserver = null;
  114313. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  114314. this._onAfterDrawPhaseObserver = null;
  114315. }
  114316. },
  114317. enumerable: true,
  114318. configurable: true
  114319. });
  114320. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  114321. /**
  114322. * Gets the perf counter used for camera render time capture
  114323. */
  114324. get: function () {
  114325. return this._cameraRenderTime;
  114326. },
  114327. enumerable: true,
  114328. configurable: true
  114329. });
  114330. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  114331. /**
  114332. * Gets the camera render time capture status
  114333. */
  114334. get: function () {
  114335. return this._captureCameraRenderTime;
  114336. },
  114337. /**
  114338. * Enable or disable the camera render time capture
  114339. */
  114340. set: function (value) {
  114341. var _this = this;
  114342. if (value === this._captureCameraRenderTime) {
  114343. return;
  114344. }
  114345. this._captureCameraRenderTime = value;
  114346. if (value) {
  114347. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  114348. _this._cameraRenderTime.beginMonitoring();
  114349. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  114350. });
  114351. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  114352. _this._cameraRenderTime.endMonitoring(false);
  114353. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  114354. });
  114355. }
  114356. else {
  114357. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  114358. this._onBeforeCameraRenderObserver = null;
  114359. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  114360. this._onAfterCameraRenderObserver = null;
  114361. }
  114362. },
  114363. enumerable: true,
  114364. configurable: true
  114365. });
  114366. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  114367. /**
  114368. * Gets the perf counter used for draw calls
  114369. */
  114370. get: function () {
  114371. return this.scene.getEngine()._drawCalls;
  114372. },
  114373. enumerable: true,
  114374. configurable: true
  114375. });
  114376. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  114377. /**
  114378. * Gets the perf counter used for texture collisions
  114379. */
  114380. get: function () {
  114381. return this.scene.getEngine()._textureCollisions;
  114382. },
  114383. enumerable: true,
  114384. configurable: true
  114385. });
  114386. /**
  114387. * Dispose and release associated resources.
  114388. */
  114389. SceneInstrumentation.prototype.dispose = function () {
  114390. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  114391. this._onAfterRenderObserver = null;
  114392. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  114393. this._onBeforeActiveMeshesEvaluationObserver = null;
  114394. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  114395. this._onAfterActiveMeshesEvaluationObserver = null;
  114396. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  114397. this._onBeforeRenderTargetsRenderObserver = null;
  114398. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  114399. this._onAfterRenderTargetsRenderObserver = null;
  114400. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  114401. this._onBeforeAnimationsObserver = null;
  114402. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  114403. this._onBeforeParticlesRenderingObserver = null;
  114404. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  114405. this._onAfterParticlesRenderingObserver = null;
  114406. if (this._onBeforeSpritesRenderingObserver) {
  114407. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  114408. this._onBeforeSpritesRenderingObserver = null;
  114409. }
  114410. if (this._onAfterSpritesRenderingObserver) {
  114411. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  114412. this._onAfterSpritesRenderingObserver = null;
  114413. }
  114414. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  114415. this._onBeforeDrawPhaseObserver = null;
  114416. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  114417. this._onAfterDrawPhaseObserver = null;
  114418. if (this._onBeforePhysicsObserver) {
  114419. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  114420. this._onBeforePhysicsObserver = null;
  114421. }
  114422. if (this._onAfterPhysicsObserver) {
  114423. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  114424. this._onAfterPhysicsObserver = null;
  114425. }
  114426. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  114427. this._onAfterAnimationsObserver = null;
  114428. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  114429. this._onBeforeCameraRenderObserver = null;
  114430. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  114431. this._onAfterCameraRenderObserver = null;
  114432. this.scene = null;
  114433. };
  114434. return SceneInstrumentation;
  114435. }());
  114436. BABYLON.SceneInstrumentation = SceneInstrumentation;
  114437. })(BABYLON || (BABYLON = {}));
  114438. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  114439. var BABYLON;
  114440. (function (BABYLON) {
  114441. /**
  114442. * @hidden
  114443. **/
  114444. var _TimeToken = /** @class */ (function () {
  114445. function _TimeToken() {
  114446. this._timeElapsedQueryEnded = false;
  114447. }
  114448. return _TimeToken;
  114449. }());
  114450. BABYLON._TimeToken = _TimeToken;
  114451. })(BABYLON || (BABYLON = {}));
  114452. //# sourceMappingURL=babylon.timeToken.js.map
  114453. var BABYLON;
  114454. (function (BABYLON) {
  114455. /**
  114456. * Background material defines definition.
  114457. * @hidden Mainly internal Use
  114458. */
  114459. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  114460. __extends(BackgroundMaterialDefines, _super);
  114461. /**
  114462. * Constructor of the defines.
  114463. */
  114464. function BackgroundMaterialDefines() {
  114465. var _this = _super.call(this) || this;
  114466. /**
  114467. * True if the diffuse texture is in use.
  114468. */
  114469. _this.DIFFUSE = false;
  114470. /**
  114471. * The direct UV channel to use.
  114472. */
  114473. _this.DIFFUSEDIRECTUV = 0;
  114474. /**
  114475. * True if the diffuse texture is in gamma space.
  114476. */
  114477. _this.GAMMADIFFUSE = false;
  114478. /**
  114479. * True if the diffuse texture has opacity in the alpha channel.
  114480. */
  114481. _this.DIFFUSEHASALPHA = false;
  114482. /**
  114483. * True if you want the material to fade to transparent at grazing angle.
  114484. */
  114485. _this.OPACITYFRESNEL = false;
  114486. /**
  114487. * True if an extra blur needs to be added in the reflection.
  114488. */
  114489. _this.REFLECTIONBLUR = false;
  114490. /**
  114491. * True if you want the material to fade to reflection at grazing angle.
  114492. */
  114493. _this.REFLECTIONFRESNEL = false;
  114494. /**
  114495. * True if you want the material to falloff as far as you move away from the scene center.
  114496. */
  114497. _this.REFLECTIONFALLOFF = false;
  114498. /**
  114499. * False if the current Webgl implementation does not support the texture lod extension.
  114500. */
  114501. _this.TEXTURELODSUPPORT = false;
  114502. /**
  114503. * True to ensure the data are premultiplied.
  114504. */
  114505. _this.PREMULTIPLYALPHA = false;
  114506. /**
  114507. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  114508. */
  114509. _this.USERGBCOLOR = false;
  114510. /**
  114511. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  114512. * stays aligned with the desired configuration.
  114513. */
  114514. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  114515. /**
  114516. * True to add noise in order to reduce the banding effect.
  114517. */
  114518. _this.NOISE = false;
  114519. /**
  114520. * is the reflection texture in BGR color scheme?
  114521. * Mainly used to solve a bug in ios10 video tag
  114522. */
  114523. _this.REFLECTIONBGR = false;
  114524. _this.IMAGEPROCESSING = false;
  114525. _this.VIGNETTE = false;
  114526. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  114527. _this.VIGNETTEBLENDMODEOPAQUE = false;
  114528. _this.TONEMAPPING = false;
  114529. _this.TONEMAPPING_ACES = false;
  114530. _this.CONTRAST = false;
  114531. _this.COLORCURVES = false;
  114532. _this.COLORGRADING = false;
  114533. _this.COLORGRADING3D = false;
  114534. _this.SAMPLER3DGREENDEPTH = false;
  114535. _this.SAMPLER3DBGRMAP = false;
  114536. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  114537. _this.EXPOSURE = false;
  114538. // Reflection.
  114539. _this.REFLECTION = false;
  114540. _this.REFLECTIONMAP_3D = false;
  114541. _this.REFLECTIONMAP_SPHERICAL = false;
  114542. _this.REFLECTIONMAP_PLANAR = false;
  114543. _this.REFLECTIONMAP_CUBIC = false;
  114544. _this.REFLECTIONMAP_PROJECTION = false;
  114545. _this.REFLECTIONMAP_SKYBOX = false;
  114546. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  114547. _this.REFLECTIONMAP_EXPLICIT = false;
  114548. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  114549. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  114550. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  114551. _this.INVERTCUBICMAP = false;
  114552. _this.REFLECTIONMAP_OPPOSITEZ = false;
  114553. _this.LODINREFLECTIONALPHA = false;
  114554. _this.GAMMAREFLECTION = false;
  114555. _this.RGBDREFLECTION = false;
  114556. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  114557. // Default BJS.
  114558. _this.MAINUV1 = false;
  114559. _this.MAINUV2 = false;
  114560. _this.UV1 = false;
  114561. _this.UV2 = false;
  114562. _this.CLIPPLANE = false;
  114563. _this.CLIPPLANE2 = false;
  114564. _this.CLIPPLANE3 = false;
  114565. _this.CLIPPLANE4 = false;
  114566. _this.POINTSIZE = false;
  114567. _this.FOG = false;
  114568. _this.NORMAL = false;
  114569. _this.NUM_BONE_INFLUENCERS = 0;
  114570. _this.BonesPerMesh = 0;
  114571. _this.INSTANCES = false;
  114572. _this.SHADOWFLOAT = false;
  114573. _this.rebuild();
  114574. return _this;
  114575. }
  114576. return BackgroundMaterialDefines;
  114577. }(BABYLON.MaterialDefines));
  114578. /**
  114579. * Background material used to create an efficient environement around your scene.
  114580. */
  114581. var BackgroundMaterial = /** @class */ (function (_super) {
  114582. __extends(BackgroundMaterial, _super);
  114583. /**
  114584. * Instantiates a Background Material in the given scene
  114585. * @param name The friendly name of the material
  114586. * @param scene The scene to add the material to
  114587. */
  114588. function BackgroundMaterial(name, scene) {
  114589. var _this = _super.call(this, name, scene) || this;
  114590. /**
  114591. * Key light Color (multiply against the environement texture)
  114592. */
  114593. _this.primaryColor = BABYLON.Color3.White();
  114594. _this._primaryColorShadowLevel = 0;
  114595. _this._primaryColorHighlightLevel = 0;
  114596. /**
  114597. * Reflection Texture used in the material.
  114598. * Should be author in a specific way for the best result (refer to the documentation).
  114599. */
  114600. _this.reflectionTexture = null;
  114601. /**
  114602. * Reflection Texture level of blur.
  114603. *
  114604. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  114605. * texture twice.
  114606. */
  114607. _this.reflectionBlur = 0;
  114608. /**
  114609. * Diffuse Texture used in the material.
  114610. * Should be author in a specific way for the best result (refer to the documentation).
  114611. */
  114612. _this.diffuseTexture = null;
  114613. _this._shadowLights = null;
  114614. /**
  114615. * Specify the list of lights casting shadow on the material.
  114616. * All scene shadow lights will be included if null.
  114617. */
  114618. _this.shadowLights = null;
  114619. /**
  114620. * Helps adjusting the shadow to a softer level if required.
  114621. * 0 means black shadows and 1 means no shadows.
  114622. */
  114623. _this.shadowLevel = 0;
  114624. /**
  114625. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  114626. * It is usually zero but might be interesting to modify according to your setup.
  114627. */
  114628. _this.sceneCenter = BABYLON.Vector3.Zero();
  114629. /**
  114630. * This helps specifying that the material is falling off to the sky box at grazing angle.
  114631. * This helps ensuring a nice transition when the camera goes under the ground.
  114632. */
  114633. _this.opacityFresnel = true;
  114634. /**
  114635. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  114636. * This helps adding a mirror texture on the ground.
  114637. */
  114638. _this.reflectionFresnel = false;
  114639. /**
  114640. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  114641. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  114642. */
  114643. _this.reflectionFalloffDistance = 0.0;
  114644. /**
  114645. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  114646. */
  114647. _this.reflectionAmount = 1.0;
  114648. /**
  114649. * This specifies the weight of the reflection at grazing angle.
  114650. */
  114651. _this.reflectionReflectance0 = 0.05;
  114652. /**
  114653. * This specifies the weight of the reflection at a perpendicular point of view.
  114654. */
  114655. _this.reflectionReflectance90 = 0.5;
  114656. /**
  114657. * Helps to directly use the maps channels instead of their level.
  114658. */
  114659. _this.useRGBColor = true;
  114660. /**
  114661. * This helps reducing the banding effect that could occur on the background.
  114662. */
  114663. _this.enableNoise = false;
  114664. _this._fovMultiplier = 1.0;
  114665. /**
  114666. * Enable the FOV adjustment feature controlled by fovMultiplier.
  114667. */
  114668. _this.useEquirectangularFOV = false;
  114669. _this._maxSimultaneousLights = 4;
  114670. /**
  114671. * Number of Simultaneous lights allowed on the material.
  114672. */
  114673. _this.maxSimultaneousLights = 4;
  114674. /**
  114675. * Keep track of the image processing observer to allow dispose and replace.
  114676. */
  114677. _this._imageProcessingObserver = null;
  114678. /**
  114679. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  114680. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  114681. */
  114682. _this.switchToBGR = false;
  114683. // Temp values kept as cache in the material.
  114684. _this._renderTargets = new BABYLON.SmartArray(16);
  114685. _this._reflectionControls = BABYLON.Vector4.Zero();
  114686. _this._white = BABYLON.Color3.White();
  114687. _this._primaryShadowColor = BABYLON.Color3.Black();
  114688. _this._primaryHighlightColor = BABYLON.Color3.Black();
  114689. // Setup the default processing configuration to the scene.
  114690. _this._attachImageProcessingConfiguration(null);
  114691. _this.getRenderTargetTextures = function () {
  114692. _this._renderTargets.reset();
  114693. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  114694. _this._renderTargets.push(_this._diffuseTexture);
  114695. }
  114696. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  114697. _this._renderTargets.push(_this._reflectionTexture);
  114698. }
  114699. return _this._renderTargets;
  114700. };
  114701. return _this;
  114702. }
  114703. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  114704. /**
  114705. * Experimental Internal Use Only.
  114706. *
  114707. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  114708. * This acts as a helper to set the primary color to a more "human friendly" value.
  114709. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  114710. * output color as close as possible from the chosen value.
  114711. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  114712. * part of lighting setup.)
  114713. */
  114714. get: function () {
  114715. return this.__perceptualColor;
  114716. },
  114717. set: function (value) {
  114718. this.__perceptualColor = value;
  114719. this._computePrimaryColorFromPerceptualColor();
  114720. this._markAllSubMeshesAsLightsDirty();
  114721. },
  114722. enumerable: true,
  114723. configurable: true
  114724. });
  114725. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  114726. /**
  114727. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  114728. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  114729. */
  114730. get: function () {
  114731. return this._primaryColorShadowLevel;
  114732. },
  114733. set: function (value) {
  114734. this._primaryColorShadowLevel = value;
  114735. this._computePrimaryColors();
  114736. this._markAllSubMeshesAsLightsDirty();
  114737. },
  114738. enumerable: true,
  114739. configurable: true
  114740. });
  114741. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  114742. /**
  114743. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  114744. * The primary color is used at the level chosen to define what the white area would look.
  114745. */
  114746. get: function () {
  114747. return this._primaryColorHighlightLevel;
  114748. },
  114749. set: function (value) {
  114750. this._primaryColorHighlightLevel = value;
  114751. this._computePrimaryColors();
  114752. this._markAllSubMeshesAsLightsDirty();
  114753. },
  114754. enumerable: true,
  114755. configurable: true
  114756. });
  114757. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  114758. /**
  114759. * Sets the reflection reflectance fresnel values according to the default standard
  114760. * empirically know to work well :-)
  114761. */
  114762. set: function (value) {
  114763. var reflectionWeight = value;
  114764. if (reflectionWeight < 0.5) {
  114765. reflectionWeight = reflectionWeight * 2.0;
  114766. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  114767. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  114768. }
  114769. else {
  114770. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  114771. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  114772. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  114773. }
  114774. },
  114775. enumerable: true,
  114776. configurable: true
  114777. });
  114778. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  114779. /**
  114780. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  114781. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  114782. * Recommended to be keep at 1.0 except for special cases.
  114783. */
  114784. get: function () {
  114785. return this._fovMultiplier;
  114786. },
  114787. set: function (value) {
  114788. if (isNaN(value)) {
  114789. value = 1.0;
  114790. }
  114791. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  114792. },
  114793. enumerable: true,
  114794. configurable: true
  114795. });
  114796. /**
  114797. * Attaches a new image processing configuration to the PBR Material.
  114798. * @param configuration (if null the scene configuration will be use)
  114799. */
  114800. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  114801. var _this = this;
  114802. if (configuration === this._imageProcessingConfiguration) {
  114803. return;
  114804. }
  114805. // Detaches observer.
  114806. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  114807. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  114808. }
  114809. // Pick the scene configuration if needed.
  114810. if (!configuration) {
  114811. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  114812. }
  114813. else {
  114814. this._imageProcessingConfiguration = configuration;
  114815. }
  114816. // Attaches observer.
  114817. if (this._imageProcessingConfiguration) {
  114818. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  114819. _this._computePrimaryColorFromPerceptualColor();
  114820. _this._markAllSubMeshesAsImageProcessingDirty();
  114821. });
  114822. }
  114823. };
  114824. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  114825. /**
  114826. * Gets the image processing configuration used either in this material.
  114827. */
  114828. get: function () {
  114829. return this._imageProcessingConfiguration;
  114830. },
  114831. /**
  114832. * Sets the Default image processing configuration used either in the this material.
  114833. *
  114834. * If sets to null, the scene one is in use.
  114835. */
  114836. set: function (value) {
  114837. this._attachImageProcessingConfiguration(value);
  114838. // Ensure the effect will be rebuilt.
  114839. this._markAllSubMeshesAsTexturesDirty();
  114840. },
  114841. enumerable: true,
  114842. configurable: true
  114843. });
  114844. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  114845. /**
  114846. * Gets wether the color curves effect is enabled.
  114847. */
  114848. get: function () {
  114849. return this.imageProcessingConfiguration.colorCurvesEnabled;
  114850. },
  114851. /**
  114852. * Sets wether the color curves effect is enabled.
  114853. */
  114854. set: function (value) {
  114855. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  114856. },
  114857. enumerable: true,
  114858. configurable: true
  114859. });
  114860. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  114861. /**
  114862. * Gets wether the color grading effect is enabled.
  114863. */
  114864. get: function () {
  114865. return this.imageProcessingConfiguration.colorGradingEnabled;
  114866. },
  114867. /**
  114868. * Gets wether the color grading effect is enabled.
  114869. */
  114870. set: function (value) {
  114871. this.imageProcessingConfiguration.colorGradingEnabled = value;
  114872. },
  114873. enumerable: true,
  114874. configurable: true
  114875. });
  114876. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  114877. /**
  114878. * Gets wether tonemapping is enabled or not.
  114879. */
  114880. get: function () {
  114881. return this._imageProcessingConfiguration.toneMappingEnabled;
  114882. },
  114883. /**
  114884. * Sets wether tonemapping is enabled or not
  114885. */
  114886. set: function (value) {
  114887. this._imageProcessingConfiguration.toneMappingEnabled = value;
  114888. },
  114889. enumerable: true,
  114890. configurable: true
  114891. });
  114892. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  114893. /**
  114894. * The camera exposure used on this material.
  114895. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  114896. * This corresponds to a photographic exposure.
  114897. */
  114898. get: function () {
  114899. return this._imageProcessingConfiguration.exposure;
  114900. },
  114901. /**
  114902. * The camera exposure used on this material.
  114903. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  114904. * This corresponds to a photographic exposure.
  114905. */
  114906. set: function (value) {
  114907. this._imageProcessingConfiguration.exposure = value;
  114908. },
  114909. enumerable: true,
  114910. configurable: true
  114911. });
  114912. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  114913. /**
  114914. * Gets The camera contrast used on this material.
  114915. */
  114916. get: function () {
  114917. return this._imageProcessingConfiguration.contrast;
  114918. },
  114919. /**
  114920. * Sets The camera contrast used on this material.
  114921. */
  114922. set: function (value) {
  114923. this._imageProcessingConfiguration.contrast = value;
  114924. },
  114925. enumerable: true,
  114926. configurable: true
  114927. });
  114928. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  114929. /**
  114930. * Gets the Color Grading 2D Lookup Texture.
  114931. */
  114932. get: function () {
  114933. return this._imageProcessingConfiguration.colorGradingTexture;
  114934. },
  114935. /**
  114936. * Sets the Color Grading 2D Lookup Texture.
  114937. */
  114938. set: function (value) {
  114939. this.imageProcessingConfiguration.colorGradingTexture = value;
  114940. },
  114941. enumerable: true,
  114942. configurable: true
  114943. });
  114944. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  114945. /**
  114946. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  114947. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  114948. * 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;
  114949. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  114950. */
  114951. get: function () {
  114952. return this.imageProcessingConfiguration.colorCurves;
  114953. },
  114954. /**
  114955. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  114956. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  114957. * 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;
  114958. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  114959. */
  114960. set: function (value) {
  114961. this.imageProcessingConfiguration.colorCurves = value;
  114962. },
  114963. enumerable: true,
  114964. configurable: true
  114965. });
  114966. Object.defineProperty(BackgroundMaterial.prototype, "hasRenderTargetTextures", {
  114967. /**
  114968. * Gets a boolean indicating that current material needs to register RTT
  114969. */
  114970. get: function () {
  114971. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  114972. return true;
  114973. }
  114974. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  114975. return true;
  114976. }
  114977. return false;
  114978. },
  114979. enumerable: true,
  114980. configurable: true
  114981. });
  114982. /**
  114983. * The entire material has been created in order to prevent overdraw.
  114984. * @returns false
  114985. */
  114986. BackgroundMaterial.prototype.needAlphaTesting = function () {
  114987. return true;
  114988. };
  114989. /**
  114990. * The entire material has been created in order to prevent overdraw.
  114991. * @returns true if blending is enable
  114992. */
  114993. BackgroundMaterial.prototype.needAlphaBlending = function () {
  114994. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  114995. };
  114996. /**
  114997. * Checks wether the material is ready to be rendered for a given mesh.
  114998. * @param mesh The mesh to render
  114999. * @param subMesh The submesh to check against
  115000. * @param useInstances Specify wether or not the material is used with instances
  115001. * @returns true if all the dependencies are ready (Textures, Effects...)
  115002. */
  115003. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  115004. var _this = this;
  115005. if (useInstances === void 0) { useInstances = false; }
  115006. if (subMesh.effect && this.isFrozen) {
  115007. if (this._wasPreviouslyReady) {
  115008. return true;
  115009. }
  115010. }
  115011. if (!subMesh._materialDefines) {
  115012. subMesh._materialDefines = new BackgroundMaterialDefines();
  115013. }
  115014. var scene = this.getScene();
  115015. var defines = subMesh._materialDefines;
  115016. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  115017. if (defines._renderId === scene.getRenderId()) {
  115018. return true;
  115019. }
  115020. }
  115021. var engine = scene.getEngine();
  115022. // Lights
  115023. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  115024. defines._needNormals = true;
  115025. // Textures
  115026. if (defines._areTexturesDirty) {
  115027. defines._needUVs = false;
  115028. if (scene.texturesEnabled) {
  115029. if (scene.getEngine().getCaps().textureLOD) {
  115030. defines.TEXTURELODSUPPORT = true;
  115031. }
  115032. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  115033. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  115034. return false;
  115035. }
  115036. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  115037. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  115038. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  115039. defines.OPACITYFRESNEL = this._opacityFresnel;
  115040. }
  115041. else {
  115042. defines.DIFFUSE = false;
  115043. defines.DIFFUSEHASALPHA = false;
  115044. defines.GAMMADIFFUSE = false;
  115045. defines.OPACITYFRESNEL = false;
  115046. }
  115047. var reflectionTexture = this._reflectionTexture;
  115048. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  115049. if (!reflectionTexture.isReadyOrNotBlocking()) {
  115050. return false;
  115051. }
  115052. defines.REFLECTION = true;
  115053. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  115054. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  115055. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  115056. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  115057. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  115058. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  115059. defines.REFLECTIONBGR = this.switchToBGR;
  115060. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  115061. defines.INVERTCUBICMAP = true;
  115062. }
  115063. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  115064. switch (reflectionTexture.coordinatesMode) {
  115065. case BABYLON.Texture.EXPLICIT_MODE:
  115066. defines.REFLECTIONMAP_EXPLICIT = true;
  115067. break;
  115068. case BABYLON.Texture.PLANAR_MODE:
  115069. defines.REFLECTIONMAP_PLANAR = true;
  115070. break;
  115071. case BABYLON.Texture.PROJECTION_MODE:
  115072. defines.REFLECTIONMAP_PROJECTION = true;
  115073. break;
  115074. case BABYLON.Texture.SKYBOX_MODE:
  115075. defines.REFLECTIONMAP_SKYBOX = true;
  115076. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  115077. break;
  115078. case BABYLON.Texture.SPHERICAL_MODE:
  115079. defines.REFLECTIONMAP_SPHERICAL = true;
  115080. break;
  115081. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  115082. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  115083. break;
  115084. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  115085. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  115086. break;
  115087. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  115088. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  115089. break;
  115090. case BABYLON.Texture.CUBIC_MODE:
  115091. case BABYLON.Texture.INVCUBIC_MODE:
  115092. default:
  115093. defines.REFLECTIONMAP_CUBIC = true;
  115094. break;
  115095. }
  115096. if (this.reflectionFresnel) {
  115097. defines.REFLECTIONFRESNEL = true;
  115098. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  115099. this._reflectionControls.x = this.reflectionAmount;
  115100. this._reflectionControls.y = this.reflectionReflectance0;
  115101. this._reflectionControls.z = this.reflectionReflectance90;
  115102. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  115103. }
  115104. else {
  115105. defines.REFLECTIONFRESNEL = false;
  115106. defines.REFLECTIONFALLOFF = false;
  115107. }
  115108. }
  115109. else {
  115110. defines.REFLECTION = false;
  115111. defines.REFLECTIONFRESNEL = false;
  115112. defines.REFLECTIONFALLOFF = false;
  115113. defines.REFLECTIONBLUR = false;
  115114. defines.REFLECTIONMAP_3D = false;
  115115. defines.REFLECTIONMAP_SPHERICAL = false;
  115116. defines.REFLECTIONMAP_PLANAR = false;
  115117. defines.REFLECTIONMAP_CUBIC = false;
  115118. defines.REFLECTIONMAP_PROJECTION = false;
  115119. defines.REFLECTIONMAP_SKYBOX = false;
  115120. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  115121. defines.REFLECTIONMAP_EXPLICIT = false;
  115122. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  115123. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  115124. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  115125. defines.INVERTCUBICMAP = false;
  115126. defines.REFLECTIONMAP_OPPOSITEZ = false;
  115127. defines.LODINREFLECTIONALPHA = false;
  115128. defines.GAMMAREFLECTION = false;
  115129. defines.RGBDREFLECTION = false;
  115130. }
  115131. }
  115132. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  115133. defines.USERGBCOLOR = this._useRGBColor;
  115134. defines.NOISE = this._enableNoise;
  115135. }
  115136. if (defines._areLightsDirty) {
  115137. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  115138. }
  115139. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  115140. if (!this._imageProcessingConfiguration.isReady()) {
  115141. return false;
  115142. }
  115143. this._imageProcessingConfiguration.prepareDefines(defines);
  115144. }
  115145. // Misc.
  115146. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  115147. // Values that need to be evaluated on every frame
  115148. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  115149. // Attribs
  115150. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  115151. if (mesh) {
  115152. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  115153. mesh.createNormals(true);
  115154. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  115155. }
  115156. }
  115157. }
  115158. // Get correct effect
  115159. if (defines.isDirty) {
  115160. defines.markAsProcessed();
  115161. scene.resetCachedMaterial();
  115162. // Fallbacks
  115163. var fallbacks = new BABYLON.EffectFallbacks();
  115164. if (defines.FOG) {
  115165. fallbacks.addFallback(0, "FOG");
  115166. }
  115167. if (defines.POINTSIZE) {
  115168. fallbacks.addFallback(1, "POINTSIZE");
  115169. }
  115170. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  115171. if (defines.NUM_BONE_INFLUENCERS > 0) {
  115172. fallbacks.addCPUSkinningFallback(0, mesh);
  115173. }
  115174. //Attributes
  115175. var attribs = [BABYLON.VertexBuffer.PositionKind];
  115176. if (defines.NORMAL) {
  115177. attribs.push(BABYLON.VertexBuffer.NormalKind);
  115178. }
  115179. if (defines.UV1) {
  115180. attribs.push(BABYLON.VertexBuffer.UVKind);
  115181. }
  115182. if (defines.UV2) {
  115183. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  115184. }
  115185. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  115186. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  115187. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  115188. "vFogInfos", "vFogColor", "pointSize",
  115189. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "mBones",
  115190. "vPrimaryColor", "vPrimaryColorShadow",
  115191. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  115192. "shadowLevel", "alpha",
  115193. "vBackgroundCenter", "vReflectionControl",
  115194. "vDiffuseInfos", "diffuseMatrix",
  115195. ];
  115196. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  115197. var uniformBuffers = ["Material", "Scene"];
  115198. if (BABYLON.ImageProcessingConfiguration) {
  115199. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  115200. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  115201. }
  115202. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  115203. uniformsNames: uniforms,
  115204. uniformBuffersNames: uniformBuffers,
  115205. samplers: samplers,
  115206. defines: defines,
  115207. maxSimultaneousLights: this._maxSimultaneousLights
  115208. });
  115209. var onCompiled = function (effect) {
  115210. if (_this.onCompiled) {
  115211. _this.onCompiled(effect);
  115212. }
  115213. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  115214. };
  115215. var join = defines.toString();
  115216. subMesh.setEffect(scene.getEngine().createEffect("background", {
  115217. attributes: attribs,
  115218. uniformsNames: uniforms,
  115219. uniformBuffersNames: uniformBuffers,
  115220. samplers: samplers,
  115221. defines: join,
  115222. fallbacks: fallbacks,
  115223. onCompiled: onCompiled,
  115224. onError: this.onError,
  115225. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  115226. }, engine), defines);
  115227. this.buildUniformLayout();
  115228. }
  115229. if (!subMesh.effect || !subMesh.effect.isReady()) {
  115230. return false;
  115231. }
  115232. defines._renderId = scene.getRenderId();
  115233. this._wasPreviouslyReady = true;
  115234. return true;
  115235. };
  115236. /**
  115237. * Compute the primary color according to the chosen perceptual color.
  115238. */
  115239. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  115240. if (!this.__perceptualColor) {
  115241. return;
  115242. }
  115243. this._primaryColor.copyFrom(this.__perceptualColor);
  115244. // Revert gamma space.
  115245. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  115246. // Revert image processing configuration.
  115247. if (this._imageProcessingConfiguration) {
  115248. // Revert Exposure.
  115249. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  115250. }
  115251. this._computePrimaryColors();
  115252. };
  115253. /**
  115254. * Compute the highlights and shadow colors according to their chosen levels.
  115255. */
  115256. BackgroundMaterial.prototype._computePrimaryColors = function () {
  115257. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  115258. return;
  115259. }
  115260. // Find the highlight color based on the configuration.
  115261. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  115262. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  115263. // Find the shadow color based on the configuration.
  115264. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  115265. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  115266. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  115267. };
  115268. /**
  115269. * Build the uniform buffer used in the material.
  115270. */
  115271. BackgroundMaterial.prototype.buildUniformLayout = function () {
  115272. // Order is important !
  115273. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  115274. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  115275. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  115276. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  115277. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  115278. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  115279. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  115280. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  115281. this._uniformBuffer.addUniform("pointSize", 1);
  115282. this._uniformBuffer.addUniform("shadowLevel", 1);
  115283. this._uniformBuffer.addUniform("alpha", 1);
  115284. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  115285. this._uniformBuffer.addUniform("vReflectionControl", 4);
  115286. this._uniformBuffer.create();
  115287. };
  115288. /**
  115289. * Unbind the material.
  115290. */
  115291. BackgroundMaterial.prototype.unbind = function () {
  115292. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  115293. this._uniformBuffer.setTexture("diffuseSampler", null);
  115294. }
  115295. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  115296. this._uniformBuffer.setTexture("reflectionSampler", null);
  115297. }
  115298. _super.prototype.unbind.call(this);
  115299. };
  115300. /**
  115301. * Bind only the world matrix to the material.
  115302. * @param world The world matrix to bind.
  115303. */
  115304. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  115305. this._activeEffect.setMatrix("world", world);
  115306. };
  115307. /**
  115308. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  115309. * @param world The world matrix to bind.
  115310. * @param subMesh The submesh to bind for.
  115311. */
  115312. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  115313. var scene = this.getScene();
  115314. var defines = subMesh._materialDefines;
  115315. if (!defines) {
  115316. return;
  115317. }
  115318. var effect = subMesh.effect;
  115319. if (!effect) {
  115320. return;
  115321. }
  115322. this._activeEffect = effect;
  115323. // Matrices
  115324. this.bindOnlyWorldMatrix(world);
  115325. // Bones
  115326. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  115327. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  115328. if (mustRebind) {
  115329. this._uniformBuffer.bindToEffect(effect, "Material");
  115330. this.bindViewProjection(effect);
  115331. var reflectionTexture = this._reflectionTexture;
  115332. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  115333. // Texture uniforms
  115334. if (scene.texturesEnabled) {
  115335. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  115336. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  115337. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  115338. }
  115339. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  115340. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  115341. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  115342. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  115343. }
  115344. }
  115345. if (this.shadowLevel > 0) {
  115346. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  115347. }
  115348. this._uniformBuffer.updateFloat("alpha", this.alpha);
  115349. // Point size
  115350. if (this.pointsCloud) {
  115351. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  115352. }
  115353. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  115354. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  115355. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  115356. }
  115357. else {
  115358. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  115359. }
  115360. }
  115361. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  115362. // Textures
  115363. if (scene.texturesEnabled) {
  115364. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  115365. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  115366. }
  115367. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  115368. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  115369. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  115370. }
  115371. else if (!defines.REFLECTIONBLUR) {
  115372. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  115373. }
  115374. else {
  115375. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  115376. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  115377. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  115378. }
  115379. if (defines.REFLECTIONFRESNEL) {
  115380. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  115381. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  115382. }
  115383. }
  115384. }
  115385. // Clip plane
  115386. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  115387. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  115388. }
  115389. if (mustRebind || !this.isFrozen) {
  115390. if (scene.lightsEnabled) {
  115391. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  115392. }
  115393. // View
  115394. this.bindView(effect);
  115395. // Fog
  115396. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  115397. // image processing
  115398. if (this._imageProcessingConfiguration) {
  115399. this._imageProcessingConfiguration.bind(this._activeEffect);
  115400. }
  115401. }
  115402. this._uniformBuffer.update();
  115403. this._afterBind(mesh, this._activeEffect);
  115404. };
  115405. /**
  115406. * Dispose the material.
  115407. * @param forceDisposeEffect Force disposal of the associated effect.
  115408. * @param forceDisposeTextures Force disposal of the associated textures.
  115409. */
  115410. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  115411. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  115412. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  115413. if (forceDisposeTextures) {
  115414. if (this.diffuseTexture) {
  115415. this.diffuseTexture.dispose();
  115416. }
  115417. if (this.reflectionTexture) {
  115418. this.reflectionTexture.dispose();
  115419. }
  115420. }
  115421. this._renderTargets.dispose();
  115422. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  115423. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  115424. }
  115425. _super.prototype.dispose.call(this, forceDisposeEffect);
  115426. };
  115427. /**
  115428. * Clones the material.
  115429. * @param name The cloned name.
  115430. * @returns The cloned material.
  115431. */
  115432. BackgroundMaterial.prototype.clone = function (name) {
  115433. var _this = this;
  115434. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  115435. };
  115436. /**
  115437. * Serializes the current material to its JSON representation.
  115438. * @returns The JSON representation.
  115439. */
  115440. BackgroundMaterial.prototype.serialize = function () {
  115441. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  115442. serializationObject.customType = "BABYLON.BackgroundMaterial";
  115443. return serializationObject;
  115444. };
  115445. /**
  115446. * Gets the class name of the material
  115447. * @returns "BackgroundMaterial"
  115448. */
  115449. BackgroundMaterial.prototype.getClassName = function () {
  115450. return "BackgroundMaterial";
  115451. };
  115452. /**
  115453. * Parse a JSON input to create back a background material.
  115454. * @param source The JSON data to parse
  115455. * @param scene The scene to create the parsed material in
  115456. * @param rootUrl The root url of the assets the material depends upon
  115457. * @returns the instantiated BackgroundMaterial.
  115458. */
  115459. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  115460. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  115461. };
  115462. /**
  115463. * Standard reflectance value at parallel view angle.
  115464. */
  115465. BackgroundMaterial.StandardReflectance0 = 0.05;
  115466. /**
  115467. * Standard reflectance value at grazing angle.
  115468. */
  115469. BackgroundMaterial.StandardReflectance90 = 0.5;
  115470. __decorate([
  115471. BABYLON.serializeAsColor3()
  115472. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  115473. __decorate([
  115474. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  115475. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  115476. __decorate([
  115477. BABYLON.serializeAsColor3()
  115478. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  115479. __decorate([
  115480. BABYLON.serialize()
  115481. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  115482. __decorate([
  115483. BABYLON.serialize()
  115484. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  115485. __decorate([
  115486. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  115487. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  115488. __decorate([
  115489. BABYLON.serializeAsTexture()
  115490. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  115491. __decorate([
  115492. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115493. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  115494. __decorate([
  115495. BABYLON.serialize()
  115496. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  115497. __decorate([
  115498. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115499. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  115500. __decorate([
  115501. BABYLON.serializeAsTexture()
  115502. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  115503. __decorate([
  115504. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115505. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  115506. __decorate([
  115507. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115508. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  115509. __decorate([
  115510. BABYLON.serialize()
  115511. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  115512. __decorate([
  115513. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115514. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  115515. __decorate([
  115516. BABYLON.serializeAsVector3()
  115517. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  115518. __decorate([
  115519. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115520. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  115521. __decorate([
  115522. BABYLON.serialize()
  115523. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  115524. __decorate([
  115525. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115526. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  115527. __decorate([
  115528. BABYLON.serialize()
  115529. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  115530. __decorate([
  115531. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115532. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  115533. __decorate([
  115534. BABYLON.serialize()
  115535. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  115536. __decorate([
  115537. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115538. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  115539. __decorate([
  115540. BABYLON.serialize()
  115541. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  115542. __decorate([
  115543. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115544. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  115545. __decorate([
  115546. BABYLON.serialize()
  115547. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  115548. __decorate([
  115549. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115550. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  115551. __decorate([
  115552. BABYLON.serialize()
  115553. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  115554. __decorate([
  115555. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115556. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  115557. __decorate([
  115558. BABYLON.serialize()
  115559. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  115560. __decorate([
  115561. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115562. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  115563. __decorate([
  115564. BABYLON.serialize()
  115565. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  115566. __decorate([
  115567. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115568. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  115569. __decorate([
  115570. BABYLON.serialize()
  115571. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  115572. __decorate([
  115573. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115574. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  115575. __decorate([
  115576. BABYLON.serializeAsImageProcessingConfiguration()
  115577. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  115578. return BackgroundMaterial;
  115579. }(BABYLON.PushMaterial));
  115580. BABYLON.BackgroundMaterial = BackgroundMaterial;
  115581. })(BABYLON || (BABYLON = {}));
  115582. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  115583. var __assign = (this && this.__assign) || function () {
  115584. __assign = Object.assign || function(t) {
  115585. for (var s, i = 1, n = arguments.length; i < n; i++) {
  115586. s = arguments[i];
  115587. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  115588. t[p] = s[p];
  115589. }
  115590. return t;
  115591. };
  115592. return __assign.apply(this, arguments);
  115593. };
  115594. var BABYLON;
  115595. (function (BABYLON) {
  115596. /**
  115597. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  115598. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  115599. * It also helps with the default setup of your imageProcessing configuration.
  115600. */
  115601. var EnvironmentHelper = /** @class */ (function () {
  115602. /**
  115603. * constructor
  115604. * @param options
  115605. * @param scene The scene to add the material to
  115606. */
  115607. function EnvironmentHelper(options, scene) {
  115608. var _this = this;
  115609. this._errorHandler = function (message, exception) {
  115610. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  115611. };
  115612. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  115613. this._scene = scene;
  115614. this.onErrorObservable = new BABYLON.Observable();
  115615. this._setupBackground();
  115616. this._setupImageProcessing();
  115617. }
  115618. /**
  115619. * Creates the default options for the helper.
  115620. */
  115621. EnvironmentHelper._getDefaultOptions = function () {
  115622. return {
  115623. createGround: true,
  115624. groundSize: 15,
  115625. groundTexture: this._groundTextureCDNUrl,
  115626. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  115627. groundOpacity: 0.9,
  115628. enableGroundShadow: true,
  115629. groundShadowLevel: 0.5,
  115630. enableGroundMirror: false,
  115631. groundMirrorSizeRatio: 0.3,
  115632. groundMirrorBlurKernel: 64,
  115633. groundMirrorAmount: 1,
  115634. groundMirrorFresnelWeight: 1,
  115635. groundMirrorFallOffDistance: 0,
  115636. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  115637. groundYBias: 0.00001,
  115638. createSkybox: true,
  115639. skyboxSize: 20,
  115640. skyboxTexture: this._skyboxTextureCDNUrl,
  115641. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  115642. backgroundYRotation: 0,
  115643. sizeAuto: true,
  115644. rootPosition: BABYLON.Vector3.Zero(),
  115645. setupImageProcessing: true,
  115646. environmentTexture: this._environmentTextureCDNUrl,
  115647. cameraExposure: 0.8,
  115648. cameraContrast: 1.2,
  115649. toneMappingEnabled: true,
  115650. };
  115651. };
  115652. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  115653. /**
  115654. * Gets the root mesh created by the helper.
  115655. */
  115656. get: function () {
  115657. return this._rootMesh;
  115658. },
  115659. enumerable: true,
  115660. configurable: true
  115661. });
  115662. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  115663. /**
  115664. * Gets the skybox created by the helper.
  115665. */
  115666. get: function () {
  115667. return this._skybox;
  115668. },
  115669. enumerable: true,
  115670. configurable: true
  115671. });
  115672. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  115673. /**
  115674. * Gets the skybox texture created by the helper.
  115675. */
  115676. get: function () {
  115677. return this._skyboxTexture;
  115678. },
  115679. enumerable: true,
  115680. configurable: true
  115681. });
  115682. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  115683. /**
  115684. * Gets the skybox material created by the helper.
  115685. */
  115686. get: function () {
  115687. return this._skyboxMaterial;
  115688. },
  115689. enumerable: true,
  115690. configurable: true
  115691. });
  115692. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  115693. /**
  115694. * Gets the ground mesh created by the helper.
  115695. */
  115696. get: function () {
  115697. return this._ground;
  115698. },
  115699. enumerable: true,
  115700. configurable: true
  115701. });
  115702. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  115703. /**
  115704. * Gets the ground texture created by the helper.
  115705. */
  115706. get: function () {
  115707. return this._groundTexture;
  115708. },
  115709. enumerable: true,
  115710. configurable: true
  115711. });
  115712. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  115713. /**
  115714. * Gets the ground mirror created by the helper.
  115715. */
  115716. get: function () {
  115717. return this._groundMirror;
  115718. },
  115719. enumerable: true,
  115720. configurable: true
  115721. });
  115722. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  115723. /**
  115724. * Gets the ground mirror render list to helps pushing the meshes
  115725. * you wish in the ground reflection.
  115726. */
  115727. get: function () {
  115728. if (this._groundMirror) {
  115729. return this._groundMirror.renderList;
  115730. }
  115731. return null;
  115732. },
  115733. enumerable: true,
  115734. configurable: true
  115735. });
  115736. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  115737. /**
  115738. * Gets the ground material created by the helper.
  115739. */
  115740. get: function () {
  115741. return this._groundMaterial;
  115742. },
  115743. enumerable: true,
  115744. configurable: true
  115745. });
  115746. /**
  115747. * Updates the background according to the new options
  115748. * @param options
  115749. */
  115750. EnvironmentHelper.prototype.updateOptions = function (options) {
  115751. var newOptions = __assign({}, this._options, options);
  115752. if (this._ground && !newOptions.createGround) {
  115753. this._ground.dispose();
  115754. this._ground = null;
  115755. }
  115756. if (this._groundMaterial && !newOptions.createGround) {
  115757. this._groundMaterial.dispose();
  115758. this._groundMaterial = null;
  115759. }
  115760. if (this._groundTexture) {
  115761. if (this._options.groundTexture != newOptions.groundTexture) {
  115762. this._groundTexture.dispose();
  115763. this._groundTexture = null;
  115764. }
  115765. }
  115766. if (this._skybox && !newOptions.createSkybox) {
  115767. this._skybox.dispose();
  115768. this._skybox = null;
  115769. }
  115770. if (this._skyboxMaterial && !newOptions.createSkybox) {
  115771. this._skyboxMaterial.dispose();
  115772. this._skyboxMaterial = null;
  115773. }
  115774. if (this._skyboxTexture) {
  115775. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  115776. this._skyboxTexture.dispose();
  115777. this._skyboxTexture = null;
  115778. }
  115779. }
  115780. if (this._groundMirror && !newOptions.enableGroundMirror) {
  115781. this._groundMirror.dispose();
  115782. this._groundMirror = null;
  115783. }
  115784. if (this._scene.environmentTexture) {
  115785. if (this._options.environmentTexture != newOptions.environmentTexture) {
  115786. this._scene.environmentTexture.dispose();
  115787. }
  115788. }
  115789. this._options = newOptions;
  115790. this._setupBackground();
  115791. this._setupImageProcessing();
  115792. };
  115793. /**
  115794. * Sets the primary color of all the available elements.
  115795. * @param color the main color to affect to the ground and the background
  115796. */
  115797. EnvironmentHelper.prototype.setMainColor = function (color) {
  115798. if (this.groundMaterial) {
  115799. this.groundMaterial.primaryColor = color;
  115800. }
  115801. if (this.skyboxMaterial) {
  115802. this.skyboxMaterial.primaryColor = color;
  115803. }
  115804. if (this.groundMirror) {
  115805. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  115806. }
  115807. };
  115808. /**
  115809. * Setup the image processing according to the specified options.
  115810. */
  115811. EnvironmentHelper.prototype._setupImageProcessing = function () {
  115812. if (this._options.setupImageProcessing) {
  115813. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  115814. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  115815. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  115816. this._setupEnvironmentTexture();
  115817. }
  115818. };
  115819. /**
  115820. * Setup the environment texture according to the specified options.
  115821. */
  115822. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  115823. if (this._scene.environmentTexture) {
  115824. return;
  115825. }
  115826. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  115827. this._scene.environmentTexture = this._options.environmentTexture;
  115828. return;
  115829. }
  115830. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  115831. this._scene.environmentTexture = environmentTexture;
  115832. };
  115833. /**
  115834. * Setup the background according to the specified options.
  115835. */
  115836. EnvironmentHelper.prototype._setupBackground = function () {
  115837. if (!this._rootMesh) {
  115838. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  115839. }
  115840. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  115841. var sceneSize = this._getSceneSize();
  115842. if (this._options.createGround) {
  115843. this._setupGround(sceneSize);
  115844. this._setupGroundMaterial();
  115845. this._setupGroundDiffuseTexture();
  115846. if (this._options.enableGroundMirror) {
  115847. this._setupGroundMirrorTexture(sceneSize);
  115848. }
  115849. this._setupMirrorInGroundMaterial();
  115850. }
  115851. if (this._options.createSkybox) {
  115852. this._setupSkybox(sceneSize);
  115853. this._setupSkyboxMaterial();
  115854. this._setupSkyboxReflectionTexture();
  115855. }
  115856. this._rootMesh.position.x = sceneSize.rootPosition.x;
  115857. this._rootMesh.position.z = sceneSize.rootPosition.z;
  115858. this._rootMesh.position.y = sceneSize.rootPosition.y;
  115859. };
  115860. /**
  115861. * Get the scene sizes according to the setup.
  115862. */
  115863. EnvironmentHelper.prototype._getSceneSize = function () {
  115864. var _this = this;
  115865. var groundSize = this._options.groundSize;
  115866. var skyboxSize = this._options.skyboxSize;
  115867. var rootPosition = this._options.rootPosition;
  115868. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  115869. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  115870. }
  115871. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  115872. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  115873. });
  115874. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  115875. if (this._options.sizeAuto) {
  115876. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  115877. this._scene.activeCamera.upperRadiusLimit) {
  115878. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  115879. skyboxSize = groundSize;
  115880. }
  115881. var sceneDiagonalLenght = sceneDiagonal.length();
  115882. if (sceneDiagonalLenght > groundSize) {
  115883. groundSize = sceneDiagonalLenght * 2;
  115884. skyboxSize = groundSize;
  115885. }
  115886. // 10 % bigger.
  115887. groundSize *= 1.1;
  115888. skyboxSize *= 1.5;
  115889. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  115890. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  115891. }
  115892. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  115893. };
  115894. /**
  115895. * Setup the ground according to the specified options.
  115896. */
  115897. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  115898. var _this = this;
  115899. if (!this._ground || this._ground.isDisposed()) {
  115900. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  115901. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  115902. this._ground.parent = this._rootMesh;
  115903. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  115904. }
  115905. this._ground.receiveShadows = this._options.enableGroundShadow;
  115906. };
  115907. /**
  115908. * Setup the ground material according to the specified options.
  115909. */
  115910. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  115911. if (!this._groundMaterial) {
  115912. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  115913. }
  115914. this._groundMaterial.alpha = this._options.groundOpacity;
  115915. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  115916. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  115917. this._groundMaterial.primaryColor = this._options.groundColor;
  115918. this._groundMaterial.useRGBColor = false;
  115919. this._groundMaterial.enableNoise = true;
  115920. if (this._ground) {
  115921. this._ground.material = this._groundMaterial;
  115922. }
  115923. };
  115924. /**
  115925. * Setup the ground diffuse texture according to the specified options.
  115926. */
  115927. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  115928. if (!this._groundMaterial) {
  115929. return;
  115930. }
  115931. if (this._groundTexture) {
  115932. return;
  115933. }
  115934. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  115935. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  115936. return;
  115937. }
  115938. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  115939. diffuseTexture.gammaSpace = false;
  115940. diffuseTexture.hasAlpha = true;
  115941. this._groundMaterial.diffuseTexture = diffuseTexture;
  115942. };
  115943. /**
  115944. * Setup the ground mirror texture according to the specified options.
  115945. */
  115946. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  115947. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  115948. if (!this._groundMirror) {
  115949. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  115950. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  115951. this._groundMirror.anisotropicFilteringLevel = 1;
  115952. this._groundMirror.wrapU = wrapping;
  115953. this._groundMirror.wrapV = wrapping;
  115954. this._groundMirror.gammaSpace = false;
  115955. if (this._groundMirror.renderList) {
  115956. for (var i = 0; i < this._scene.meshes.length; i++) {
  115957. var mesh = this._scene.meshes[i];
  115958. if (mesh !== this._ground &&
  115959. mesh !== this._skybox &&
  115960. mesh !== this._rootMesh) {
  115961. this._groundMirror.renderList.push(mesh);
  115962. }
  115963. }
  115964. }
  115965. }
  115966. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  115967. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  115968. };
  115969. /**
  115970. * Setup the ground to receive the mirror texture.
  115971. */
  115972. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  115973. if (this._groundMaterial) {
  115974. this._groundMaterial.reflectionTexture = this._groundMirror;
  115975. this._groundMaterial.reflectionFresnel = true;
  115976. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  115977. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  115978. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  115979. }
  115980. };
  115981. /**
  115982. * Setup the skybox according to the specified options.
  115983. */
  115984. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  115985. var _this = this;
  115986. if (!this._skybox || this._skybox.isDisposed()) {
  115987. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  115988. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  115989. }
  115990. this._skybox.parent = this._rootMesh;
  115991. };
  115992. /**
  115993. * Setup the skybox material according to the specified options.
  115994. */
  115995. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  115996. if (!this._skybox) {
  115997. return;
  115998. }
  115999. if (!this._skyboxMaterial) {
  116000. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  116001. }
  116002. this._skyboxMaterial.useRGBColor = false;
  116003. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  116004. this._skyboxMaterial.enableNoise = true;
  116005. this._skybox.material = this._skyboxMaterial;
  116006. };
  116007. /**
  116008. * Setup the skybox reflection texture according to the specified options.
  116009. */
  116010. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  116011. if (!this._skyboxMaterial) {
  116012. return;
  116013. }
  116014. if (this._skyboxTexture) {
  116015. return;
  116016. }
  116017. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  116018. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  116019. return;
  116020. }
  116021. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  116022. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  116023. this._skyboxTexture.gammaSpace = false;
  116024. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  116025. };
  116026. /**
  116027. * Dispose all the elements created by the Helper.
  116028. */
  116029. EnvironmentHelper.prototype.dispose = function () {
  116030. if (this._groundMaterial) {
  116031. this._groundMaterial.dispose(true, true);
  116032. }
  116033. if (this._skyboxMaterial) {
  116034. this._skyboxMaterial.dispose(true, true);
  116035. }
  116036. this._rootMesh.dispose(false);
  116037. };
  116038. /**
  116039. * Default ground texture URL.
  116040. */
  116041. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  116042. /**
  116043. * Default skybox texture URL.
  116044. */
  116045. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  116046. /**
  116047. * Default environment texture URL.
  116048. */
  116049. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  116050. return EnvironmentHelper;
  116051. }());
  116052. BABYLON.EnvironmentHelper = EnvironmentHelper;
  116053. })(BABYLON || (BABYLON = {}));
  116054. //# sourceMappingURL=babylon.environmentHelper.js.map
  116055. var BABYLON;
  116056. (function (BABYLON) {
  116057. /** Internal class used to store shapes for emitters */
  116058. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  116059. function ParticleSystemSetEmitterCreationOptions() {
  116060. }
  116061. return ParticleSystemSetEmitterCreationOptions;
  116062. }());
  116063. /**
  116064. * Represents a set of particle systems working together to create a specific effect
  116065. */
  116066. var ParticleSystemSet = /** @class */ (function () {
  116067. function ParticleSystemSet() {
  116068. /**
  116069. * Gets the particle system list
  116070. */
  116071. this.systems = new Array();
  116072. }
  116073. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  116074. /**
  116075. * Gets the emitter node used with this set
  116076. */
  116077. get: function () {
  116078. return this._emitterNode;
  116079. },
  116080. enumerable: true,
  116081. configurable: true
  116082. });
  116083. /**
  116084. * Creates a new emitter mesh as a sphere
  116085. * @param options defines the options used to create the sphere
  116086. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  116087. * @param scene defines the hosting scene
  116088. */
  116089. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  116090. if (this._emitterNode) {
  116091. this._emitterNode.dispose();
  116092. }
  116093. this._emitterCreationOptions = {
  116094. kind: "Sphere",
  116095. options: options,
  116096. renderingGroupId: renderingGroupId
  116097. };
  116098. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  116099. emitterMesh.renderingGroupId = renderingGroupId;
  116100. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  116101. material.emissiveColor = options.color;
  116102. emitterMesh.material = material;
  116103. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  116104. var system = _a[_i];
  116105. system.emitter = emitterMesh;
  116106. }
  116107. this._emitterNode = emitterMesh;
  116108. };
  116109. /**
  116110. * Starts all particle systems of the set
  116111. * @param emitter defines an optional mesh to use as emitter for the particle systems
  116112. */
  116113. ParticleSystemSet.prototype.start = function (emitter) {
  116114. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  116115. var system = _a[_i];
  116116. if (emitter) {
  116117. system.emitter = emitter;
  116118. }
  116119. system.start();
  116120. }
  116121. };
  116122. /**
  116123. * Release all associated resources
  116124. */
  116125. ParticleSystemSet.prototype.dispose = function () {
  116126. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  116127. var system = _a[_i];
  116128. system.dispose();
  116129. }
  116130. this.systems = [];
  116131. if (this._emitterNode) {
  116132. this._emitterNode.dispose();
  116133. this._emitterNode = null;
  116134. }
  116135. };
  116136. /**
  116137. * Serialize the set into a JSON compatible object
  116138. * @returns a JSON compatible representation of the set
  116139. */
  116140. ParticleSystemSet.prototype.serialize = function () {
  116141. var result = {};
  116142. result.systems = [];
  116143. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  116144. var system = _a[_i];
  116145. result.systems.push(system.serialize());
  116146. }
  116147. if (this._emitterNode) {
  116148. result.emitter = this._emitterCreationOptions;
  116149. }
  116150. return result;
  116151. };
  116152. /**
  116153. * Parse a new ParticleSystemSet from a serialized source
  116154. * @param data defines a JSON compatible representation of the set
  116155. * @param scene defines the hosting scene
  116156. * @param gpu defines if we want GPU particles or CPU particles
  116157. * @returns a new ParticleSystemSet
  116158. */
  116159. ParticleSystemSet.Parse = function (data, scene, gpu) {
  116160. if (gpu === void 0) { gpu = false; }
  116161. var result = new ParticleSystemSet();
  116162. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  116163. scene = scene || BABYLON.Engine.LastCreatedScene;
  116164. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  116165. var system = _a[_i];
  116166. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl, true) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl, true));
  116167. }
  116168. if (data.emitter) {
  116169. var options = data.emitter.options;
  116170. switch (data.emitter.kind) {
  116171. case "Sphere":
  116172. result.setEmitterAsSphere({
  116173. diameter: options.diameter,
  116174. segments: options.segments,
  116175. color: BABYLON.Color3.FromArray(options.color)
  116176. }, data.emitter.renderingGroupId, scene);
  116177. break;
  116178. }
  116179. }
  116180. return result;
  116181. };
  116182. return ParticleSystemSet;
  116183. }());
  116184. BABYLON.ParticleSystemSet = ParticleSystemSet;
  116185. })(BABYLON || (BABYLON = {}));
  116186. //# sourceMappingURL=babylon.particleSystemSet.js.map
  116187. var BABYLON;
  116188. (function (BABYLON) {
  116189. /**
  116190. * This class is made for on one-liner static method to help creating particle system set.
  116191. */
  116192. var ParticleHelper = /** @class */ (function () {
  116193. function ParticleHelper() {
  116194. }
  116195. /**
  116196. * Create a default particle system that you can tweak
  116197. * @param emitter defines the emitter to use
  116198. * @param capacity defines the system capacity (default is 500 particles)
  116199. * @param scene defines the hosting scene
  116200. * @param useGPU defines if a GPUParticleSystem must be created (default is false)
  116201. * @returns the new Particle system
  116202. */
  116203. ParticleHelper.CreateDefault = function (emitter, capacity, scene, useGPU) {
  116204. if (capacity === void 0) { capacity = 500; }
  116205. if (useGPU === void 0) { useGPU = false; }
  116206. var system;
  116207. if (useGPU) {
  116208. system = new BABYLON.GPUParticleSystem("default system", { capacity: capacity }, scene);
  116209. }
  116210. else {
  116211. system = new BABYLON.ParticleSystem("default system", capacity, scene);
  116212. }
  116213. system.emitter = emitter;
  116214. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  116215. system.createConeEmitter(0.1, Math.PI / 4);
  116216. // Particle color
  116217. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  116218. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  116219. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  116220. // Particle Size
  116221. system.minSize = 0.1;
  116222. system.maxSize = 0.1;
  116223. // Emission speed
  116224. system.minEmitPower = 2;
  116225. system.maxEmitPower = 2;
  116226. // Update speed
  116227. system.updateSpeed = 1 / 60;
  116228. system.emitRate = 30;
  116229. return system;
  116230. };
  116231. /**
  116232. * This is the main static method (one-liner) of this helper to create different particle systems
  116233. * @param type This string represents the type to the particle system to create
  116234. * @param scene The scene where the particle system should live
  116235. * @param gpu If the system will use gpu
  116236. * @returns the ParticleSystemSet created
  116237. */
  116238. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  116239. if (gpu === void 0) { gpu = false; }
  116240. if (!scene) {
  116241. scene = BABYLON.Engine.LastCreatedScene;
  116242. }
  116243. var token = {};
  116244. scene._addPendingData(token);
  116245. return new Promise(function (resolve, reject) {
  116246. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  116247. scene._removePendingData(token);
  116248. return reject("Particle system with GPU is not supported.");
  116249. }
  116250. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  116251. scene._removePendingData(token);
  116252. var newData = JSON.parse(data.toString());
  116253. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  116254. }, undefined, undefined, undefined, function (req, exception) {
  116255. scene._removePendingData(token);
  116256. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  116257. });
  116258. });
  116259. };
  116260. /**
  116261. * Static function used to export a particle system to a ParticleSystemSet variable.
  116262. * Please note that the emitter shape is not exported
  116263. * @param systems defines the particle systems to export
  116264. * @returns the created particle system set
  116265. */
  116266. ParticleHelper.ExportSet = function (systems) {
  116267. var set = new BABYLON.ParticleSystemSet();
  116268. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  116269. var system = systems_1[_i];
  116270. set.systems.push(system);
  116271. }
  116272. return set;
  116273. };
  116274. /**
  116275. * Gets or sets base Assets URL
  116276. */
  116277. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  116278. return ParticleHelper;
  116279. }());
  116280. BABYLON.ParticleHelper = ParticleHelper;
  116281. })(BABYLON || (BABYLON = {}));
  116282. //# sourceMappingURL=babylon.particleHelper.js.map
  116283. var BABYLON;
  116284. (function (BABYLON) {
  116285. /**
  116286. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  116287. * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.
  116288. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  116289. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  116290. */
  116291. var VideoDome = /** @class */ (function (_super) {
  116292. __extends(VideoDome, _super);
  116293. /**
  116294. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  116295. * @param name Element's name, child elements will append suffixes for their own names.
  116296. * @param urlsOrVideo defines the url(s) or the video element to use
  116297. * @param options An object containing optional or exposed sub element properties
  116298. */
  116299. function VideoDome(name, urlsOrVideo, options, scene) {
  116300. var _this = _super.call(this, name, scene) || this;
  116301. _this._useDirectMapping = false;
  116302. // set defaults and manage values
  116303. name = name || "videoDome";
  116304. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  116305. options.clickToPlay = Boolean(options.clickToPlay);
  116306. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  116307. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  116308. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  116309. if (options.useDirectMapping === undefined) {
  116310. _this._useDirectMapping = true;
  116311. }
  116312. else {
  116313. _this._useDirectMapping = options.useDirectMapping;
  116314. }
  116315. _this._setReady(false);
  116316. // create
  116317. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  116318. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  116319. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  116320. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  116321. texture.onLoadObservable.addOnce(function () {
  116322. _this._setReady(true);
  116323. });
  116324. // configure material
  116325. material.useEquirectangularFOV = true;
  116326. material.fovMultiplier = 1.0;
  116327. material.opacityFresnel = false;
  116328. if (_this._useDirectMapping) {
  116329. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  116330. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  116331. material.diffuseTexture = texture;
  116332. }
  116333. else {
  116334. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  116335. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  116336. material.reflectionTexture = texture;
  116337. }
  116338. // configure mesh
  116339. _this._mesh.material = material;
  116340. _this._mesh.parent = _this;
  116341. // optional configuration
  116342. if (options.clickToPlay) {
  116343. scene.onPointerUp = function () {
  116344. _this._videoTexture.video.play();
  116345. };
  116346. }
  116347. return _this;
  116348. }
  116349. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  116350. /**
  116351. * Gets the video texture being displayed on the sphere
  116352. */
  116353. get: function () {
  116354. return this._videoTexture;
  116355. },
  116356. enumerable: true,
  116357. configurable: true
  116358. });
  116359. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  116360. /**
  116361. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  116362. * Also see the options.resolution property.
  116363. */
  116364. get: function () {
  116365. return this._material.fovMultiplier;
  116366. },
  116367. set: function (value) {
  116368. this._material.fovMultiplier = value;
  116369. },
  116370. enumerable: true,
  116371. configurable: true
  116372. });
  116373. /**
  116374. * Releases resources associated with this node.
  116375. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  116376. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  116377. */
  116378. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  116379. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  116380. this._videoTexture.dispose();
  116381. this._mesh.dispose();
  116382. this._material.dispose();
  116383. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  116384. };
  116385. return VideoDome;
  116386. }(BABYLON.TransformNode));
  116387. BABYLON.VideoDome = VideoDome;
  116388. })(BABYLON || (BABYLON = {}));
  116389. //# sourceMappingURL=babylon.videoDome.js.map
  116390. var BABYLON;
  116391. (function (BABYLON) {
  116392. /**
  116393. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  116394. * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.
  116395. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  116396. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  116397. */
  116398. var PhotoDome = /** @class */ (function (_super) {
  116399. __extends(PhotoDome, _super);
  116400. /**
  116401. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  116402. * @param name Element's name, child elements will append suffixes for their own names.
  116403. * @param urlsOfPhoto defines the url of the photo to display
  116404. * @param options defines an object containing optional or exposed sub element properties
  116405. * @param onError defines a callback called when an error occured while loading the texture
  116406. */
  116407. function PhotoDome(name, urlOfPhoto, options, scene, onError) {
  116408. if (onError === void 0) { onError = null; }
  116409. var _this = _super.call(this, name, scene) || this;
  116410. _this._useDirectMapping = false;
  116411. /**
  116412. * Observable raised when an error occured while loading the 360 image
  116413. */
  116414. _this.onLoadErrorObservable = new BABYLON.Observable();
  116415. // set defaults and manage values
  116416. name = name || "photoDome";
  116417. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  116418. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  116419. if (options.useDirectMapping === undefined) {
  116420. _this._useDirectMapping = true;
  116421. }
  116422. else {
  116423. _this._useDirectMapping = options.useDirectMapping;
  116424. }
  116425. _this._setReady(false);
  116426. // create
  116427. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  116428. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  116429. // configure material
  116430. material.opacityFresnel = false;
  116431. material.useEquirectangularFOV = true;
  116432. material.fovMultiplier = 1.0;
  116433. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping, undefined, undefined, function (message, exception) {
  116434. _this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured");
  116435. if (onError) {
  116436. onError(message, exception);
  116437. }
  116438. });
  116439. _this.photoTexture.onLoadObservable.addOnce(function () {
  116440. _this._setReady(true);
  116441. });
  116442. // configure mesh
  116443. _this._mesh.material = material;
  116444. _this._mesh.parent = _this;
  116445. return _this;
  116446. }
  116447. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  116448. /**
  116449. * Gets or sets the texture being displayed on the sphere
  116450. */
  116451. get: function () {
  116452. return this._photoTexture;
  116453. },
  116454. set: function (value) {
  116455. if (this._photoTexture === value) {
  116456. return;
  116457. }
  116458. this._photoTexture = value;
  116459. if (this._useDirectMapping) {
  116460. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  116461. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  116462. this._material.diffuseTexture = this._photoTexture;
  116463. }
  116464. else {
  116465. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  116466. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  116467. this._material.reflectionTexture = this._photoTexture;
  116468. }
  116469. },
  116470. enumerable: true,
  116471. configurable: true
  116472. });
  116473. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  116474. /**
  116475. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  116476. * Also see the options.resolution property.
  116477. */
  116478. get: function () {
  116479. return this._material.fovMultiplier;
  116480. },
  116481. set: function (value) {
  116482. this._material.fovMultiplier = value;
  116483. },
  116484. enumerable: true,
  116485. configurable: true
  116486. });
  116487. /**
  116488. * Releases resources associated with this node.
  116489. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  116490. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  116491. */
  116492. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  116493. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  116494. this._photoTexture.dispose();
  116495. this._mesh.dispose();
  116496. this._material.dispose();
  116497. this.onLoadErrorObservable.clear();
  116498. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  116499. };
  116500. return PhotoDome;
  116501. }(BABYLON.TransformNode));
  116502. BABYLON.PhotoDome = PhotoDome;
  116503. })(BABYLON || (BABYLON = {}));
  116504. //# sourceMappingURL=babylon.photoDome.js.map
  116505. var BABYLON;
  116506. (function (BABYLON) {
  116507. /** @hidden */
  116508. var _OcclusionDataStorage = /** @class */ (function () {
  116509. function _OcclusionDataStorage() {
  116510. /** @hidden */
  116511. this.occlusionInternalRetryCounter = 0;
  116512. /** @hidden */
  116513. this.isOcclusionQueryInProgress = false;
  116514. /** @hidden */
  116515. this.isOccluded = false;
  116516. /** @hidden */
  116517. this.occlusionRetryCount = -1;
  116518. /** @hidden */
  116519. this.occlusionType = BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE;
  116520. /** @hidden */
  116521. this.occlusionQueryAlgorithmType = BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  116522. }
  116523. return _OcclusionDataStorage;
  116524. }());
  116525. BABYLON.Engine.prototype.createQuery = function () {
  116526. return this._gl.createQuery();
  116527. };
  116528. BABYLON.Engine.prototype.deleteQuery = function (query) {
  116529. this._gl.deleteQuery(query);
  116530. return this;
  116531. };
  116532. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  116533. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  116534. };
  116535. BABYLON.Engine.prototype.getQueryResult = function (query) {
  116536. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  116537. };
  116538. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  116539. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  116540. this._gl.beginQuery(glAlgorithm, query);
  116541. return this;
  116542. };
  116543. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  116544. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  116545. this._gl.endQuery(glAlgorithm);
  116546. return this;
  116547. };
  116548. BABYLON.Engine.prototype._createTimeQuery = function () {
  116549. var timerQuery = this.getCaps().timerQuery;
  116550. if (timerQuery.createQueryEXT) {
  116551. return timerQuery.createQueryEXT();
  116552. }
  116553. return this.createQuery();
  116554. };
  116555. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  116556. var timerQuery = this.getCaps().timerQuery;
  116557. if (timerQuery.deleteQueryEXT) {
  116558. timerQuery.deleteQueryEXT(query);
  116559. return;
  116560. }
  116561. this.deleteQuery(query);
  116562. };
  116563. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  116564. var timerQuery = this.getCaps().timerQuery;
  116565. if (timerQuery.getQueryObjectEXT) {
  116566. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  116567. }
  116568. return this.getQueryResult(query);
  116569. };
  116570. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  116571. var timerQuery = this.getCaps().timerQuery;
  116572. if (timerQuery.getQueryObjectEXT) {
  116573. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  116574. }
  116575. return this.isQueryResultAvailable(query);
  116576. };
  116577. BABYLON.Engine.prototype.startTimeQuery = function () {
  116578. var caps = this.getCaps();
  116579. var timerQuery = caps.timerQuery;
  116580. if (!timerQuery) {
  116581. return null;
  116582. }
  116583. var token = new BABYLON._TimeToken();
  116584. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  116585. if (caps.canUseTimestampForTimerQuery) {
  116586. token._startTimeQuery = this._createTimeQuery();
  116587. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  116588. }
  116589. else {
  116590. if (this._currentNonTimestampToken) {
  116591. return this._currentNonTimestampToken;
  116592. }
  116593. token._timeElapsedQuery = this._createTimeQuery();
  116594. if (timerQuery.beginQueryEXT) {
  116595. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  116596. }
  116597. else {
  116598. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  116599. }
  116600. this._currentNonTimestampToken = token;
  116601. }
  116602. return token;
  116603. };
  116604. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  116605. var caps = this.getCaps();
  116606. var timerQuery = caps.timerQuery;
  116607. if (!timerQuery || !token) {
  116608. return -1;
  116609. }
  116610. if (caps.canUseTimestampForTimerQuery) {
  116611. if (!token._startTimeQuery) {
  116612. return -1;
  116613. }
  116614. if (!token._endTimeQuery) {
  116615. token._endTimeQuery = this._createTimeQuery();
  116616. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  116617. }
  116618. }
  116619. else if (!token._timeElapsedQueryEnded) {
  116620. if (!token._timeElapsedQuery) {
  116621. return -1;
  116622. }
  116623. if (timerQuery.endQueryEXT) {
  116624. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  116625. }
  116626. else {
  116627. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  116628. }
  116629. token._timeElapsedQueryEnded = true;
  116630. }
  116631. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  116632. var available = false;
  116633. if (token._endTimeQuery) {
  116634. available = this._getTimeQueryAvailability(token._endTimeQuery);
  116635. }
  116636. else if (token._timeElapsedQuery) {
  116637. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  116638. }
  116639. if (available && !disjoint) {
  116640. var result = 0;
  116641. if (caps.canUseTimestampForTimerQuery) {
  116642. if (!token._startTimeQuery || !token._endTimeQuery) {
  116643. return -1;
  116644. }
  116645. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  116646. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  116647. result = timeEnd - timeStart;
  116648. this._deleteTimeQuery(token._startTimeQuery);
  116649. this._deleteTimeQuery(token._endTimeQuery);
  116650. token._startTimeQuery = null;
  116651. token._endTimeQuery = null;
  116652. }
  116653. else {
  116654. if (!token._timeElapsedQuery) {
  116655. return -1;
  116656. }
  116657. result = this._getTimeQueryResult(token._timeElapsedQuery);
  116658. this._deleteTimeQuery(token._timeElapsedQuery);
  116659. token._timeElapsedQuery = null;
  116660. token._timeElapsedQueryEnded = false;
  116661. this._currentNonTimestampToken = null;
  116662. }
  116663. return result;
  116664. }
  116665. return -1;
  116666. };
  116667. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  116668. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  116669. };
  116670. Object.defineProperty(BABYLON.AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  116671. get: function () {
  116672. return this._occlusionDataStorage.isOcclusionQueryInProgress;
  116673. },
  116674. enumerable: false,
  116675. configurable: true
  116676. });
  116677. Object.defineProperty(BABYLON.AbstractMesh.prototype, "_occlusionDataStorage", {
  116678. get: function () {
  116679. if (!this.__occlusionDataStorage) {
  116680. this.__occlusionDataStorage = new _OcclusionDataStorage();
  116681. }
  116682. return this.__occlusionDataStorage;
  116683. },
  116684. enumerable: false,
  116685. configurable: true
  116686. });
  116687. Object.defineProperty(BABYLON.AbstractMesh.prototype, "isOccluded", {
  116688. get: function () {
  116689. return this._occlusionDataStorage.isOccluded;
  116690. },
  116691. set: function (value) {
  116692. this._occlusionDataStorage.isOccluded = value;
  116693. },
  116694. enumerable: true,
  116695. configurable: true
  116696. });
  116697. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionQueryAlgorithmType", {
  116698. get: function () {
  116699. return this._occlusionDataStorage.occlusionQueryAlgorithmType;
  116700. },
  116701. set: function (value) {
  116702. this._occlusionDataStorage.occlusionQueryAlgorithmType = value;
  116703. },
  116704. enumerable: true,
  116705. configurable: true
  116706. });
  116707. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionType", {
  116708. get: function () {
  116709. return this._occlusionDataStorage.occlusionType;
  116710. },
  116711. set: function (value) {
  116712. this._occlusionDataStorage.occlusionType = value;
  116713. },
  116714. enumerable: true,
  116715. configurable: true
  116716. });
  116717. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionRetryCount", {
  116718. get: function () {
  116719. return this._occlusionDataStorage.occlusionRetryCount;
  116720. },
  116721. set: function (value) {
  116722. this._occlusionDataStorage.occlusionRetryCount = value;
  116723. },
  116724. enumerable: true,
  116725. configurable: true
  116726. });
  116727. // We also need to update AbstractMesh as there is a portion of the code there
  116728. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  116729. var dataStorage = this._occlusionDataStorage;
  116730. if (dataStorage.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  116731. dataStorage.isOccluded = false;
  116732. return false;
  116733. }
  116734. var engine = this.getEngine();
  116735. if (engine.webGLVersion < 2) {
  116736. dataStorage.isOccluded = false;
  116737. return false;
  116738. }
  116739. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  116740. dataStorage.isOccluded = false;
  116741. return false;
  116742. }
  116743. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  116744. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  116745. if (isOcclusionQueryAvailable) {
  116746. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  116747. dataStorage.isOcclusionQueryInProgress = false;
  116748. dataStorage.occlusionInternalRetryCounter = 0;
  116749. dataStorage.isOccluded = occlusionQueryResult === 1 ? false : true;
  116750. }
  116751. else {
  116752. dataStorage.occlusionInternalRetryCounter++;
  116753. if (dataStorage.occlusionRetryCount !== -1 && dataStorage.occlusionInternalRetryCounter > dataStorage.occlusionRetryCount) {
  116754. dataStorage.isOcclusionQueryInProgress = false;
  116755. dataStorage.occlusionInternalRetryCounter = 0;
  116756. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  116757. // if strict continue the last state of the object.
  116758. dataStorage.isOccluded = dataStorage.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : dataStorage.isOccluded;
  116759. }
  116760. else {
  116761. return false;
  116762. }
  116763. }
  116764. }
  116765. var scene = this.getScene();
  116766. if (scene.getBoundingBoxRenderer) {
  116767. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  116768. if (!this._occlusionQuery) {
  116769. this._occlusionQuery = engine.createQuery();
  116770. }
  116771. engine.beginOcclusionQuery(dataStorage.occlusionQueryAlgorithmType, this._occlusionQuery);
  116772. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  116773. engine.endOcclusionQuery(dataStorage.occlusionQueryAlgorithmType);
  116774. this._occlusionDataStorage.isOcclusionQueryInProgress = true;
  116775. }
  116776. return dataStorage.isOccluded;
  116777. };
  116778. })(BABYLON || (BABYLON = {}));
  116779. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  116780. var BABYLON;
  116781. (function (BABYLON) {
  116782. /**
  116783. * Class used to generate noise procedural textures
  116784. */
  116785. var NoiseProceduralTexture = /** @class */ (function (_super) {
  116786. __extends(NoiseProceduralTexture, _super);
  116787. /**
  116788. * Creates a new NoiseProceduralTexture
  116789. * @param name defines the name fo the texture
  116790. * @param size defines the size of the texture (default is 256)
  116791. * @param scene defines the hosting scene
  116792. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  116793. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  116794. */
  116795. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  116796. if (size === void 0) { size = 256; }
  116797. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  116798. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  116799. _this._time = 0;
  116800. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  116801. _this.brightness = 0.2;
  116802. /** Defines the number of octaves to process */
  116803. _this.octaves = 3;
  116804. /** Defines the level of persistence (0.8 by default) */
  116805. _this.persistence = 0.8;
  116806. /** Gets or sets animation speed factor (default is 1) */
  116807. _this.animationSpeedFactor = 1;
  116808. _this.autoClear = false;
  116809. _this._updateShaderUniforms();
  116810. return _this;
  116811. }
  116812. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  116813. var scene = this.getScene();
  116814. if (!scene) {
  116815. return;
  116816. }
  116817. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  116818. this.setFloat("brightness", this.brightness);
  116819. this.setFloat("persistence", this.persistence);
  116820. this.setFloat("timeScale", this._time);
  116821. };
  116822. NoiseProceduralTexture.prototype._getDefines = function () {
  116823. return "#define OCTAVES " + (this.octaves | 0);
  116824. };
  116825. /** Generate the current state of the procedural texture */
  116826. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  116827. this._updateShaderUniforms();
  116828. _super.prototype.render.call(this, useCameraPostProcess);
  116829. };
  116830. /**
  116831. * Serializes this noise procedural texture
  116832. * @returns a serialized noise procedural texture object
  116833. */
  116834. NoiseProceduralTexture.prototype.serialize = function () {
  116835. var serializationObject = {};
  116836. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  116837. serializationObject.brightness = this.brightness;
  116838. serializationObject.octaves = this.octaves;
  116839. serializationObject.persistence = this.persistence;
  116840. serializationObject.animationSpeedFactor = this.animationSpeedFactor;
  116841. serializationObject.size = this.getSize().width;
  116842. serializationObject.generateMipMaps = this._generateMipMaps;
  116843. return serializationObject;
  116844. };
  116845. /**
  116846. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  116847. * @param parsedTexture defines parsed texture data
  116848. * @param scene defines the current scene
  116849. * @param rootUrl defines the root URL containing noise procedural texture information
  116850. * @returns a parsed NoiseProceduralTexture
  116851. */
  116852. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  116853. var texture = new NoiseProceduralTexture(parsedTexture.name, parsedTexture.size, scene, undefined, parsedTexture.generateMipMaps);
  116854. texture.brightness = parsedTexture.brightness;
  116855. texture.octaves = parsedTexture.octaves;
  116856. texture.persistence = parsedTexture.persistence;
  116857. texture.animationSpeedFactor = parsedTexture.animationSpeedFactor;
  116858. return texture;
  116859. };
  116860. return NoiseProceduralTexture;
  116861. }(BABYLON.ProceduralTexture));
  116862. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  116863. })(BABYLON || (BABYLON = {}));
  116864. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  116865. var __assign = (this && this.__assign) || function () {
  116866. __assign = Object.assign || function(t) {
  116867. for (var s, i = 1, n = arguments.length; i < n; i++) {
  116868. s = arguments[i];
  116869. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  116870. t[p] = s[p];
  116871. }
  116872. return t;
  116873. };
  116874. return __assign.apply(this, arguments);
  116875. };
  116876. var BABYLON;
  116877. (function (BABYLON) {
  116878. /**
  116879. * This can helps recording videos from BabylonJS.
  116880. * This is based on the available WebRTC functionalities of the browser.
  116881. *
  116882. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_video
  116883. */
  116884. var VideoRecorder = /** @class */ (function () {
  116885. /**
  116886. * Create a new VideoCapture object which can help converting what you see in Babylon to
  116887. * a video file.
  116888. * @param engine Defines the BabylonJS Engine you wish to record
  116889. * @param options Defines options that can be used to customized the capture
  116890. */
  116891. function VideoRecorder(engine, options) {
  116892. if (options === void 0) { options = null; }
  116893. if (!VideoRecorder.IsSupported(engine)) {
  116894. throw "Your browser does not support recording so far.";
  116895. }
  116896. var canvas = engine.getRenderingCanvas();
  116897. if (!canvas) {
  116898. throw "The babylon engine must have a canvas to be recorded";
  116899. }
  116900. this._canvas = canvas;
  116901. this._canvas.isRecording = false;
  116902. this._options = __assign({}, VideoRecorder._defaultOptions, options);
  116903. var stream = this._canvas.captureStream(this._options.fps);
  116904. this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
  116905. this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);
  116906. this._mediaRecorder.onerror = this._handleError.bind(this);
  116907. this._mediaRecorder.onstop = this._handleStop.bind(this);
  116908. }
  116909. /**
  116910. * Returns wehther or not the VideoRecorder is available in your browser.
  116911. * @param engine Defines the Babylon Engine to check the support for
  116912. * @returns true if supported otherwise false
  116913. */
  116914. VideoRecorder.IsSupported = function (engine) {
  116915. var canvas = engine.getRenderingCanvas();
  116916. return (!!canvas && typeof canvas.captureStream === "function");
  116917. };
  116918. Object.defineProperty(VideoRecorder.prototype, "isRecording", {
  116919. /**
  116920. * True wether a recording is already in progress.
  116921. */
  116922. get: function () {
  116923. return !!this._canvas && this._canvas.isRecording;
  116924. },
  116925. enumerable: true,
  116926. configurable: true
  116927. });
  116928. /**
  116929. * Stops the current recording before the default capture timeout passed in the startRecording
  116930. * functions.
  116931. */
  116932. VideoRecorder.prototype.stopRecording = function () {
  116933. if (!this._canvas || !this._mediaRecorder) {
  116934. return;
  116935. }
  116936. if (!this.isRecording) {
  116937. return;
  116938. }
  116939. this._canvas.isRecording = false;
  116940. this._mediaRecorder.stop();
  116941. };
  116942. /**
  116943. * Starts recording the canvas for a max duration specified in parameters.
  116944. * @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.
  116945. * @param maxDuration Defines the maximum recording time in seconds.
  116946. * It default to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.
  116947. * @return a promise callback at the end of the recording with the video data in Blob.
  116948. */
  116949. VideoRecorder.prototype.startRecording = function (fileName, maxDuration) {
  116950. var _this = this;
  116951. if (fileName === void 0) { fileName = "babylonjs.webm"; }
  116952. if (maxDuration === void 0) { maxDuration = 7; }
  116953. if (!this._canvas || !this._mediaRecorder) {
  116954. throw "Recorder has already been disposed";
  116955. }
  116956. if (this.isRecording) {
  116957. throw "Recording already in progress";
  116958. }
  116959. if (maxDuration > 0) {
  116960. setTimeout(function () {
  116961. _this.stopRecording();
  116962. }, maxDuration * 1000);
  116963. }
  116964. this._fileName = fileName;
  116965. this._recordedChunks = [];
  116966. this._resolve = null;
  116967. this._reject = null;
  116968. this._canvas.isRecording = true;
  116969. this._mediaRecorder.start(this._options.recordChunckSize);
  116970. return new Promise(function (resolve, reject) {
  116971. _this._resolve = resolve;
  116972. _this._reject = reject;
  116973. });
  116974. };
  116975. /**
  116976. * Releases internal resources used during the recording.
  116977. */
  116978. VideoRecorder.prototype.dispose = function () {
  116979. this._canvas = null;
  116980. this._mediaRecorder = null;
  116981. this._recordedChunks = [];
  116982. this._fileName = null;
  116983. this._resolve = null;
  116984. this._reject = null;
  116985. };
  116986. VideoRecorder.prototype._handleDataAvailable = function (event) {
  116987. if (event.data.size > 0) {
  116988. this._recordedChunks.push(event.data);
  116989. }
  116990. };
  116991. VideoRecorder.prototype._handleError = function (event) {
  116992. this.stopRecording();
  116993. if (this._reject) {
  116994. this._reject(event.error);
  116995. }
  116996. else {
  116997. throw new event.error();
  116998. }
  116999. };
  117000. VideoRecorder.prototype._handleStop = function () {
  117001. this.stopRecording();
  117002. var superBuffer = new Blob(this._recordedChunks);
  117003. if (this._resolve) {
  117004. this._resolve(superBuffer);
  117005. }
  117006. window.URL.createObjectURL(superBuffer);
  117007. if (this._fileName) {
  117008. BABYLON.Tools.Download(superBuffer, this._fileName);
  117009. }
  117010. };
  117011. VideoRecorder._defaultOptions = {
  117012. mimeType: "video/webm",
  117013. fps: 25,
  117014. recordChunckSize: 3000
  117015. };
  117016. return VideoRecorder;
  117017. }());
  117018. BABYLON.VideoRecorder = VideoRecorder;
  117019. })(BABYLON || (BABYLON = {}));
  117020. //# sourceMappingURL=babylon.videoRecorder.js.map
  117021. var BABYLON;
  117022. (function (BABYLON) {
  117023. BABYLON.Scene.prototype.createDefaultLight = function (replace) {
  117024. if (replace === void 0) { replace = false; }
  117025. // Dispose existing light in replace mode.
  117026. if (replace) {
  117027. if (this.lights) {
  117028. for (var i = 0; i < this.lights.length; i++) {
  117029. this.lights[i].dispose();
  117030. }
  117031. }
  117032. }
  117033. // Light
  117034. if (this.lights.length === 0) {
  117035. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  117036. }
  117037. };
  117038. BABYLON.Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  117039. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  117040. if (replace === void 0) { replace = false; }
  117041. if (attachCameraControls === void 0) { attachCameraControls = false; }
  117042. // Dispose existing camera in replace mode.
  117043. if (replace) {
  117044. if (this.activeCamera) {
  117045. this.activeCamera.dispose();
  117046. this.activeCamera = null;
  117047. }
  117048. }
  117049. // Camera
  117050. if (!this.activeCamera) {
  117051. var worldExtends = this.getWorldExtends();
  117052. var worldSize = worldExtends.max.subtract(worldExtends.min);
  117053. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  117054. var camera;
  117055. var radius = worldSize.length() * 1.5;
  117056. // empty scene scenario!
  117057. if (!isFinite(radius)) {
  117058. radius = 1;
  117059. worldCenter.copyFromFloats(0, 0, 0);
  117060. }
  117061. if (createArcRotateCamera) {
  117062. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  117063. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  117064. arcRotateCamera.wheelPrecision = 100 / radius;
  117065. camera = arcRotateCamera;
  117066. }
  117067. else {
  117068. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  117069. freeCamera.setTarget(worldCenter);
  117070. camera = freeCamera;
  117071. }
  117072. camera.minZ = radius * 0.01;
  117073. camera.maxZ = radius * 1000;
  117074. camera.speed = radius * 0.2;
  117075. this.activeCamera = camera;
  117076. var canvas = this.getEngine().getRenderingCanvas();
  117077. if (attachCameraControls && canvas) {
  117078. camera.attachControl(canvas);
  117079. }
  117080. }
  117081. };
  117082. BABYLON.Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  117083. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  117084. if (replace === void 0) { replace = false; }
  117085. if (attachCameraControls === void 0) { attachCameraControls = false; }
  117086. this.createDefaultLight(replace);
  117087. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  117088. };
  117089. BABYLON.Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  117090. if (pbr === void 0) { pbr = false; }
  117091. if (scale === void 0) { scale = 1000; }
  117092. if (blur === void 0) { blur = 0; }
  117093. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  117094. if (!environmentTexture) {
  117095. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  117096. return null;
  117097. }
  117098. if (setGlobalEnvTexture) {
  117099. if (environmentTexture) {
  117100. this.environmentTexture = environmentTexture;
  117101. }
  117102. }
  117103. // Skybox
  117104. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  117105. if (pbr) {
  117106. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  117107. hdrSkyboxMaterial.backFaceCulling = false;
  117108. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  117109. if (hdrSkyboxMaterial.reflectionTexture) {
  117110. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  117111. }
  117112. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  117113. hdrSkyboxMaterial.disableLighting = true;
  117114. hdrSkyboxMaterial.twoSidedLighting = true;
  117115. hdrSkybox.infiniteDistance = true;
  117116. hdrSkybox.material = hdrSkyboxMaterial;
  117117. }
  117118. else {
  117119. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  117120. skyboxMaterial.backFaceCulling = false;
  117121. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  117122. if (skyboxMaterial.reflectionTexture) {
  117123. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  117124. }
  117125. skyboxMaterial.disableLighting = true;
  117126. hdrSkybox.infiniteDistance = true;
  117127. hdrSkybox.material = skyboxMaterial;
  117128. }
  117129. return hdrSkybox;
  117130. };
  117131. BABYLON.Scene.prototype.createDefaultEnvironment = function (options) {
  117132. if (BABYLON.EnvironmentHelper) {
  117133. return new BABYLON.EnvironmentHelper(options, this);
  117134. }
  117135. return null;
  117136. };
  117137. BABYLON.Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  117138. if (webVROptions === void 0) { webVROptions = {}; }
  117139. return new BABYLON.VRExperienceHelper(this, webVROptions);
  117140. };
  117141. })(BABYLON || (BABYLON = {}));
  117142. //# sourceMappingURL=babylon.sceneHelpers.js.map
  117143. 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\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nfloat scales[16]=float[16](\n0.1,\n0.11406250000000001,\n0.131640625,\n0.15625,\n0.187890625,\n0.2265625,\n0.272265625,\n0.325,\n0.384765625,\n0.4515625,\n0.525390625,\n0.60625,\n0.694140625,\n0.7890625,\n0.891015625,\n1.0\n);\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\n\nfloat dotProduct=dot(rvec,normal);\nrvec=1.0-abs(dotProduct)>1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=scales[(i+int(random.x*16.0)) % 16]*tbn*sampleSphere[(i+int(random.y*16.0)) % 16];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\ndifference=depthSign*samplePosition.z-sampleDepth;\nfloat rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);\nocclusion+=(difference>=0.0 ? 1.0 : 0.0)*rangeCheck;\n}\nocclusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\n\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n","noisePixelShader":"\n\nuniform float brightness;\nuniform float persistence;\nuniform float timeScale;\n\nvarying vec2 vUV;\n\nvec2 hash22(vec2 p)\n{\np=p*mat2(127.1,311.7,269.5,183.3);\np=-1.0+2.0*fract(sin(p)*43758.5453123);\nreturn sin(p*6.283+timeScale);\n}\nfloat interpolationNoise(vec2 p)\n{\nvec2 pi=floor(p);\nvec2 pf=p-pi;\nvec2 w=pf*pf*(3.-2.*pf);\nfloat f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));\nfloat f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));\nfloat f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));\nfloat f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));\nfloat xm1=mix(f00,f10,w.x);\nfloat xm2=mix(f01,f11,w.x);\nfloat ym=mix(xm1,xm2,w.y); \nreturn ym;\n}\nfloat perlinNoise2D(float x,float y)\n{\nfloat sum=0.0;\nfloat frequency=0.0;\nfloat amplitude=0.0;\nfor(int i=0; i<OCTAVES; i++)\n{\nfrequency=pow(2.0,float(i));\namplitude=pow(persistence,float(i));\nsum=sum+interpolationNoise(vec2(x*frequency,y*frequency))*amplitude;\n}\nreturn sum;\n}\n\nvoid main(void)\n{\nfloat x=abs(vUV.x);\nfloat y=abs(vUV.y);\nfloat noise=brightness+(1.0-brightness)*perlinNoise2D(x,y);\ngl_FragColor=vec4(noise,noise,noise,1.0);\n}\n"};
  117144. 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};"};
  117145. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  117146. globalObject["BABYLON"] = BABYLON;
  117147. //backwards compatibility
  117148. if(typeof earcut !== 'undefined') {
  117149. globalObject["Earcut"] = {
  117150. earcut: earcut
  117151. };
  117152. }
  117153. return BABYLON;
  117154. });